<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>jmglov's blog</title>
  <subtitle>A blog about stuff but also things.</subtitle>
  <link href="https://jmglov.net/blog/atom.xml" rel="self"/>
  <link href="https://jmglov.net/blog/"/>
  <updated>2026-11-08T10:14:33+00:00</updated>
  <id>https://jmglov.net/blog/</id>
  <author>
    <name>Josh Glover</name>
  </author>
  <entry>
    <id>https://jmglov.net/blog/2026-11-07-persistence.html</id>
    <link href="https://jmglov.net/blog/2026-11-07-persistence.html"/>
    <title>Scittlecastr: All You Need is Persistence</title>
    <updated>2026-11-07T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="Teenager writing HTML on chalk board" src="assets/2026-11-07-persistence-preview.jpg" title="Photo by by Rafa Fernandez from Noun Project" /></p><p><em>This post was entirely written by a human, with no assistance from LLMs or other &quot;AI&quot; technology such as pervert glasses or autonomous weapon systems.</em></p><p>Last time on <a href="2026-11-01-scittlecastr.html">Scittlecastr: The Scittling</a>, we scittled up a podcast player, using the awesome power of the ClojureScript REPL.</p><p>What we found great about this approach was the ability to create HTML elements on the fly and update the page without having to reload, but at the end of our session, we were struck by the fear that if we do reload, we will lose all the state of our running program.</p><p>Before we grit our teeth and test our hypothesis, I present to you a</p><div class="markdown-heading"><h2 id="table-of-contents">Table of contents</h2><a href="#table-of-contents" class="anchor" aria-label="Permalink: Table of contents"><img src="assets/link.svg" /></a></div><ol start="1"><li><a href="#shoot-outside-of-the-screen-to-reload">Shoot outside of the screen to
   reload</a> - writing functions to get the tag name and attributes of DOM elements</li><li><a href="#data-is-elemental">Data is elemental</a> - turning DOM nodes into Clojure maps</li><li><a href="#the-resurrection">The resurrection</a> - rebuilding the podcast player in the REPL</li><li><a href="#it&apos;s-an-unstable-era">It&apos;s an unstable era</a> - starting to turn the DOM into HTML</li><li><a href="#textual-healing">Textual healing</a> - handling text nodes</li><li><a href="#html-at-last">HTML at last</a> - finally transforming the entire DOM into HTML</li><li><a href="#plausible-deniability">Plausible deniability</a> - filtering out DOM elements added by extensions</li><li><a href="#indenting-for-fun-and-profit">Indenting for fun and profit</a> - indenting generated HTML nicely</li><li><a href="#shaving-that-final-yak">Shaving that final yak</a> - saving the HTML to a file</li><li><a href="#button-mashing">Button mashing</a> - making the buttons work on page reload</li><li><a href="#atomic-elbow">Atomic elbow</a> - introducing state</li><li><a href="#what-has-css-ever-done-for-us-anyway?">What has CSS ever done for us
    anyway?</a> - generating CSS from inline styles</li><li><a href="#it’s-your-birthday.-someone-gives-you-a-calfskin-wallet.">It’s your birthday. Someone gives you a calfskin
    wallet.</a> - grouping styles by class</li><li><a href="#inline-skating-away-on-the-thin-ice-of-a-new-day">Inline skating away on the thin ice of a new
    day</a> - switching from inline styles to an external stylesheet</li></ol><div class="markdown-heading"><h2 id="shoot-outside-of-the-screen-to-reload">Shoot outside of the screen to reload</h2><a href="#shoot-outside-of-the-screen-to-reload" class="anchor" aria-label="Permalink: Shoot outside of the screen to reload"><img src="assets/link.svg" /></a></div><p>OK, with that housekeeping out of the way, let&apos;s screw our courage to the sticking point and reload the page:</p><p><img alt="Blank webpage" src="assets/2026-11-07-persistence-reloaded.png" title="Where did my stuff go?" class="border" /></p><p>😭😭😭</p><p>The Buddha spake wisely when he claimed that life is a vale of tears. However, we have achieved satori through Scittle, so we discard our fragile ego and expand our consciousness to encompass all things, and discover wisdom in the infinite.</p><p>This wisdom was that of having done our interactive development in a Rich comment, thus allowing us build our interface back up by evaluating our <code>player.cljs</code> buffer, then stepping through the Rich comment, evaluating each form one by one (you can use <code>cider-eval-last-sexp</code> (<strong>C-c C-e</strong>) for this, since you don&apos;t need the comment inserted again). Let&apos;s rebuild our initial ugly player, using our slick new functions.</p><p>Make sure to evaluate the entire buffer after a page reload (<strong>C-c C-k</strong>), or you&apos;ll get an error similar to this the first time you try to evaluate a form in the REPL:</p><pre><code class="language-clojure">(comment

  ;; ...

  (get-el &quot;body&quot;)
  ;; =&gt; &quot;#error {:message \&quot;Unable to resolve symbol: get-el\&quot;,
  ;;             :data {:type :sci/error, :line 1, :column 1, ...}}

  )
</code></pre><p>Having evaluated the buffer, let&apos;s get ugly!</p><pre><code class="language-clojure">(comment

  ;; ...

  (set-children! &quot;body&quot;
                 [(create-el {:tag &quot;h1&quot;
                              :classes [&quot;cljcastr&quot;]
                              :text &quot;cljcastr player&quot;})
                  (create-el {:tag &quot;audio&quot;
                              :classes [&quot;cljcastr&quot;]
                              :attrs {:controls true
                                      :src &quot;https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3&quot;}})])
  ;; =&gt; #object[HTMLBodyElement [object HTMLBodyElement]]

  )
</code></pre><p>That is quite a pain, though. Is there a way to effectively export the running program as HTML so we could save it to our <code>index.html</code>? Well, let&apos;s give it a go.</p><p>What we&apos;d like is to turn the <strong>body</strong> DOM node into an HTML fragment. We can actually already do this in a clunky way. We log the element:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (get-el &quot;body&quot;)
      log)
  ;; =&gt; #object[HTMLBodyElement [object HTMLBodyElement]]

  )
</code></pre><p>and then look at the console:</p><p><img alt="JavaScript console with body element and children" src="assets/2026-11-07-persistence-boring.png" title="Nice HTML you got there" class="border" /></p><p>Unfortunately, we can&apos;t directly use the console output in the REPL. We could of course just copy and paste it from the console window, but that feels too efficient, and we&apos;d rather spend some time shaving those yaks, so let&apos;s think about how we might generate our own HTML from the DOM tree anchored at the <strong>body</strong> element.</p><p>First, we need to do a depth-first traversal of the children of <strong>body</strong>. This is quite easy for the time being, since body only has children and no grandchildren or great-grandchildren or whatever. Let&apos;s try to count those children:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def children (-&gt; (get-children &quot;body&quot;)
                    log))
  ;; =&gt; #&apos;cljcastr.player/children

  (count children)
  ;; =&gt; 3

  )
</code></pre><p>Wait, what&apos;s going on here? The JS console actually holds the key. If we look in the console at the previously logged line and expand it, we see:</p><pre><code class="language-text">  ▼ (2) [h1.cljcastr, audio.cljcastr, protonpass-root-64f9] ℹ        nrepl.cljs:10
    ‣ 0: h1.cljcastr
    ‣ 1: audio.cljcastr
    ‣ 2: protonpass-root-64f9
      length: 2
    ‣ [[Prototype]]: Array(0)
</code></pre><p>Looks like my <a href="https://proton.me/pass">Proton Pass</a> extension is adding an element to the body. 😬</p><p>But luckily, we added the <code>cljcastr</code> class to all our elements, so we can use a <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors">CSS
selector</a> to limit the children to the ones we actually put there ourselves:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def children (-&gt; (js/document.querySelectorAll &quot;body &gt; .cljcastr&quot;)
                    seq
                    log))
  ;; =&gt; #&apos;cljcastr.player/children

  (count children)
  ;; =&gt; 2

  )
</code></pre><p>Excellent! Now let&apos;s see what the element names of the children are:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; children
       (map get-name)
       log)
  ;; =&gt; (&quot;h1&quot; &quot;audio&quot;)

  )
</code></pre><p>And their attributes?</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (-&gt;&gt; children
       (map #(.-attributes %))
       log)
  ;; =&gt; (#object[NamedNodeMap [object NamedNodeMap]]
  ;;     #object[NamedNodeMap [object NamedNodeMap]])

  )
</code></pre><p>Ah yes, thank you for not using a POJSO (Plain &apos;Ol JavaScript Object, ofc) there. I guess we&apos;ll need some sort of function to turn a <a href="https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap">NamedNodeMap</a> into a Clojure map. No matter, we can write some simple Clojure to fix this:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (-&gt;&gt; children
       (map (fn [el]
              (let [attrs (.-attributes el)]
                (-&gt;&gt; (range (.-length attrs))
                     (map #(let [attr (.item attrs %)]
                             [(-&gt; (.-name attr) keyword) (.-value attr)]))
                     (into {})))))
       log)
  ;; =&gt; ({:class &quot;cljcastr&quot;}
  ;;     {:controls &quot;true&quot;,
  ;;      :src &quot;https://media.zencastr.com/audio-files/...&quot;,
  ;;      :class &quot;cljcastr&quot;})

  )
</code></pre><p>Um. This is... yeah. I think it&apos;s time to write a few functions to decomplect this mess. Let&apos;s head back up to the top of the file and add a few little functions:</p><pre><code class="language-clojure">(ns cljcastr.player)

;; ...
;; (defn get-attr ...)

(defn attr-&gt;clj
  &quot;Given an entry in an attribute map (i.e. `Attr` in a `NamedNodeMap` that is
   the value of the `.-attributes` property of an element), returns a vector of
   the name (as a keyword) and value of the attribute.&quot;
  [attr]
  [(-&gt; (.-name attr) keyword) (.-value attr)])

(defn get-attrs
  &quot;Returns the attributes of an element as a map of attribute names (as keywords)
   to attribute values.&quot;
  [el]
  (let [el (get-el el)
        attrs (.-attributes el)]
    (-&gt;&gt; (range (.-length attrs))
         (map #(-&gt;&gt; % (.item attrs) attr-&gt;clj))
         (into {}))))

;; (defn set-attr! ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; children
       (map get-attrs)
       log)
  ;; =&gt; ({:class &quot;cljcastr&quot;}
  ;;     {:controls &quot;true&quot;,
  ;;      :src &quot;https://media.zencastr.com/audio-files/...&quot;,
  ;;      :class &quot;cljcastr&quot;})

  )
</code></pre><p>Now that we know how to get both the name of the tag and its attributes, let&apos;s combine them into a function that we can use to map over a list of elements and transform them into a nice Clojurey data structure.</p><div class="markdown-heading"><h2 id="data-is-elemental">Data is elemental</h2><a href="#data-is-elemental" class="anchor" aria-label="Permalink: Data is elemental"><img src="assets/link.svg" /></a></div><p>Climbing into our hammock ever so briefly, we sketch out the following:</p><pre><code class="language-clojure">{:tag &quot;{{tag-name}}&quot;
 :attrs {:k1 &quot;{{v1}}&quot;
         :k2 &quot;{{v2}}&quot;}}
</code></pre><p>Given this data structure and the functions we&apos;ve already written, it&apos;s not too difficult to write the code:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (-&gt;&gt; children
       (map (fn [el]
              {:tag (get-name el)
               :attrs (get-attrs el)}))
       log)
  ;; =&gt; ({:tag &quot;h1&quot;, :attrs {:class &quot;cljcastr&quot;}}
  ;;     {:tag &quot;audio&quot;,
  ;;      :attrs {:controls &quot;true&quot;,
  ;;              :src &quot;https://media.zencastr.com/audio-files/...&quot;,
  ;;              :class &quot;cljcastr&quot;}})

  )
</code></pre><p>The only thing missing from this is the inner text for the <strong>h1</strong> element. Let&apos;s add a <code>:text</code> key to our map for elements that have text:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (-&gt;&gt; children
       (map (fn [el]
              (let [text (get-text el)]
                (merge {:tag (get-name el)
                        :attrs (get-attrs el)}
                       (when-not (empty? text)
                         {:text text})))))
       log)
  ;; =&gt; ({:tag &quot;h1&quot;, :attrs {:class &quot;cljcastr&quot;}, :text &quot;cljcastr player&quot;}
  ;;     {:tag &quot;audio&quot;,
  ;;      :attrs {:controls &quot;true&quot;,
  ;;              :src &quot;https://media.zencastr.com/audio-files/...&quot;,
  ;;              :class &quot;cljcastr&quot;}})

  )
</code></pre><p>Let&apos;s turn this into a nice function, and whilst we&apos;re at it, add all of the keys that <code>create-el</code> takes. We also want to handle the case where the function is called with a Clojure representation of an element (i.e. a map), in which case it should just return the map:</p><pre><code class="language-clojure">(ns cljcastr.player)

;; ...
;; (defn add-style! ...)

(defn el-&gt;clj
  &quot;Given an HTML element, returns a map containing :tag, :id, :classes, :styles,
   :text, and :attrs.&quot;
  [el]
  (if (map? el)
    el
    (let [el (get-el el)]
      (-&gt;&gt; {:tag (get-name el)
            :id (get-id el)
            :classes (get-classes el)
            :styles (get-styles el)
            :text (get-text el)
            :attrs (get-attrs el)}
           (remove (fn [[_ v]] (empty? v)))
           (into {})))))

;; (defn create-el ...)
;; ...

(comment

  ;; ...
  
  (-&gt;&gt; children
       (map el-&gt;clj)
       log)
  ;; =&gt; ({:tag &quot;h1&quot;,
  ;;      :classes (&quot;cljcastr&quot;),
  ;;      :text &quot;cljcastr player&quot;,
  ;;      :attrs {:class &quot;cljcastr&quot;}}
  ;;     {:tag &quot;audio&quot;,
  ;;      :classes (&quot;cljcastr&quot;),
  ;;      :attrs {:controls &quot;true&quot;,
  ;;              :src &quot;https://media.zencastr.com/audio-files/...&quot;,
  ;;              :class &quot;cljcastr&quot;}})

  )
</code></pre><p>I wonder if we can roundtrip an element to a map back to an element?</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (create-el {:tag &quot;button&quot;
                   :id &quot;button-play&quot;
                   :classes [&quot;cljcastr&quot; &quot;playback-button&quot;]
                   :styles {:padding &quot;0px&quot;
                            :margin &quot;0px&quot;
                            :border &quot;0px&quot;
                            :background &quot;transparent&quot;
                            :cursor &quot;pointer&quot;}
                   :attrs {:aria-label &quot;Play&quot;}})
       el-&gt;clj
       create-el
       log)
  ;; =&gt; #object[HTMLButtonElement [object HTMLButtonElement]]

  )
</code></pre><p>Looking good! From this, it&apos;s pretty straightforward to turn this into an HTML string:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (-&gt;&gt; children
       (map el-&gt;clj)
       (map (fn [{:keys [tag attrs text]}]
              (let [attrs-str (if (empty? attrs)
                                &quot;&quot;
                                (str &quot; &quot;
                                     (-&gt;&gt; attrs
                                          (map (fn [[k v]] (str (name k) &quot;=\&quot;&quot; v &quot;\&quot;&quot;)))
                                          (str/join &quot; &quot;))))]
                (str &quot;&lt;&quot; tag attrs-str &quot;&gt;&quot; text &quot;&lt;/&quot; tag &quot;&gt;&quot;))))
       (str/join &quot;\n&quot;)
       log)
  ;; =&gt; &quot;&lt;h1 class=\&quot;cljcastr\&quot;&gt;cljcastr player&lt;/h1&gt;\n
  ;;     &lt;audio controls=\&quot;true\&quot;
  ;;       src=\&quot;https://media.zencastr.com/audio-files/...\&quot;
  ;;       class=\&quot;cljcastr\&quot;&gt;&lt;/audio&gt;&quot;

  )
</code></pre><p>That looks pretty reasonable, so let&apos;s extract a few functions:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el-&gt;clj ...)

(defn attrs-&gt;str
  &quot;Given a map of attributes, returns a string of k=\&quot;v\&quot;...&quot;
  [attrs]
  (-&gt;&gt; attrs
       (map (fn [[k v]] (str (name k) &quot;=\&quot;&quot; v &quot;\&quot;&quot;)))
       (str/join &quot; &quot;)))

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  [el]
  (let [{:keys [tag attrs text]} (if (map? el) el (el-&gt;clj el))
        attrs-str (attrs-&gt;str attrs)]
    (str &quot;&lt;&quot; tag (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str)) &quot;&gt;&quot;
         text
         &quot;&lt;/&quot; tag &quot;&gt;&quot;)))

;; (defn create-el ...)
;; ...

(comment

  ;; ...
  
  (-&gt;&gt; children
       (map el-&gt;html)
       (str/join &quot;\n&quot;)
       log)
  ;; =&gt; &quot;&lt;h1 class=\&quot;cljcastr\&quot;&gt;cljcastr player&lt;/h1&gt;\n
  ;;     &lt;audio controls=\&quot;true\&quot;
  ;;       src=\&quot;https://media.zencastr.com/audio-files/...\&quot;
  ;;       class=\&quot;cljcastr\&quot;&gt;&lt;/audio&gt;&quot;

  )
</code></pre><p>Just as we&apos;re about to paste our HTML into <code>index.html</code>, a thought occurs to us. We wrote some mucky DOM-tacular JS-interop code to create elements, but now we have an elegant Clojure data structure to describe our elements, and we can turn that into HTML, so why not into DOM nodes as well?</p><p>Well, given the way we&apos;ve built up our functions for dealing with the DOM, it turns out we can do this easily!</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (create-el {:tag &quot;h1&quot;, :attrs {:class &quot;cljcastr&quot;}, :text &quot;cljcastr player&quot;})
      log)
  ;; =&gt; #object[HTMLHeadingElement [object HTMLHeadingElement]]
  
  )
</code></pre><p>Looking at the browser console, we&apos;re convinced we&apos;re onto something:</p><pre><code class="language-text">  &lt;h1 class=&quot;cljcastr&quot;&gt;cljcastr player&lt;/h1&gt;                          nrepl.cljs:10
</code></pre><p>Looks great! Now that we have a nicer way to build up elements interactively, as well as a way to dehydrate elements into HTML, let&apos;s think about what it would take to dehydrate the entire DOM tree rooted at our <strong>body</strong> tag.</p><p>We pretty much have everything we need:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;body &gt; .cljcastr&quot;)
       (map el-&gt;html)
       (str/join &quot;\n&quot;)
       log)
  ;; =&gt; &quot;&lt;h1 class=\&quot;cljcastr\&quot;&gt;cljcastr player&lt;/h1&gt;\n
  ;;     &lt;audio controls=\&quot;true\&quot;
  ;;       src=\&quot;https://media.zencastr.com/audio-files/...\&quot;
  ;;       class=\&quot;cljcastr\&quot;&gt;&lt;/audio&gt;&quot;

  )
</code></pre><p>This looks great, so let&apos;s build the full podcast player we had before back up in our REPL and try dehydrating that into HTML. Might as well reload the page to make sure we&apos;re starting out with a pristine REPL. Remember to eval the buffer (<strong>C-c C-k</strong>) after reloading!</p><div class="markdown-heading"><h2 id="the-resurrection">The resurrection</h2><a href="#the-resurrection" class="anchor" aria-label="Permalink: The resurrection"><img src="assets/link.svg" /></a></div><p>To rebuild our player, we could just step through the entire Rich comment from the beginning, evaluating each form one by one, but this sounds like a lot of work! Let&apos;s add a new <code>add-attrs!</code> function and another adornment to our <code>create-el</code> function to make life easier on ourselves:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-attrs! ...)
;; ...

(defn add-attrs! [el attrs]
  (let [el (get-el el)]
    (set-attrs! el (merge (get-attrs el) attrs))))

;; (defn get-id ...)
;; ...
;; (defn el-&gt;html ...)

(defn create-el [{:keys [tag id classes styles text attrs children] :as args}]
  (-&gt; (js/document.createElement tag)
      (set-attrs! attrs)
      (set-id! id)
      (set-classes! classes)
      (set-styles! styles)
      (set-children! children)
      (set-text! text)))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (create-el {:tag &quot;div&quot;
                   :id &quot;episode-container&quot;
                   :classes [&quot;cljcastr&quot;]
                   :styles {:width &quot;100%&quot;
                            :display &quot;flex&quot;
                            :flex-direction &quot;column&quot;
                            :align-items &quot;center&quot;}
                   :children
                   [
                    ;; episode-info
                    (create-el {:tag &quot;div&quot;
                                :id &quot;episode-info&quot;
                                :classes [&quot;cljcastr&quot;]
                                :styles {:max-width &quot;420px&quot;
                                         :text-align &quot;center&quot;}
                                :children
                                [(create-el {:tag &quot;h3&quot;
                                             :id &quot;podcast-title&quot;
                                             :classes [&quot;cljcastr&quot;]
                                             :text &quot;defn&quot;})
                                 (create-el {:tag &quot;h2&quot;
                                             :id &quot;episode-title&quot;
                                             :classes [&quot;cljcastr&quot;]
                                             :text &quot;876b4c306172 Cora Sutton&quot;})
                                 (create-el {:tag &quot;span&quot;
                                             :id &quot;episode-date&quot;
                                             :classes [&quot;cljcastr&quot;]
                                             :styles {:color &quot;grey&quot;}
                                             :text &quot;July 9, 2025&quot;})]})

                    ;;episode-art
                    (create-el {:tag &quot;div&quot;
                                :id &quot;episode-art-container&quot;
                                :classes [&quot;cljcastr&quot;]
                                :children
                                [(create-el {:tag &quot;img&quot;
                                             :id &quot;episode-art&quot;
                                             :classes [&quot;cljcastr&quot;]
                                             :styles {:width &quot;400px&quot;
                                                      :border-radius &quot;5%&quot;
                                                      :padding &quot;10px&quot;}
                                             :attrs {:src &quot;https://media.zencastr.com/image-files/5d9048546bacd9001de88f1c/a5b922ac-7294-4d58-9a33-4308f5d4f50b.png&quot;}})]})

                    ;;audio
                    (-&gt; (create-el {:tag &quot;audio&quot;
                                    :classes [&quot;cljcastr&quot;]
                                    :attrs {:controls true
                                            :src &quot;https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3&quot;}
                                    :styles {:display &quot;none&quot;}})
                        (add-event-listener! &quot;timeupdate&quot;
                                             (fn [ev]
                                               (let [audio (.-target ev)]
                                                 (update-playback-position-indicators!
                                                  (.-currentTime audio) (.-duration audio)
                                                  {:elapsed-time &quot;#elapsed-time&quot;
                                                   :remaining-time &quot;#remaining-time&quot;
                                                   :progress-slider &quot;#progress-slider&quot;
                                                   :progress-bar &quot;#progress-bar&quot;})))))

                    ;;progress
                    (create-el {:tag &quot;div&quot;
                                :id &quot;progress&quot;
                                :classes [&quot;cljcastr&quot;]
                                :styles {:width &quot;390px&quot;
                                         :margin &quot;1.5em auto 0 auto&quot;}
                                :children
                                [(create-el {:tag &quot;span&quot;
                                             :text (secs-&gt;ts 0)
                                             :classes [&quot;cljcastr&quot;]
                                             :id &quot;elapsed-time&quot;
                                             :styles {:margin &quot;0 5px 0 5px&quot;
                                                      :font-size &quot;0.7rem&quot;
                                                      :color &quot;grey&quot;
                                                      :float &quot;left&quot;}})
                                 (create-el {:tag &quot;span&quot;
                                             :text (secs-&gt;ts 0)
                                             :classes [&quot;cljcastr&quot;]
                                             :id &quot;remaining-time&quot;
                                             :styles {:margin &quot;0 5px 0 5px&quot;
                                                      :font-size &quot;0.7rem&quot;
                                                      :color &quot;grey&quot;
                                                      :float &quot;right&quot;}})
                                 (create-el {:tag &quot;div&quot;
                                             :id &quot;progress-container&quot;
                                             :classes [&quot;cljcastr&quot;]
                                             :styles {:position &quot;relative&quot;
                                                      :height &quot;28px&quot;
                                                      :clear &quot;both&quot;}
                                             :children
                                             [(create-el {:tag &quot;progress&quot;
                                                          :id &quot;progress-bar&quot;
                                                          :classes [&quot;cljcastr&quot;]
                                                          :attrs {:min 0
                                                                  :max 0
                                                                  :value 0}
                                                          :styles {:appearance &quot;none&quot;
                                                                   :height &quot;8px&quot;
                                                                   :width &quot;100%&quot;
                                                                   :border &quot;0&quot;
                                                                   :border-radius &quot;4px&quot;
                                                                   :margin &quot;0&quot;
                                                                   :overflow &quot;hidden&quot;
                                                                   :background-color &quot;lightgray&quot;
                                                                   :color &quot;#f7931e&quot;
                                                                   :position &quot;absolute&quot;
                                                                   :top &quot;10px&quot;
                                                                   :left &quot;0px&quot;
                                                                   :z-index 0}})
                                              (create-el {:tag &quot;input&quot;
                                                          :id &quot;progress-slider&quot;
                                                          :classes [&quot;cljcastr&quot;]
                                                          :attrs {:type &quot;range&quot;
                                                                  :min 0
                                                                  :max 0
                                                                  :value 0
                                                                  :step &quot;any&quot;
                                                                  :aria-label &quot;Seek&quot;
                                                                  :aria-valuetext (str (secs-&gt;ts 0)
                                                                                       &quot; of &quot;
                                                                                       (secs-&gt;ts 0))
                                                                  :aria-valuemax 0}
                                                          :styles {:appearance &quot;none&quot;
                                                                   :cursor &quot;pointer&quot;
                                                                   :height &quot;28px&quot;
                                                                   :width &quot;100%&quot;
                                                                   :border &quot;0&quot;
                                                                   :margin &quot;0&quot;
                                                                   :touch-action &quot;manipulation&quot;
                                                                   :position &quot;absolute&quot;
                                                                   :top &quot;0px&quot;
                                                                   :left &quot;0px&quot;
                                                                   :z-index 1
                                                                   :background-color &quot;transparent&quot;}})]})]})

                    ;;playback-controls
                    (create-el {:tag &quot;div&quot;
                                :id &quot;playback-controls&quot;
                                :classes [&quot;cljcastr&quot;]
                                :children
                                (-&gt;&gt; [:backward :play :pause :forward :speed]
                                     (map (fn [button-name]
                                            [button-name (get playback-controls button-name)]))
                                     (map (fn [[button-name button]]
                                            (let [button-el (create-button button-name button
                                                                           {:seek-dur-sec seek-dur-sec
                                                                            :button-class &quot;playback-button&quot;
                                                                            :img-class &quot;playback-icon&quot;})]
                                              (-&gt; (get-children button-el)
                                                  first
                                                  (set-styles! {:width &quot;35px&quot;
                                                                :filter (str &quot;invert(59%) sepia(92%) saturate(611%) &quot;
                                                                             &quot;hue-rotate(343deg) brightness(97%) contrast(99%)&quot;)}))
                                              button-el))) log)})]})
       log
       list
       (set-children! &quot;body&quot;))
  ;; =&gt; #object[HTMLBodyElement [object HTMLBodyElement]]

  (let [audio (get-el &quot;audio.cljcastr&quot;)]
    (set-text! &quot;#elapsed-time&quot; (secs-&gt;ts (.-currentTime audio)))
    (set-text! &quot;#remaining-time&quot; (secs-&gt;ts (- (.-duration audio)
                                              (.-currentTime audio))))
    (add-attrs! &quot;#progress-bar&quot; {:max (.-duration audio)
                                 :value (.-currentTime audio)})
    (add-attrs! &quot;#progress-slider&quot; {:max (.-duration audio)
                                    :value (.-currentTime audio)
                                    :aria-valuetext (str (secs-&gt;ts (.-currentTime audio))
                                                         &quot; of &quot;
                                                         (secs-&gt;ts (.-duration audio)))
                                    :aria-valuemax (.-duration audio)}))
  ;; =&gt; #object[HTMLInputElement [object HTMLInputElement]]
  
  )
</code></pre><p>Much like Lazarus, our podcast player hath now been resurrected! And also like Lazarus, the method of resurrection required divine powers. But fear not! for this shall be the last time we rely on the divine to rebuild our player.</p><div class="markdown-heading"><h2 id="it&apos;s-an-unstable-era">It&apos;s an unstable era</h2><a href="#it&apos;s-an-unstable-era" class="anchor" aria-label="Permalink: It&apos;s an unstable era"><img src="assets/link.svg" /></a></div><p>Let&apos;s get back to dehydration, shall we? We can use the same method as before, when we had a really simple player:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;body &gt; .cljcastr&quot;)
       (map el-&gt;html)
       (str/join &quot;\n&quot;)
       log)
  ;; =&gt; &quot;&lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot;
  ;;       style=\&quot;width: 100%; display: flex; flex-direction: column;
  ;;       align-items: center;\&quot;&gt;
  ;;       defn876b4c306172 Cora SuttonJuly 9, 202500:001:29:30&lt;/div&gt;&quot;

  )
</code></pre><p>Hrm, that&apos;s not very helpful. First of all, we&apos;re only getting the direct children of our <strong>body</strong> element, which in this case is a single child: the <code>episode-container</code> div. What we&apos;d actually like is the entire tree of elements rooted at body.</p><p>Let&apos;s see if we can figure out how to do that.</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;body &gt; .cljcastr&quot;)
       (map (fn [el]
              (let [{:keys [tag attrs text]} (if (map? el) el (el-&gt;clj el))
                    attrs-str (attrs-&gt;str attrs)
                    tag-open (str &quot;  &lt;&quot; tag (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str)) &quot;&gt;&quot;)
                    tag-close (str &quot;&lt;/&quot; tag &quot;&gt;&quot;)
                    children (get-children el)]
                (if (seq children)
                  (str/join &quot;\n&quot;
                            (concat [tag-open]
                                    (map el-&gt;html children)
                                    [tag-close]))
                  (str tag-open text tag-close)))))
       (str/join &quot;\n&quot;)
       log)
  ;; =&gt; &quot;&lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot; style=\&quot;...\&quot;&gt;\n
  ;;       &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;...\&quot;&gt;defn876b4c306172 Cora SuttonJuly 9, 2025&lt;/div&gt;\n
  ;;       &lt;div id=\&quot;episode-art-container\&quot; class=\&quot;cljcastr\&quot;&gt;&lt;/div&gt;\n
  ;;       &lt;audio controls=\&quot;true\&quot; src=\&quot;https://media.zencastr.com/audio-files/...\&quot; class=\&quot;cljcastr\&quot; style=\&quot;display: none;\&quot;&gt;&lt;/audio&gt;\n
  ;;       &lt;div id=\&quot;progress\&quot; class=\&quot;cljcastr\&quot; style=\&quot;...\&quot;&gt;00:37-1:28:53&lt;/div&gt;\n
  ;;       &lt;div id=\&quot;playback-controls\&quot; class=\&quot;cljcastr\&quot;&gt;&lt;/div&gt;\n
  ;;       &lt;/div&gt;&quot;

  )
</code></pre><p>OK, this is progress, but we&apos;re only grabbing the first level of children. In order to include grandchildren and great-grandchildren and great-great-grandchildren (and so on to the last syllable of recorded time), we&apos;ll need to include our new code in <code>el-&gt;html</code> itself:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs-&gt;str ...)

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  [el]
  (let [{:keys [tag attrs text]} (if (map? el) el (el-&gt;clj el))
        attrs-str (attrs-&gt;str attrs)
        tag-open (str &quot;  &lt;&quot; tag (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str)) &quot;&gt;&quot;)
        tag-close (str &quot;&lt;/&quot; tag &quot;&gt;&quot;)
        children (get-children el)]
    (if (seq children)
      (str/join &quot;\n&quot;
                (concat [tag-open]
                        (map el-&gt;html children)
                        [tag-close]))
      (str tag-open text tag-close))))

;; (defn create-el ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;body &gt; .cljcastr&quot;)
       (map el-&gt;html)
       (str/join &quot;\n&quot;)
       log)
  ;; =&gt; &quot;#error {:message \&quot;Failed to execute &apos;querySelector&apos; on &apos;Document&apos;:
  ;;                        &apos;[object Text]&apos; is not a valid selector.\&quot;,
  ;;             ...}&quot;

  )
</code></pre><p>Well, that doesn&apos;t look promising. Let&apos;s see if we can figure this out.</p><div class="markdown-heading"><h2 id="textual-healing">Textual healing</h2><a href="#textual-healing" class="anchor" aria-label="Permalink: Textual healing"><img src="assets/link.svg" /></a></div><p>Looking back out at the HTML we generated in previously, we get a hint about which element might be the culprit:</p><pre><code class="language-clojure">  ;; =&gt; &quot;&lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot; style=\&quot;...\&quot;&gt;\n
  ;;       &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;...\&quot;&gt;defn876b4c306172 Cora SuttonJuly 9, 2025&lt;/div&gt;\n
</code></pre><p>Our <code>#episode-info</code> <strong>div</strong> looks a bit odd, doesn&apos;t it. Let&apos;s take a closer look:</p><pre><code class="language-clojure">(comment

  ;; ...

  (get-children &quot;#episode-info&quot;)
  ;; =&gt; (#object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[HTMLSpanElement [object HTMLSpanElement]])

  )
</code></pre><p>OK, so <code>#episode-info</code> has three children: two headings and a span. Let&apos;s feed the first child to <code>el-&gt;html</code> and see what happens:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      el-&gt;html)
  ;; =&gt; &quot;#error {:message \&quot;Failed to execute &apos;querySelector&apos; on &apos;Document&apos;:
  ;;                        &apos;[object Text]&apos; is not a valid selector.\&quot;,
  ;;             ...}&quot;

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      get-children
      log)
  ;; =&gt; (#object[Text [object Text]])

  )
</code></pre><p>Ah yes, there it is. So there seems to be something special about a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Text">Text</a> node that causes <code>el-&gt;html</code> to blow up. Let&apos;s see what we can actually do with this type of object. Reading the documentation, we see that it inherits from the <a href="https://developer.mozilla.org/en-US/docs/Web/API/CharacterData">CharacterData</a> class, which has a handy <code>data</code> attribute that is &quot;string representing the textual data contained in this object&quot;. Let&apos;s try that out:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      get-children
      first
      log)
  ;; =&gt; #object[Text [object Text]]

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      get-children
      first
      (.-data))
  ;; =&gt; &quot;defn&quot;

  )
</code></pre><p>Armed with this knowledge, we should be able to fix <code>get-text</code> to handle <code>Text</code> nodes:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-name ...)

(defn get-text
  &quot;Returns the inner text of an element.&quot;
  [el]
  (let [el (get-el el)]
    (if (instance? js/CharacterData el)
      (.-data el)
      (or (.-textContent el)
          (.-innerText el)))))

;; (defn set-text! ...)
;; ...

(comment

  ;; ...

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      get-children
      first
      get-text)
  ;; =&gt; &quot;#error {:message \&quot;Failed to execute &apos;querySelector&apos; on &apos;Document&apos;:
  ;;                        &apos;[object Text]&apos; is not a valid selector.\&quot;,
  ;;             ...}&quot;

  )
</code></pre><p>Hrm, we&apos;re back to this. Let&apos;s trace through <code>get-text</code> line by line to see if we can figure out what&apos;s going on:</p><pre><code class="language-clojure">(let [el (get-el el)]
  ...)
</code></pre><p>So we&apos;d be calling <code>(get-el)</code> with our <code>Text</code> node. Let&apos;s try that and see what happens:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      get-children
      first
      get-el)
  ;; =&gt; &quot;#error {:message \&quot;Failed to execute &apos;querySelector&apos; on &apos;Document&apos;:
  ;;                        &apos;[object Text]&apos; is not a valid selector.\&quot;,
  ;;             ...}&quot;

  )
</code></pre><p>Aha, so the problem is in <code>get-el</code>, which looks like this:</p><pre><code class="language-clojure">(defn get-el [selector]
  (if (instance? js/Element selector)
    selector
    (js/document.querySelector selector)))
</code></pre><p>What we&apos;re trying to do here is just return the <code>selector</code> arg if we&apos;re passed an element, otherwise assume <code>selector</code> is a string and use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector">Document.querySelector</a> to look up the element. But wait, why should we assume it&apos;s a string? Why not actually check? In fact, why not actually write the function in the same way we would describe it in English?</p><blockquote><p>If <code>selector</code> is a string, returns the element matching CSS selector. Otherwise, assume it&apos;s already an element and just return it.</p></blockquote><p>And whilst we&apos;re at it, why not update the docstring of the function to say exactly this?</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn secs-&gt;ts ...)

(defn get-el
  &quot;If `selector` is a string, returns the element matching CSS selector.
   Otherwise, assume it&apos;s already an element and just return it.&quot;
  [selector]
  (if (string? selector)
    (js/document.querySelector selector)
    selector))

;; (defn get-els ...)
;; ...

(comment

  ;; ...

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      get-children
      first
      get-text)
  ;; =&gt; &quot;defn&quot;

  )
</code></pre><p>Much better!</p><p>However, we still have that annoying word &quot;assume&quot; in our docstring. 😬</p><blockquote><p>Returns the element matching the specified CSS selector. If <code>selector</code> is already an element, just returns the element.</p></blockquote><p>How about we stop assuming, and actually throw an exception when we get an argument we can&apos;t handle? Sounds good, but the reason we&apos;re in this mess is because we were treating anything that wasn&apos;t an <strong>Element</strong> object as a string, and we discovered that <strong>Text</strong> isn&apos;t a subclass of <strong>Element</strong>. So what we actually want is a common ancestor of both <strong>Text</strong> and <strong>Element</strong>, right? And luckily, there is just such a subclass: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node">Node</a>! 🎉</p><p>Let&apos;s use that:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn secs-&gt;ts ...)

(defn get-el
  &quot;If `selector` is a string, returns the element matching CSS selector.
   If `selector` is a `Node`, returns it. Otherwise, throws an exception.&quot;
  [selector]
  (cond
    (string? selector)
    (js/document.querySelector selector)

    (instance? js/Node selector)
    selector

    :else
    (let [cls (-&gt; selector .-constructor .-name)]
      (throw (ex-info (str &quot;Expecting a string or a Node; got: &quot; cls)
                      {:dom/error :dom/error.invalid-class
                       :js/class cls})))))

;; (defn get-els ...)
;; ...

(comment

  ;; ...

  (get-el &quot;#podcast-title&quot;)
  ;; =&gt; #object[HTMLHeadingElement [object HTMLHeadingElement]]

  (get-el (js/document.querySelector &quot;#podcast-title&quot;))
  ;; =&gt; #object[HTMLHeadingElement [object HTMLHeadingElement]]

  (get-el 42)
  ;; =&gt; &quot;#error {:message \&quot;Expecting a string or a Node; got: Number\&quot;, ...}&quot;

  (try
    (get-el 42)
    (catch js/Error e
      (ex-data e)))
  ;; =&gt; {:dom/error :dom/error.invalid-class, :js/class &quot;Number&quot;}

  (-&gt; (get-children &quot;#episode-info&quot;)
      first
      get-children
      first
      get-text)
  ;; =&gt; &quot;defn&quot;

  )
</code></pre><p>Let&apos;s try turning the <code>#episode-info</code> div into HTML:</p><pre><code class="language-clojure">(comment

  ;; ...

  (el-&gt;html &quot;#episode-info&quot;)
  ;; =&gt; &quot;#error {:message \&quot;Could not find instance method: getAttribute\&quot;, ...}&quot;

  )
</code></pre><p><img alt="George Clooney sings &quot;I Am a Man of Constant Sorrow&quot;" src="assets/2026-11-07-persistence-sorrow.jpg" title="I bid farewell to old get-attr" class="border" /></p><p>Let&apos;s slow down for a second and actually think this through. What we&apos;re dealing with is HTML like this:</p><pre><code class="language-html">&lt;h3&gt;defn&lt;/h3&gt;
</code></pre><p>which is represented by a DOM node that we can create like this:</p><pre><code class="language-clojure">(create-el {:tag &quot;h3&quot;, :text &quot;defn&quot;})
</code></pre><p>And if we currently try to turn this into HTML, we get the &quot;Could not find instance method: getAttribute&quot; error, which makes sense, because neither <strong>Text</strong> nor any of its parent classes (<strong>CharacterData</strong> and <strong>Node</strong>) have a <code>.getAttribute()</code> method, and <code>el-&gt;html</code> calls <code>el-&gt;clj</code>, which in turn will try to get all sorts of attributes from the poor <strong>Text</strong> object. 😭</p><p>We should be able to solve this by making sure <code>el-&gt;html</code> can handle a <strong>Text</strong> node:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs-&gt;str ...)

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  [el]
  (if (instance? js/CharacterData el)
    (get-text el)
    (let [{:keys [tag attrs text]} (if (map? el) el (el-&gt;clj el))
          attrs-str (attrs-&gt;str attrs)
          tag-open (str &quot;  &lt;&quot; tag (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str)) &quot;&gt;&quot;)
          tag-close (str &quot;&lt;/&quot; tag &quot;&gt;&quot;)
          children (get-children el)]
      (if (seq children)
        (str/join &quot;\n&quot;
                  (concat [tag-open]
                          (map el-&gt;html children)
                          [tag-close]))
        (str tag-open text tag-close)))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el-&gt;html (js/Text. &quot;foo&quot;))
  ;; =&gt; &quot;foo&quot;

  (-&gt; (create-el {:tag &quot;h3&quot;, :text &quot;defn&quot;})
      el-&gt;html)
  ;; =&gt; &quot;  &lt;h3&gt;\ndefn\n&lt;/h3&gt;&quot;

  )
</code></pre><p>That seems somewhat reasonable, so let&apos;s see what happens when we turn the entire <code>#episode-info</code> <strong>div</strong> into HTML now:</p><pre><code class="language-clojure">(comment

  ;; ...

  (el-&gt;html &quot;#episode-info&quot;)
  ;; =&gt; &quot;  &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n
  ;;       &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;\ndefn\n&lt;/h3&gt;\n
  ;;       &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;\n876b4c306172 Cora Sutton\n&lt;/h2&gt;\n
  ;;       &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;\nJuly 9, 2025\n&lt;/span&gt;\n
  ;;       &lt;/div&gt;&quot;

  )
</code></pre><p>Hey, not bad!</p><div class="markdown-heading"><h2 id="html-at-last">HTML at last</h2><a href="#html-at-last" class="anchor" aria-label="Permalink: HTML at last"><img src="assets/link.svg" /></a></div><p>Feeling confident, we go ahead and dump the entire DOM to HTML:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (el-&gt;html &quot;html&quot;)
      log)
  ;; =&gt; &quot;  &lt;html xmlns=\&quot;http://www.w3.org/1999/xhtml\&quot;&gt;\n
  ;;       &lt;head&gt;\n\n
  ;;       \n
  ;;       &lt;title&gt;\ncljcastr episode player\n&lt;/title&gt;\n\n
  ;;       \n
  ;;       &lt;link rel=\&quot;stylesheet\&quot; href=\&quot;main.css\&quot;&gt;&lt;/link&gt;\n\n\n
  ;;       \n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n\n
  ;;       \n
  ;;       &lt;script&gt;\nvar SCITTLE_NREPL_WEBSOCKET_PORT = 1340;\n&lt;/script&gt;\n\n
  ;;       \n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n\n\n\n
  ;;       &lt;script type=\&quot;application/x-scittle\&quot; src=\&quot;player.cljs\&quot;&gt;&lt;/script&gt;\n\n\n&lt;/head&gt;\n\n\n\n
  ;;       &lt;body&gt;\n
  ;;       &lt;div class=\&quot;translate-tooltip-mtz blue sm-root translate hidden_translate\&quot;&gt;
  ;;       &lt;div class=\&quot;header-wrapper\&quot;&gt;
  ;;       &lt;div class=\&quot;header-controls\&quot;&gt;
  ;;       ...
  ;;       &lt;/div&gt;
  ;;       &lt;span class=\&quot;translate-button-mtz hidden_translate blue\&quot;&gt;&lt;/span&gt;\n
  ;;       &lt;audio class=\&quot;audio-for-speech\&quot; src=\&quot;\&quot;&gt;&lt;/audio&gt;\n
  ;;       &lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot; style=\&quot;width: 100%; display: flex; flex-direction: column; align-items: center;\&quot;&gt;\n
  ;;       &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n
  ;;       &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;\ndefn\n&lt;/h3&gt;\n
  ;;       &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;\n876b4c306172 Cora Sutton\n&lt;/h2&gt;\n
  ;;       &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;\nJuly 9, 2025\n&lt;/span&gt;\n
  ;;       &lt;/div&gt;\n
  ;;       ...
  ;;       &lt;button aria-label=\&quot;Playback speed\&quot; id=\&quot;button-speed\&quot; class=\&quot;cljcastr playback-button\&quot; style=\&quot;padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;\&quot;&gt;\n
  ;;       &lt;img src=\&quot;https://www.svgrepo.com/show/151785/speed-meter.svg\&quot; draggable=\&quot;false\&quot; id=\&quot;button-speed-icon\&quot; class=\&quot;cljcastr playback-icon\&quot; style=\&quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);\&quot;&gt;&lt;/img&gt;\n
  ;;       &lt;/button&gt;\n
  ;;       &lt;/div&gt;\n
  ;;       &lt;/div&gt;\n
  ;;       &lt;/body&gt;\n
  ;;       &lt;/html&gt;&quot;
</code></pre><p>Now that&apos;s more like it! Better yet, if we look in the browser console, we see some HTML:</p><p><img alt="HTML code" src="assets/2026-11-07-persistence-html.png" title="Such HTML!" class="border" /></p><p>Let&apos;s copy this HTML from the console and paste it into our <code>index.html</code>:</p><pre><code class="language-html">  &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
  &lt;head&gt;

  
  &lt;title&gt;
cljcastr episode player
&lt;/title&gt;

  
  &lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&gt;&lt;/link&gt;


  
  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;

  
  &lt;script&gt;
var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;
&lt;/script&gt;

  
  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;



  &lt;script type=&quot;application/x-scittle&quot; src=&quot;player.cljs&quot;&gt;&lt;/script&gt;


&lt;/head&gt;



  &lt;body&gt;
  &lt;div id=&quot;episode-container&quot; class=&quot;cljcastr&quot; style=&quot;width: 100%; display: flex; flex-direction: column; align-items: center;&quot;&gt;
  &lt;div id=&quot;episode-info&quot; class=&quot;cljcastr&quot; style=&quot;max-width: 420px; text-align: center;&quot;&gt;
  &lt;h3 id=&quot;podcast-title&quot; class=&quot;cljcastr&quot;&gt;
defn
&lt;/h3&gt;
  &lt;h2 id=&quot;episode-title&quot; class=&quot;cljcastr&quot;&gt;
876b4c306172 Cora Sutton
&lt;/h2&gt;
  &lt;span id=&quot;episode-date&quot; class=&quot;cljcastr&quot; style=&quot;color: grey;&quot;&gt;
July 9, 2025
&lt;/span&gt;
&lt;/div&gt;
  &lt;div id=&quot;episode-art-container&quot; class=&quot;cljcastr&quot;&gt;
  &lt;img src=&quot;https://media.zencastr.com/image-files/5d9048546bacd9001de88f1c/a5b922ac-7294-4d58-9a33-4308f5d4f50b.png&quot; id=&quot;episode-art&quot; class=&quot;cljcastr&quot; style=&quot;width: 400px; border-radius: 5%; padding: 10px;&quot;&gt;&lt;/img&gt;
&lt;/div&gt;
  &lt;audio controls=&quot;true&quot; src=&quot;https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3&quot; class=&quot;cljcastr&quot; style=&quot;display: none;&quot;&gt;&lt;/audio&gt;
  &lt;div id=&quot;progress&quot; class=&quot;cljcastr&quot; style=&quot;width: 390px; margin: 1.5em auto 0px;&quot;&gt;
  &lt;span id=&quot;elapsed-time&quot; class=&quot;cljcastr&quot; style=&quot;margin: 0px 5px; font-size: 0.7rem; color: grey; float: left;&quot;&gt;
00:00
&lt;/span&gt;
  &lt;span id=&quot;remaining-time&quot; class=&quot;cljcastr&quot; style=&quot;margin: 0px 5px; font-size: 0.7rem; color: grey; float: right;&quot;&gt;
1:29:30
&lt;/span&gt;
  &lt;div id=&quot;progress-container&quot; class=&quot;cljcastr&quot; style=&quot;position: relative; height: 28px; clear: both;&quot;&gt;
  &lt;progress min=&quot;0&quot; max=&quot;5370.949958&quot; value=&quot;0&quot; id=&quot;progress-bar&quot; class=&quot;cljcastr&quot; style=&quot;color: rgb(247, 147, 30); top: 10px; overflow: hidden; background-color: lightgray; width: 100%; z-index: 0; appearance: none; position: absolute; border: 0px; border-radius: 4px; height: 8px; left: 0px; margin: 0px;&quot;&gt;&lt;/progress&gt;
  &lt;input min=&quot;0&quot; value=&quot;0&quot; aria-valuemax=&quot;5370.949958&quot; type=&quot;range&quot; style=&quot;top: 0px; background-color: transparent; width: 100%; cursor: pointer; z-index: 1; appearance: none; position: absolute; border: 0px; touch-action: manipulation; height: 28px; left: 0px; margin: 0px;&quot; aria-valuetext=&quot;00:00 of 1:29:30&quot; max=&quot;5370.949958&quot; id=&quot;progress-slider&quot; class=&quot;cljcastr&quot; aria-label=&quot;Seek&quot; step=&quot;any&quot;&gt;&lt;/input&gt;
&lt;/div&gt;
&lt;/div&gt;
  &lt;div id=&quot;playback-controls&quot; class=&quot;cljcastr&quot;&gt;
  &lt;button aria-label=&quot;Back 15 seconds&quot; id=&quot;button-backward&quot; class=&quot;cljcastr playback-button&quot; style=&quot;padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;&quot;&gt;
  &lt;img src=&quot;https://www.svgrepo.com/show/495036/backward-15-seconds.svg&quot; draggable=&quot;false&quot; id=&quot;button-backward-icon&quot; class=&quot;cljcastr playback-icon&quot; style=&quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);&quot;&gt;&lt;/img&gt;
&lt;/button&gt;
  &lt;button aria-label=&quot;Play&quot; id=&quot;button-play&quot; class=&quot;cljcastr playback-button&quot; style=&quot;padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;&quot;&gt;
  &lt;img src=&quot;https://www.svgrepo.com/show/436852/play-circle-fill.svg&quot; draggable=&quot;false&quot; id=&quot;button-play-icon&quot; class=&quot;cljcastr playback-icon&quot; style=&quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);&quot;&gt;&lt;/img&gt;
&lt;/button&gt;
  &lt;button aria-label=&quot;Pause&quot; id=&quot;button-pause&quot; class=&quot;cljcastr playback-button&quot; style=&quot;padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;&quot;&gt;
  &lt;img src=&quot;https://www.svgrepo.com/show/436829/pause-circle-fill.svg&quot; draggable=&quot;false&quot; id=&quot;button-pause-icon&quot; class=&quot;cljcastr playback-icon&quot; style=&quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);&quot;&gt;&lt;/img&gt;
&lt;/button&gt;
  &lt;button aria-label=&quot;Forward 15 seconds&quot; id=&quot;button-forward&quot; class=&quot;cljcastr playback-button&quot; style=&quot;padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;&quot;&gt;
  &lt;img src=&quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot; draggable=&quot;false&quot; id=&quot;button-forward-icon&quot; class=&quot;cljcastr playback-icon&quot; style=&quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);&quot;&gt;&lt;/img&gt;
&lt;/button&gt;
  &lt;button aria-label=&quot;Playback speed&quot; id=&quot;button-speed&quot; class=&quot;cljcastr playback-button&quot; style=&quot;padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;&quot;&gt;
  &lt;img src=&quot;https://www.svgrepo.com/show/151785/speed-meter.svg&quot; draggable=&quot;false&quot; id=&quot;button-speed-icon&quot; class=&quot;cljcastr playback-icon&quot; style=&quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);&quot;&gt;&lt;/img&gt;
&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;protonpass-root-c873 data-protonpass-role=&quot;root&quot; data-protonpass-theme=&quot;os&quot;&gt;&lt;/protonpass-root-c873&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>Saving the file, we take a deep breath and refresh the page in the browser. Et voilà, our page reappears just as we&apos;d left it! 🎉</p><p>This is wonderful and all, but that HTML that we produced is a bit of an eyesore:</p><pre><code class="language-html">  &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
  &lt;head&gt;

  
  &lt;title&gt;
cljcastr episode player
&lt;/title&gt;

  
  &lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&gt;&lt;/link&gt;

  ...

&lt;/head&gt;



  &lt;body&gt;
  &lt;audio class=&quot;audio-for-speech&quot; src=&quot;&quot;&gt;&lt;/audio&gt;
  &lt;div class=\&quot;translate-tooltip-mtz blue sm-root translate hidden_translate\&quot;&gt;
  &lt;div class=\&quot;header-wrapper\&quot;&gt;
  &lt;div class=\&quot;header-controls\&quot;&gt;
  &lt;span class=\&quot;sound-translate\&quot;&gt;&lt;/span&gt;
  &lt;span class=\&quot;copy blue\&quot;&gt;&lt;/span&gt;
  &lt;span class=\&quot;settings-translator\&quot;&gt;&lt;/span&gt;
  &lt;/div&gt;
  &lt;div class=\&quot;header-title\&quot;&gt;translator&lt;/div&gt;
  &lt;div class=\&quot;translate-icons\&quot;&gt;
  &lt;img class=\&quot;from\&quot; src=\&quot;\&quot;&gt;&lt;/img&gt;
  &lt;img class=\&quot;translate-arrow\&quot; src=\&quot;chrome-extension://bebmphofpgkhclocdbgomhnjcpelbenh/images/right-arrow.png\&quot;&gt;&lt;/img&gt;
  &lt;div class=\&quot;translate_to_dropdown\&quot;&gt;
  &lt;button class=\&quot;dropbtn dropdown-toggle\&quot; type=\&quot;button\&quot; id=\&quot;dropdownMenuButton1\&quot; aria-expanded=\&quot;false\&quot;&gt;&lt;/button&gt;
  &lt;ul class=\&quot;dropdown-content-wrapper languageSelector blue\&quot;&gt;
  &lt;li&gt;
  &lt;a class=\&quot;dropdown-item\&quot; data-lang=\&quot;af\&quot;&gt;Afrikaans&lt;/a&gt;
  &lt;/li&gt;
  &lt;li&gt;
  &lt;a class=\&quot;dropdown-item\&quot; data-lang=\&quot;sq\&quot;&gt;Albanian - shqipe&lt;/a&gt;
  &lt;/li&gt;
  &lt;li&gt;
  &lt;a class=\&quot;dropdown-item\&quot; data-lang=\&quot;ar\&quot;&gt;Arabic - ‎‫العربية‬‎&lt;/a&gt;
  &lt;/li&gt;
  ...
  &lt;li&gt;
  &lt;a class=\&quot;dropdown-item\&quot; data-lang=\&quot;yi\&quot;&gt;Yiddish - יידיש&lt;/a&gt;
  &lt;/li&gt;
  &lt;/ul&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  &lt;div class=\&quot;translated-text\&quot;&gt;
  ...
  &lt;div id=&quot;episode-container&quot; class=&quot;cljcastr&quot; style=&quot;width: 100%; display: flex; flex-direction: column; align-items: center;&quot;&gt;
  &lt;div id=&quot;episode-info&quot; class=&quot;cljcastr&quot; style=&quot;max-width: 420px; text-align: center;&quot;&gt;
  ...
&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;protonpass-root-c873 data-protonpass-role=&quot;root&quot; data-protonpass-theme=&quot;os&quot;&gt;&lt;/protonpass-root-c873&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>In addition to all this whitespace, what&apos;s that weird stuff we didn&apos;t add to the DOM?</p><pre><code class="language-html">  &lt;audio class=&quot;audio-for-speech&quot; src=&quot;&quot;&gt;&lt;/audio&gt;
  &lt;div class=\&quot;translate-tooltip-mtz blue sm-root translate hidden_translate\&quot;&gt;
  &lt;div class=\&quot;header-wrapper\&quot;&gt;
  &lt;div class=\&quot;header-controls\&quot;&gt;
  ...
&lt;protonpass-root-c873 data-protonpass-role=&quot;root&quot; data-protonpass-theme=&quot;os&quot;&gt;&lt;/protonpass-root-c873&gt;
</code></pre><p>It seems that extensions occasionally shove stuff into the DOM, so maybe we should give ourselves a way to filter out nodes we don&apos;t want. Let&apos;s start by adding a new arity to <code>get-children</code> that lets us filter and remove children using an options map:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-classes! ...)

(defn get-children
  &quot;Returns the children of the specified element. Accepts an `opts` map with the
   following keys:

     `:filter-children` - predicate passed to `filter` on list of children
     `:remove-children` - predicate passed to `remove` on list of children

   `filter` is called before `remove`.&quot;
  ([el]
   (get-children el {}))
  ([el {:keys [filter-children remove-children]
        :or {filter-children (constantly true)
             remove-children (constantly false)} :as opts}]
   (-&gt;&gt; (get-el el)
        .-childNodes
        seq
        (filter filter-children)
        (remove remove-children))))

;; (defn add-child! ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (get-children &quot;#episode-info&quot;)
       log)
  ;; =&gt; (#object[Text [object Text]]
  ;;     #object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[Text [object Text]]
  ;;     #object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[Text [object Text]]
  ;;     #object[HTMLSpanElement [object HTMLSpanElement]]
  ;;     #object[Text [object Text]])

  (-&gt;&gt; (get-children &quot;#episode-info&quot;
                     {:filter-children (partial instance? js/HTMLHeadingElement)})
       log
       (map get-text))
  ;; =&gt; (&quot;\ndefn\n&quot; &quot;\n876b4c306172 Cora Sutton\n&quot;)

  (-&gt;&gt; (get-children &quot;#episode-info&quot;
                     {:remove-children (partial instance? js/Text)})
       log
       (map get-text))
  ;; =&gt; (&quot;\ndefn\n&quot; &quot;\n876b4c306172 Cora Sutton\n&quot; &quot;\nJuly 9, 2025\n&quot;)

  )
</code></pre><p>Now we need a way to pass those options in to <code>get-children</code> from <code>el-&gt;html</code>:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs-&gt;str ...)

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  ([el]
   (el-&gt;html el {}))
  ([el opts]
   (if (instance? js/CharacterData el)
     (get-text el)
     (let [{:keys [tag attrs text]} (if (map? el) el (el-&gt;clj el))
           attrs-str (attrs-&gt;str attrs)
           tag-open (str &quot;  &lt;&quot; tag (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str)) &quot;&gt;&quot;)
           tag-close (str &quot;&lt;/&quot; tag &quot;&gt;&quot;)
           children (get-children el opts)]
       (if (seq children)
         (str/join &quot;\n&quot;
                   (concat [tag-open]
                           (map #(el-&gt;html % opts) children)
                           [tag-close]))
         (str tag-open text tag-close))))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el-&gt;html &quot;#episode-info&quot;)
  ;; =&gt; &quot;  &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n\n
  ;;       \n
  ;;       &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;\n\ndefn\n\n&lt;/h3&gt;\n\n
  ;;       \n
  ;;       &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;\n\n876b4c306172 Cora Sutton\n\n&lt;/h2&gt;\n\n
  ;;       \n
  ;;       &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;\n\n
  ;;       July 9, 2025\n\n&lt;/span&gt;\n\n\n
  ;;       &lt;/div&gt;&quot;

  ;; Remove empty text nodes
  (el-&gt;html &quot;#episode-info&quot;
            {:remove-children #(empty? (str/replace (get-text %) #&quot;[\n\s]+&quot; &quot;&quot;))})
  ;; =&gt; &quot;  &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n
  ;;       &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;\n\ndefn\n\n&lt;/h3&gt;\n
  ;;       &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;\n\n876b4c306172 Cora Sutton\n\n&lt;/h2&gt;\n
  ;;       &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;\n\nJuly 9, 2025\n\n&lt;/span&gt;\n
  ;;       &lt;/div&gt;&quot;

  )
</code></pre><p>Now we have what we need to clean up our HTML a little bit:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [empty-text? #(and (instance? js/Text %)
                          (empty? (str/replace (get-text %) #&quot;[\n\s]+&quot; &quot;&quot;)))]
    (el-&gt;html &quot;html&quot;
              {:remove-children (fn [el]
                                  (or (empty-text? el)
                                      ;; Bye-bye Proton Pass!
                                      (str/starts-with? (or (get-name el) &quot;&quot;)
                                                        &quot;protonpass-&quot;)
                                      ;; Be gone, Translator!
                                      (some #(str/starts-with? % &quot;translate-&quot;)
                                            (get-classes el))
                                      (and (= &quot;audio&quot; (get-name el))
                                           (not (some #{&quot;cljcastr&quot;} (get-classes el))))))}))
  ;; =&gt; &quot;  &lt;html xmlns=\&quot;http://www.w3.org/1999/xhtml\&quot;&gt;\n
  ;;       &lt;head&gt;\n
  ;;       &lt;title&gt;\n\ncljcastr episode player\n\n&lt;/title&gt;\n
  ;;       &lt;link rel=\&quot;stylesheet\&quot; href=\&quot;main.css\&quot;&gt;&lt;/link&gt;\n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;script&gt;\n\n
  ;;       var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;\n\n
  ;;       &lt;/script&gt;\n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;script type=\&quot;application/x-scittle\&quot; src=\&quot;player.cljs\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;/head&gt;\n
  ;;       &lt;body&gt;\n
  ;;       &lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot; style=\&quot;width: 100%; display: flex; flex-direction: column; align-items: center;\&quot;&gt;\n
  ;;       ...
  ;;       &lt;/div&gt;\n
  ;;       &lt;/div&gt;\n
  ;;       &lt;/body&gt;\n
  ;;       &lt;/html&gt;&quot;

  )
</code></pre><p>This is cool and all, but the <code>:remove-children</code> function is getting a bit hairy, and we&apos;re haunted by the fact that we&apos;ll need to keep adding to it every time we install a new extension that inserts nodes into the DOM. This is the classic allowlist / denylist problem, and we can take a page out of the secure development notebook and deny all nodes by default, keeping only the ones we actually want.</p><div class="markdown-heading"><h2 id="plausible-deniability">Plausible deniability</h2><a href="#plausible-deniability" class="anchor" aria-label="Permalink: Plausible deniability"><img src="assets/link.svg" /></a></div><p>We know that this means using <code>:filter-children</code> instead of <code>:remove-children</code>, but what should we allow? How about this:</p><ul><li>The <strong>html</strong>, <strong>head</strong>, and <strong>body</strong> elements themselves</li><li>All elements that are descendants of the <strong>head</strong> element (i.e. children, grandchildren, great grandchildren, etc.)</li><li>All elements that are descendants of the <strong>body</strong> element that have the &quot;cljcastr&quot; class</li></ul><p>Let&apos;s start by adding a function to check whether an element has a specific class:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-classes ...)

(defn has-class?
  &quot;Returns true if the element&apos;s list of classes contains the specified class.&quot;
  [el cls]
  (-&gt; (get-classes el)
      set
      (contains? cls)))

;; (defn set-classes! ...)
;; ...

(comment

  ;; ...

  (has-class? &quot;#button-backward&quot; &quot;cljcastr&quot;)
  ;; =&gt; true

  )
</code></pre><p>Now, how about a function that checks whether one element is a descendant of another?</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-els ...)

(defn descendant?
  &quot;Returns truthy if the specified element is an ancestor of the element named by
   the specified CSS selector. NOTE: `ancestor-sel` must be a string containing
   a CSS selector, not an element!&quot;
  [el ancestor-sel]
  (-&gt; (get-el el)
      (.closest ancestor-sel)))

;; (defn get-attr ...)
;; ...

(comment

  ;; ...

  (descendant? &quot;#button-backward&quot; &quot;#episode-container&quot;)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  (descendant? &quot;#button-backward&quot; &quot;#episode-info&quot;)
  ;; =&gt; nil

  )
</code></pre><p>Given this, we should be able to write the <code>:filter-children</code> function of our dreams:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn ??? ...)

;; (defn ??? ...)
;; ...

(comment

  ;; ...

  (el-&gt;html &quot;html&quot;
            {:filter-children (fn [el]
                                (cond
                                  (instance? js/Text el)
                                  (-&gt; (get-text el)
                                      (str/replace #&quot;[\n\s]+&quot; &quot;&quot;)
                                      not-empty)
                                  
                                  (instance? js/Element el)
                                  (or (contains? #{&quot;html&quot; &quot;head&quot; &quot;body&quot;}
                                                 (get-name el))
                                      (descendant? el &quot;head&quot;)
                                      (and (descendant? el &quot;body&quot;)
                                           (has-class? el &quot;cljcastr&quot;)))))})
  ;; =&gt; &quot;  &lt;html xmlns=\&quot;http://www.w3.org/1999/xhtml\&quot;&gt;\n
  ;;       &lt;head&gt;\n
  ;;       &lt;title&gt;cljcastr episode player&lt;/title&gt;\n
  ;;       &lt;link rel=\&quot;stylesheet\&quot; href=\&quot;main.css\&quot;&gt;&lt;/link&gt;\n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;script&gt;var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;&lt;/script&gt;\n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;script type=\&quot;application/x-scittle\&quot; src=\&quot;player.cljs\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;/head&gt;\n
  ;;       &lt;body&gt;\n
  ;;       &lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot; style=\&quot;width: 100%; display: flex; flex-direction: column; align-items: center;\&quot;&gt;\n
  ;;       &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n
  ;;       ...
  ;;       &lt;/div&gt;\n
  ;;       &lt;/div&gt;\n
  ;;     &lt;/body&gt;\n
  ;;     &lt;/html&gt;\n
  ;;     &quot;

  )
</code></pre><p>This is definite progress! We&apos;re still not loving that indentation, though.</p><div class="markdown-heading"><h2 id="indenting-for-fun-and-profit">Indenting for fun and profit</h2><a href="#indenting-for-fun-and-profit" class="anchor" aria-label="Permalink: Indenting for fun and profit"><img src="assets/link.svg" /></a></div><p>Let&apos;s think about how we&apos;d like our HTML indented:</p><ol start="1"><li>Indent children by two spaces</li><li><code>&lt;head&gt;</code> and <code>&lt;body&gt;</code> should not be indented</li><li><code>&lt;head&gt;</code> and <code>&lt;body&gt;</code> should reset indentation</li><li>The content of text nodes should go on the same line as the parent node</li></ol><p>In other words, we&apos;d like our HTML to look like this:</p><pre><code class="language-html">&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
  &lt;title&gt;cljcastr episode player&lt;/title&gt;
  ...
&lt;/head&gt;
&lt;body&gt;
  &lt;div id=&quot;episode-container&quot; class=&quot;cljcastr&quot; style=&quot;width: 100%; display: flex; flex-direction: column; align-items: center;&quot;&gt;
    &lt;div id=&quot;episode-info&quot; class=&quot;cljcastr&quot; style=&quot;max-width: 420px; text-align: center;&quot;&gt;
      &lt;h3 id=&quot;podcast-title&quot; class=&quot;cljcastr&quot;&gt;defn&lt;/h3&gt;
      &lt;h2 id=&quot;episode-title&quot; class=&quot;cljcastr&quot;&gt;876b4c306172 Cora Sutton&lt;/h2&gt;
      &lt;span id=&quot;episode-date&quot; class=&quot;cljcastr&quot; style=&quot;color: grey;&quot;&gt;July 9, 2025&lt;/span&gt;
    &lt;/div&gt;
    ...
&lt;/body&gt;
&lt;/html&gt;
</code></pre><p>Let&apos;s start with rule #4. First of all, what does the content of one of our text nodes look like?</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-children &quot;#podcast-title&quot;)
       first
       get-text)
  ;; =&gt; &quot;\ndefn\n&quot;

  )
</code></pre><p>OK, it starts with a newline and ends with two newlines. How about we get rid of those?</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-children &quot;#podcast-title&quot;)
       first
       get-text
       str/trim)
  ;; =&gt; &quot;defn&quot;

  )
</code></pre><p>Great! Now we can plug this into <code>el-&gt;html</code>. We also need to stop putting newlines between the children (this will mess up our formatting, but we&apos;ll address that as we work our way through the rest of the rules in our list).</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs-&gt;str ...)

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  ([el]
   (el-&gt;html el {}))
  ([el opts]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs text]} (if (map? el) el (el-&gt;clj el))
           attrs-str (attrs-&gt;str attrs)
           tag-open (str &quot;  &lt;&quot; tag (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str)) &quot;&gt;&quot;)
           tag-close (str &quot;&lt;/&quot; tag &quot;&gt;&quot;)
           children (get-children el opts)]
       (if (seq children)
         (str/join &quot;&quot;
                   (concat [tag-open]
                           (map #(el-&gt;html % opts) children)
                           [tag-close]))
         (str tag-open text tag-close))))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el-&gt;html &quot;#podcast-title&quot;)
  ;; =&gt; &quot;  &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;defn&lt;/h3&gt;&quot;

  )
</code></pre><p>Great! That&apos;s rule #4 ticked off the list. Of course, this has made a bit of a mess of other things:</p><pre><code class="language-clojure">(comment

  ;; ...

  (el-&gt;html &quot;#episode-info&quot;)
  ;; =&gt; &quot;  &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;  &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;defn&lt;/h3&gt;  &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;876b4c306172 Cora Sutton&lt;/h2&gt;  &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;July 9, 2025&lt;/span&gt;&lt;/div&gt;&quot;

  )
</code></pre><p>Note the extreme lack of newlines there. We can address this by adding some indentation rules to our <code>opts</code> map:</p><ul><li><code>:indent-level</code> - number of levels to indent</li><li><code>:indent-str</code> - string to use when indenting</li></ul><p>Now for a little helper function:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs-&gt;str ...)

(defn indent
  &quot;Returns `indent-str` repeated `indent-level` times.&quot;
  [indent-level indent-str]
  (-&gt;&gt; (repeat indent-level indent-str)
       (str/join &quot;&quot;)))

;; (defn el-&gt;html ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (range 3)
       (map #(str (indent % &quot;  &quot;) &quot;indent &quot; %)))
  ;; =&gt; (&quot;indent 0&quot; &quot;  indent 1&quot; &quot;    indent 2&quot;)

  )
</code></pre><p>Let&apos;s plug this into <code>el-&gt;html</code>:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn indent ...)

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  ([el]
   (el-&gt;html el {}))
  ([el {:keys [indent-level indent-str]
        :or {indent-level 0, indent-str &quot;  &quot;}
        :as opts}]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs]} (if (map? el) el (el-&gt;clj el))
           attrs-str (attrs-&gt;str attrs)
           children-html (-&gt;&gt; (get-children el opts)
                              (map #(el-&gt;html % (assoc opts :indent-level
                                                       (inc indent-level))))
                              (str/join &quot;&quot;))
           tag-open (str (indent indent-level indent-str)
                         &quot;&lt;&quot; tag
                         (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str))
                         &quot;&gt;&quot;
                         (if (str/ends-with? children-html &quot;\n&quot;)
                           &quot;\n&quot;
                           &quot;&quot;))
           tag-close (str (if (str/ends-with? children-html &quot;\n&quot;)
                            (indent indent-level indent-str)
                            &quot;&quot;)
                          &quot;&lt;/&quot; tag &quot;&gt;\n&quot;)]
       (str tag-open children-html tag-close)))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el-&gt;html &quot;#episode-info&quot;)
  ;; =&gt; &quot;&lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n
  ;;       &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;defn&lt;/h3&gt;\n
  ;;       &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;876b4c306172 Cora Sutton&lt;/h2&gt;\n
  ;;       &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;July 9, 2025&lt;/span&gt;\n
  ;;     &lt;/div&gt;\n&quot;

  )
</code></pre><p>Biting our bottom lip to keep the fear at bay, we unleash <code>el-&gt;html</code> on the entire DOM:</p><pre><code class="language-clojure">(comment

  ;; ...

  (el-&gt;html &quot;html&quot;
            {:filter-children (fn [el]
                                (cond
                                  (instance? js/Text el)
                                  (-&gt; (get-text el)
                                      (str/replace #&quot;[\n\s]+&quot; &quot;&quot;)
                                      not-empty)
                                  
                                  (instance? js/Element el)
                                  (or (contains? #{&quot;html&quot; &quot;head&quot; &quot;body&quot;}
                                                 (get-name el))
                                      (descendant? el &quot;head&quot;)
                                      (and (descendant? el &quot;body&quot;)
                                           (has-class? el &quot;cljcastr&quot;)))))})
  ;; =&gt; &quot;&lt;html xmlns=\&quot;http://www.w3.org/1999/xhtml\&quot;&gt;\n
  ;;       &lt;head&gt;\n
  ;;         &lt;title&gt;cljcastr episode player&lt;/title&gt;\n
  ;;         ...
  ;;       &lt;/head&gt;\n
  ;;       &lt;body&gt;\n
  ;;         &lt;audio class=\&quot;audio-for-speech\&quot; src=\&quot;\&quot;&gt;&lt;/audio&gt;\n
  ;;         &lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot; style=\&quot;width: 100%; display: flex; flex-direction: column; align-items: center;\&quot;&gt;\n
  ;;           &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n
  ;;             &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;defn&lt;/h3&gt;\n
  ;;             &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;876b4c306172 Cora Sutton&lt;/h2&gt;\n
  ;;             &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;July 9, 2025&lt;/span&gt;\n
  ;;           &lt;/div&gt;\n
  ;;           ...
  ;;         &lt;/div&gt;\n
  ;;       &lt;/body&gt;\n
  ;;     &lt;/html&gt;\n
  ;;     &quot;

  )
</code></pre><p>This looks great! Or rather, almost great, because we forgot about rules #2 and #3:</p><pre><code class="language-text">2. `&lt;head&gt;` and `&lt;body&gt;` should not be indented
3. `&lt;head&gt;` and `&lt;body&gt;` should reset indentation
</code></pre><p>Turns out we can implement both of these rules with a one-line addition to <code>el-&gt;html</code>! Well, maybe two lines, because a comment seems appropriate.</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn indent ...)

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  ([el]
   (el-&gt;html el {}))
  ([el {:keys [indent-level indent-str]
        :or {indent-level 0, indent-str &quot;  &quot;}
        :as opts}]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs]} (if (map? el) el (el-&gt;clj el))
           attrs-str (attrs-&gt;str attrs)
           ;; Reset indentation for &lt;head&gt; and &lt;body&gt; tags
           indent-level (if (#{&quot;head&quot; &quot;body&quot;} (str/lower-case tag)) 0 indent-level)
           children-html (-&gt;&gt; (get-children el opts)
                              (map #(el-&gt;html % (assoc opts :indent-level
                                                       (inc indent-level))))
                              (str/join &quot;&quot;))
           tag-open (str (indent indent-level indent-str)
                         &quot;&lt;&quot; tag
                         (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str))
                         &quot;&gt;&quot;
                         (if (str/ends-with? children-html &quot;\n&quot;)
                           &quot;\n&quot;
                           &quot;&quot;))
           tag-close (str (if (str/ends-with? children-html &quot;\n&quot;)
                            (indent indent-level indent-str)
                            &quot;&quot;)
                          &quot;&lt;/&quot; tag &quot;&gt;\n&quot;)]
       (str tag-open children-html tag-close)))))

;; (defn format-css ...)
;; ...
</code></pre><p>In case the two new lines where hard to spot, here they are again:</p><pre><code class="language-clojure">           ;; Reset indentation for &lt;head&gt; and &lt;body&gt; tags
           indent-level (if (#{&quot;head&quot; &quot;body&quot;} (str/lower-case tag)) 0 indent-level)
</code></pre><p>Now let&apos;s try again with the HTML dumping:</p><pre><code class="language-clojure">(comment

  ;; ...

  (el-&gt;html &quot;html&quot;
            {:filter-children (fn [el]
                                (cond
                                  (instance? js/Text el)
                                  (-&gt; (get-text el)
                                      (str/replace #&quot;[\n\s]+&quot; &quot;&quot;)
                                      not-empty)
                                  
                                  (instance? js/Element el)
                                  (or (contains? #{&quot;html&quot; &quot;head&quot; &quot;body&quot;}
                                                 (get-name el))
                                      (descendant? el &quot;head&quot;)
                                      (and (descendant? el &quot;body&quot;)
                                           (has-class? el &quot;cljcastr&quot;)))))})
  ;; =&gt; &quot;&lt;html xmlns=\&quot;http://www.w3.org/1999/xhtml\&quot;&gt;\n
  ;;     &lt;head&gt;\n
  ;;       &lt;title&gt;cljcastr episode player&lt;/title&gt;\n
  ;;       &lt;link rel=\&quot;stylesheet\&quot; href=\&quot;main.css\&quot;&gt;&lt;/link&gt;\n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;script&gt;var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;&lt;/script&gt;\n
  ;;       &lt;script src=\&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\&quot; type=\&quot;application/javascript\&quot;&gt;&lt;/script&gt;\n
  ;;       &lt;script type=\&quot;application/x-scittle\&quot; src=\&quot;player.cljs\&quot;&gt;&lt;/script&gt;\n
  ;;     &lt;/head&gt;\n
  ;;     &lt;body&gt;\n
  ;;       &lt;audio class=\&quot;audio-for-speech\&quot; src=\&quot;\&quot;&gt;&lt;/audio&gt;\n
  ;;       &lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot; style=\&quot;width: 100%; display: flex; flex-direction: column; align-items: center;\&quot;&gt;\n
  ;;         &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot; style=\&quot;max-width: 420px; text-align: center;\&quot;&gt;\n
  ;;           &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;defn&lt;/h3&gt;\n
  ;;           &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;876b4c306172 Cora Sutton&lt;/h2&gt;\n
  ;;           &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot; style=\&quot;color: grey;\&quot;&gt;July 9, 2025&lt;/span&gt;\n
  ;;         &lt;/div&gt;\n
  ;;         ...
  ;;       &lt;/div&gt;\n
  ;;     &lt;/body&gt;\n
  ;;     &lt;/html&gt;\n
  ;;     &quot;

  )
</code></pre><p>Looking at the browser console confirms that our HTML looks exactly as we wanted! And we could copy that sweet sweet HTML from the console and paste it into our <code>index.html</code> and move on with our lives... or we could shave just one more yak.</p><div class="markdown-heading"><h2 id="shaving-that-final-yak">Shaving that final yak</h2><a href="#shaving-that-final-yak" class="anchor" aria-label="Permalink: Shaving that final yak"><img src="assets/link.svg" /></a></div><p>It&apos;s a bit annoying that we have to keep remembering the elements we want to keep when dumping our HTML, so let&apos;s create a nice little set of functions to take care of that:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn update-playback-position-indicators! ...)

(defn keep-child? [el]
  (cond
    (instance? js/Text el)
    (-&gt; (get-text el)
        (str/replace #&quot;[\n\s]+&quot; &quot;&quot;)
        not-empty)
    
    (instance? js/Element el)
    (or (contains? #{&quot;html&quot; &quot;head&quot; &quot;body&quot;}
                   (get-name el))
        (descendant? el &quot;head&quot;)
        (and (descendant? el &quot;body&quot;)
             (has-class? el &quot;cljcastr&quot;)))))

(defn dom-&gt;html []
  (el-&gt;html &quot;html&quot; {:filter-children keep-child?}))

;; (js/console.log ...)
;; ...

(comment

  ;; ...

  (do
    (log (dom-&gt;html))
    nil)
  ;; =&gt; nil

  )
</code></pre><p>Checking the console verifies that this is the HTML we&apos;re looking for.</p><p>But this is really not the yak we came here to shave. That big old annoying yak staring us in the face is the one that makes us use the mouse (the horror!) to copy a bunch of HTML from the browser console, and then pop back over to Emacs and switch to the <code>index.html</code> buffer and yank and then kill the old contents of the file and save. I mean, who has time for this kind of nonsense? Not us, that&apos;s for damn sure!</p><p>If only there was a way to save a file from the browser...</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [filename &quot;boring.html&quot;
        html &quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Yawn...&lt;/body&gt;&lt;/html&gt;&quot;
        blob-url (-&gt; (js/Blob. [html] (clj-&gt;js {:type &quot;text/html&quot;}))
                     js/URL.createObjectURL)]
    (-&gt; (create-el {:tag &quot;a&quot;
                    :attrs {:download filename
                            :href blob-url}})
        .click))
  ;; =&gt; nil

  )
</code></pre><p>When we evaluate this form, we get a helpful save file dialog of the sort we&apos;ve seen millions of times before, with <code>boring.html</code> helpfully prefilled.</p><p><img alt="Browser save file dialog" src="assets/2026-11-07-persistence-save.png" title="Save me from boredom!" class="border" /></p><p>If you were to save this file in your <code>public</code> directory alongside <code>index.html</code> and then browse to <a href="http://localhost:1341/boring.html">http://localhost:1341/boring.html</a>, you would be quite bored.</p><p>But that&apos;s OK, for we have learned the magic incantation for saving a file:</p><ol start="1"><li>Create a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">Blob</a> containing some HTML and a <code>text/html</code> content type.</li><li>Create a blob <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">URL</a> (i.e. a URL with <code>blob:</code> as its scheme) from said blob.</li><li>Create an <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement">a</a> element with its <code>download</code> attribute set to a filename of our choosing and its <code>href</code> attribute set to the blob URL we created.</li><li>Click on the <strong>a</strong> element.</li></ol><p>This is quite straightforward to turn into a couple of functions:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-event-listener! ...)

(defn save-file! [filename content content-type]
  (let [blob-url (-&gt; (js/Blob. [content] (clj-&gt;js {:type content-type}))
                     js/URL.createObjectURL)]
    (-&gt; (create-el {:tag &quot;a&quot;
                    :attrs {:download filename
                            :href blob-url}})
        .click)))

;; (defn create-button ...)
;; ...
;; (defn dom-&gt;html ...)

(defn save-html!
  ([]
   (save-html! &quot;index.html&quot;))
  ([filename]
   (save-html! filename (dom-&gt;html)))
  ([filename html]
   (save-file! filename html &quot;text/html&quot;)))

;; (js/console.log ...)
;; ...
(comment

  ;; ...

  (save-html!)
  ;; =&gt; nil

  )
</code></pre><p>When the save file dialog pops up, let&apos;s save it over top of our existing <code>index.html</code> and then reload the browser.</p><p>The page looks exactly the same as before, but our <code>index.html</code> is a work of art, formatted as purdy as a peach, as we say back where ah&apos;m from (locating my point of provence shall remain an exercise for the reader, though that information is readily available in the <a href="https://zencastr.com/z/AbDd9ONj">latest episode of
defn</a>—as of this writing, that is; I have no clue when you&apos;re reading this). 🍑</p><p>All is good in the world... except that clicking the buttons on our lovely player has no effect whatsoever. 😅</p><div class="markdown-heading"><h2 id="button-mashing">Button mashing</h2><a href="#button-mashing" class="anchor" aria-label="Permalink: Button mashing"><img src="assets/link.svg" /></a></div><p>But fear not! &apos;Tis but the work of a moment to fix them. Moving back over to our <code>player.cljs</code> buffer, we mash <strong>C-c C-k</strong> (<code>cider-load-buffer</code>), then pop down to the bottom of our <code>comment</code> form and search backwards for &quot;(def playback-controls&quot;. Once we find what we&apos;re looking for, we copy it and paste it into our namespace, right before our &quot;Ready to play!&quot; message:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...) 

(def playback-controls
  {:play {:src &quot;https://www.svgrepo.com/show/436852/play-circle-fill.svg&quot;
          :label &quot;Play&quot;
          :click-handler #(.play (get-el &quot;audio.cljcastr&quot;))}
   :pause {:src &quot;https://www.svgrepo.com/show/436829/pause-circle-fill.svg&quot;
           :label &quot;Pause&quot;
           :click-handler #(.pause (get-el &quot;audio.cljcastr&quot;))}
   :forward {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
             :label &quot;Forward {{seek-dur-sec}} seconds&quot;
             :click-handler #(skip-forward! (get-el &quot;audio.cljcastr&quot;) seek-dur-sec)}
   :backward {:src &quot;https://www.svgrepo.com/show/495036/backward-15-seconds.svg&quot;
              :label &quot;Back {{seek-dur-sec}} seconds&quot;
              :click-handler #(skip-backward! (get-el &quot;audio.cljcastr&quot;) seek-dur-sec)}
   :speed {:src &quot;https://www.svgrepo.com/show/151785/speed-meter.svg&quot;
           :label &quot;Playback speed&quot;}})

(js/console.log &quot;Ready to play!&quot;)

(comment

  ;; ...

  )
</code></pre><p>We hit <strong>C-c C-k</strong> again, but are deeply saddened by an error message:</p><pre><code class="language-clojure">#error {:message &quot;Unable to resolve symbol: seek-dur-sec&quot;,
        :data {:type :sci/error, :line 10, :column 30,
               :message &quot;Unable to resolve symbol: seek-dur-sec&quot;,
               ;; ...
               },
        ;; ...
        }
</code></pre><p>Oops, looks like we need to grab <code>seek-dur-sec</code> as well:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...) 

(def seek-dur-sec 15)

;; (def playback-controls ...)
</code></pre><p><strong>C-c C-k</strong> FTW?</p><p>Victory! 🏆</p><p>Or maybe more accurately, not defeat, since clicking the buttons still doesn&apos;t work. Which isn&apos;t that surprising, since we didn&apos;t actually attach any event listeners to anything. Let&apos;s see if we can figure out how to do that.</p><pre><code class="language-clojure">(comment

  ;; ...

  (doseq [[el-id {:keys [click-handler]}] playback-controls]
    (add-event-listener! (str &quot;#button-&quot; (name el-id)) &quot;click&quot;
                         click-handler))
  ;; =&gt; nil

  )
</code></pre><p>Now if we click the play button, the episode starts playing! We skip backwards and forwards in the episode, try pausing it, and finally convince ourselves that all the buttons work.</p><p>The only problem is that the elapsed time, remaining time, progress bar, and slider aren&apos;t working. 🤔</p><p>Oh yeah, we had a handler for that as well. And we might as well attach the listener to the slider that updates the playback position too:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [audio (get-el &quot;audio.cljcastr&quot;)]
    (add-event-listener! &quot;#progress-slider&quot; &quot;input&quot;
                         #(-&gt;&gt; % .-target .-value (set! (.-currentTime audio))))
    (add-event-listener! audio &quot;timeupdate&quot;
                         #(update-playback-position-indicators!
                           (.-currentTime audio) (.-duration audio)
                           (-&gt;&gt; [:elapsed-time
                                 :remaining-time
                                 :progress-slider
                                 :progress-bar]
                                (map (fn [el-id]
                                       [el-id (str &quot;#&quot; (name el-id))]))
                                (into {}))))
    audio)
  ;; =&gt; #object[HTMLAudioElement [object HTMLAudioElement]]

  )
</code></pre><p>If we click play again, we see the timestamps updating and slider moving, and if we move the slider ourselves, we can successfully jump around in the episode. Life is good!</p><p>That is, until we hit <strong>C-c C-k</strong> again and realise that despite the console cheerily telling us that we&apos;re &quot;Ready to play!&quot;, the buttons don&apos;t work. 😢</p><p>Of course, we can evaluate the two forms we just added to the Rich comment, but it&apos;s hardly a good user experience to expect our users to connect a ClojureScript REPL, paste in some code, and evaluate it before they can actually play an episode.</p><p>There is a pretty easy solution to this. If we just add the two magic forms right before our &quot;Ready to play!&quot; log statement, the listeners should be attached on page load. Let&apos;s try it:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (def playback-controls ...)

(doseq [[el-id {:keys [click-handler]}] playback-controls]
  (add-event-listener! (str &quot;#button-&quot; (name el-id)) &quot;click&quot;
                       click-handler))

(let [audio (get-el &quot;audio.cljcastr&quot;)]
  (add-event-listener! &quot;#progress-slider&quot; &quot;input&quot;
                       #(-&gt;&gt; % .-target .-value (set! (.-currentTime audio))))
  (add-event-listener! audio &quot;timeupdate&quot;
                       #(update-playback-position-indicators!
                         (.-currentTime audio) (.-duration audio)
                         (-&gt;&gt; [:elapsed-time
                               :remaining-time
                               :progress-slider
                               :progress-bar]
                              (map (fn [el-id]
                                     [el-id (str &quot;#&quot; (name el-id))]))
                              (into {}))))
  audio)

;; (js/console.log ...)
</code></pre><p>If we save the file and reload the page, the buttons now work from the start. This is good, but there is one oddity that we&apos;ll notice in the console if we pause playback then evaluate the buffer with <strong>C-c C-k</strong> again:</p><pre><code class="language-text">  Added listener for click events to                                  nrepl.cljs:10
   ‣ &lt;button class=​&quot;cljcastr&quot; id=​&quot;button-speed&quot;
             style=​&quot;padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​&quot;
             aria-label=​&quot;Playback speed&quot;&gt;​…​&lt;/button&gt;​
  Added listener for input events to                                  nrepl.cljs:10
   ‣ &lt;input class=​&quot;cljcastr&quot; id=​&quot;progress-slider&quot; type=​&quot;range&quot;
            min=​&quot;0&quot; max=​&quot;3138.727422&quot; value=​&quot;0&quot;step=​&quot;any&quot;
            style=​&quot;top:​ 0px;​ background-color:​ transparent;​ width:​ 100%;​ cursor:​ pointer;​ z-index:​ 1;​ appearance:​ none;​ position:​ absolute;​ border:​ 0px;​ touch-action:​ manipulation;​ height:​ 28px;​ left:​ 0px;​ margin:​ 0px;​&quot;
            aria-label=​&quot;Seek&quot; aria-valuetext=​&quot;11:​58 of 52:​18&quot; 
            aria-valuemax=​&quot;3138.727422&quot;&gt;​
  Added listener for timeupdate events to                             nrepl.cljs:10
   ‣ &lt;audio class=​&quot;cljcastr&quot; controls style=​&quot;display:​ none;​&quot; 
            src=​&quot;https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3&quot;&gt;​&lt;/audio&gt;​
  Ready to play!
</code></pre><p>And if we click play then pause again, we see that the click handlers are firing twice:</p><pre><code class="language-text">  Handling click on                                                   nrepl.cljs:10
   ‣ &lt;button class=​&quot;cljcastr&quot; id=​&quot;button-pause&quot;
             style=​&quot;padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​&quot;
             aria-label=​&quot;Pause&quot;&gt;​…​&lt;/button&gt;​
   ‣ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
  Handling click on                                                   nrepl.cljs:10
   ‣ &lt;button class=​&quot;cljcastr&quot; id=​&quot;button-pause&quot;
             style=​&quot;padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​&quot;
             aria-label=​&quot;Pause&quot;&gt;​…​&lt;/button&gt;​
   ‣ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
</code></pre><p>If we evaluate the buffer again, then click play and pause, we see the handlers firing thrice! 😱</p><pre><code class="language-text">  Handling click on                                                   nrepl.cljs:10
   ‣ &lt;button class=​&quot;cljcastr&quot; id=​&quot;button-pause&quot;
             style=​&quot;padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​&quot;
             aria-label=​&quot;Pause&quot;&gt;​…​&lt;/button&gt;​
   ‣ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
  Handling click on                                                   nrepl.cljs:10
   ‣ &lt;button class=​&quot;cljcastr&quot; id=​&quot;button-pause&quot;
             style=​&quot;padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​&quot;
             aria-label=​&quot;Pause&quot;&gt;​…​&lt;/button&gt;​
   ‣ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
  Handling click on                                                   nrepl.cljs:10
   ‣ &lt;button class=​&quot;cljcastr&quot; id=​&quot;button-pause&quot;
             style=​&quot;padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​&quot;
             aria-label=​&quot;Pause&quot;&gt;​…​&lt;/button&gt;​
   ‣ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
</code></pre><p>OK, so it appears that every time we evaluate the buffer, we get a new click handler. And if we think about it for a moment, it makes sense, because these forms:</p><pre><code class="language-clojure">(doseq [[el-id {:keys [click-handler]}] playback-controls]
  (add-event-listener! (str &quot;#button-&quot; (name el-id)) &quot;click&quot;
                       click-handler))

(let [audio (get-el &quot;audio.cljcastr&quot;)]
  (add-event-listener! &quot;#progress-slider&quot; &quot;input&quot;
                       #(-&gt;&gt; % .-target .-value (set! (.-currentTime audio))))
  (add-event-listener! audio &quot;timeupdate&quot;
                       #(update-playback-position-indicators!
                         (.-currentTime audio) (.-duration audio)
                         (-&gt;&gt; [:elapsed-time
                               :remaining-time
                               :progress-slider
                               :progress-bar]
                              (map (fn [el-id]
                                     [el-id (str &quot;#&quot; (name el-id))]))
                              (into {}))))
  audio)

;; (js/console.log ...)
</code></pre><p>are getting evaluated every time, since they are at the top level of our namespace. Luckily for us, if we whip out our microscope, we find a solution (and a precipitate, but that&apos;s beside the point): the mighty atom!</p><div class="markdown-heading"><h2 id="atomic-elbow">Atomic elbow</h2><a href="#atomic-elbow" class="anchor" aria-label="Permalink: Atomic elbow"><img src="assets/link.svg" /></a></div><p>A common pattern in ClojureScript apps is to define a single atom that holds all of the state we care about. It is conventional to call this atom <code>state</code>, so let&apos;s follow said convention because we aren&apos;t iconoclastic hipsters, after all!</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

(defonce state (atom {}))

;; (defn log ...)
;; ...
</code></pre><p>We use <a href="https://clojuredocs.org/clojure.core/defonce">defonce</a> instead of plain ol&apos; <a href="https://clojuredocs.org/clojure.core/def">def</a>, because otherwise every time we evaluated the buffer, our <code>state</code> var would be rebound to a fresh new atom, thus defeating the point of keeping state in the first place.</p><p>Now that we&apos;ve done this, let&apos;s move our code that attaches event listeners into a function:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (def playback-controls)

(defn init-ui! []
  (doseq [[el-id {:keys [click-handler]}] playback-controls]
    (add-event-listener! (str &quot;#button-&quot; (name el-id)) &quot;click&quot;
                         click-handler))
  (let [audio (get-el &quot;audio.cljcastr&quot;)]
    (add-event-listener! &quot;#progress-slider&quot; &quot;input&quot;
                         #(-&gt;&gt; % .-target .-value (set! (.-currentTime audio))))
    (add-event-listener! audio &quot;timeupdate&quot;
                         #(update-playback-position-indicators!
                           (.-currentTime audio) (.-duration audio)
                           (-&gt;&gt; [:elapsed-time
                                 :remaining-time
                                 :progress-slider
                                 :progress-bar]
                                (map (fn [el-id]
                                       [el-id (str &quot;#&quot; (name el-id))]))
                                (into {}))))
    audio)
  (log &quot;UI initialised&quot;))

;; (js/console.log ...)
</code></pre><p>Now if we evaluate the buffer, we don&apos;t see &quot;UI initialised!&quot; get printed in the console. However, if we reload the page, we&apos;re back to our buttons not working, which makes sense, because we&apos;re never calling our new <code>init-ui!</code> function.</p><p>Let&apos;s fix that!</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn init-ui! ...) 

(when-not (:initialised? @state)
  (init-ui!)
  (swap! state assoc :initialised? true))

;; (js/console.log ...)
</code></pre><p>If we reload the page now, we&apos;ll see our handlers getting installed and our log statement telling us &quot;UI initialised&quot;, as well as the usual chipper &quot;Ready to play!&quot;. And if we evaluate the buffer a couple times, we see &quot;Ready to play!&quot; being logged, but nothing about handlers and initialisation.</p><p><img alt="Console with initialisation messages" src="assets/2026-11-07-persistence-init.png" title="Now we&apos;re actually ready!" class="border" /></p><p>Better yet, everything seems to work!</p><div class="markdown-heading"><h2 id="what-has-css-ever-done-for-us-anyway?">What has CSS ever done for us anyway?</h2><a href="#what-has-css-ever-done-for-us-anyway?" class="anchor" aria-label="Permalink: What has CSS ever done for us anyway?"><img src="assets/link.svg" /></a></div><p>Of course, we are not the sort of Clojurians to rest on our laurels, for there are still improvements to be made! It is considered a bit tacky these days to use inline styles, so let&apos;s see if we can take a page out of our <code>el-&gt;html</code> book and export our styles.</p><p>In fact, we already have a function to get a map of styles from an element (<code>get-styles</code>), and code in our <code>set-styles!</code> function that turns a map of styles into a CSS string, so it&apos;s but the work of a moment to squish them together:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (-&gt;&gt; (get-styles &quot;#progress-bar&quot;)
       (map (fn [[k v]]
              (str (name k) &quot;: &quot; v)))
       (str/join &quot;; &quot;))
  ;; =&gt; &quot;color: rgb(247, 147, 30); top: 10px; overflow: hidden;
  ;;     background-color: lightgray; width: 100%; z-index: 0;
  ;;     appearance: none; position: absolute; border: 0px;
  ;;     border-radius: 4px; height: 8px; left: 0px; margin: 0px;&quot;

  )
</code></pre><p>What would be really cool, though, would be to produce a snippet like this:</p><pre><code class="language-css">#progress-bar {
  color: rgb(247, 147, 30);
  top: 10px;
  overflow: hidden;
  background-color: lightgray;
  width: 100%;
  z-index: 0;
  appearance: none;
  position: absolute;
  border: 0px;
  border-radius: 4px;
  height: 8px;
  left: 0px;
  margin: 0px;
}
</code></pre><p>Honestly, that shouldn&apos;t be too tricky. Let&apos;s see what we can do:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [el (get-el &quot;#progress-bar&quot;)
        styles (get-styles el)]
    (str &quot;#&quot; (get-id el) &quot; {\n  &quot;
         (-&gt;&gt; styles
              (map (fn [[k v]]
                     (str (name k) &quot;: &quot; v)))
              (str/join &quot;;\n  &quot;))
         &quot;\n}&quot;))
  ;; =&gt; &quot;#progress-bar {\n
  ;;       color: rgb(247, 147, 30);\n
  ;;       top: 10px;\n
  ;;       overflow: hidden;\n
  ;;       background-color: lightgray;\n
  ;;       width: 100%;\n
  ;;       z-index: 0;\n
  ;;       appearance: none;\n
  ;;       position: absolute;\n
  ;;       border: 0px;\n
  ;;       border-radius: 4px;\n
  ;;       height: 8px;\n
  ;;       left: 0px;\n
  ;;       margin: 0px;\n
  ;;     }&quot;

  )
</code></pre><p>But what about elements without an ID?</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [el (get-el &quot;audio.cljcastr&quot;)
        styles (get-styles el)]
    (str &quot;#&quot; (get-id el) &quot; {\n  &quot;
         (-&gt;&gt; styles
              (map (fn [[k v]]
                     (str (name k) &quot;: &quot; v)))
              (str/join &quot;;\n  &quot;))
         &quot;\n}&quot;))
  ;; =&gt; &quot;# {\n  display: none;\n}&quot;

  )
</code></pre><p>For that, let&apos;s fall back to the tag name, plus the class if it exists:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [el (get-el &quot;audio.cljcastr&quot;)
        styles (get-styles el)
        id (get-id el)
        classes (get-classes el)
        sel (if (not-empty id)
              (str &quot;#&quot; (get-id el))
              (str (get-name el) (if (seq classes)
                                   (str &quot;.&quot; (first classes)))))]
    (str sel &quot; {\n  &quot;
         (-&gt;&gt; styles
              (map (fn [[k v]]
                     (str (name k) &quot;: &quot; v)))
              (str/join &quot;;\n  &quot;))
         &quot;\n}&quot;))
  ;; =&gt; &quot;audio.cljcastr {\n  display: none;\n}&quot;

  )
</code></pre><p>This is a bit clunky, though. It would be a lot cleaner if we used <code>el-&gt;clj</code> to turn the element into a Clojure datastructure:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [el (get-el &quot;audio.cljcastr&quot;)
        styles (get-styles el)
        id (get-id el)
        classes (get-classes el)
        sel (if (not-empty id)
              (str &quot;#&quot; (get-id el))
              (str (get-name el) (if (seq classes)
                                   (str &quot;.&quot; (first classes)))))]
    (str sel &quot; {\n  &quot;
         (-&gt;&gt; styles
              (map (fn [[k v]]
                     (str (name k) &quot;: &quot; v)))
              (str/join &quot;;\n  &quot;))
         &quot;\n}&quot;))
  ;; =&gt; &quot;audio.cljcastr {\n  display: none;\n}&quot;

  )
</code></pre><p>This code is so special it deserves a name! And lo! that name shall be <code>el-&gt;css</code>, and it shall be good.</p><p><img alt="Ramses I from The Ten Commandments saying &apos;So let it be written, so let it be done&apos;" src="assets/2026-11-07-persistence-written.jpg" title="Quoth the pharoah: nevermore!" class="border" /></p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el-&gt;html ...)

(defn format-css
  &quot;Returns a CSS string with the specified selector and styles&quot;
  [sel styles]
  (str sel &quot; {\n  &quot;
       (-&gt;&gt; styles
            (map (fn [[k v]]
                   (str (name k) &quot;: &quot; v)))
            (str/join &quot;;\n  &quot;))
       &quot;\n}&quot;))

(defn el-&gt;css
  &quot;Given an element (or the Clojure representation of an element), returns a CSS
   rule corresponding to the element&apos;s ID.&quot;
  [el]
  (let [el (log (if (map? el) el (-&gt; (get-el el) el-&gt;clj)))
        {:keys [styles id tag classes]} el
        sel (if (not-empty id)
              (str &quot;#&quot; id)
              (str tag (if (seq classes)
                         (str &quot;.&quot; (first classes)))))]
    (format-css sel styles)))

;; (defn create-el ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (el-&gt;css &quot;#progress-bar&quot;)
       log)
  ;; =&gt; &quot;#progress-bar {\n
  ;;       color: rgb(247, 147, 30);\n
  ;;       top: 10px;\n
  ;;       overflow: hidden;\n
  ;;       background-color: lightgray;\n
  ;;       width: 100%;\n
  ;;       z-index: 0;\n
  ;;       appearance: none;\n
  ;;       position: absolute;\n
  ;;       border: 0px;\n
  ;;       border-radius: 4px;\n
  ;;       height: 8px;\n
  ;;       left: 0px;\n
  ;;       margin: 0px;\n
  ;;     }&quot;

)
</code></pre><p>This is pretty cool, so why don&apos;t we add a function to generate CSS for multiple elements at a time?</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el-&gt;css ...)

(defn els-&gt;css
  &quot;Given an collection of elements (or Clojure representations of elements),
   returns CSS rules corresponding to the elements&apos; IDs.&quot;
  [els]
  (-&gt;&gt; els
       (map el-&gt;clj)
       (remove (comp empty? :styles))
       (map el-&gt;css)
       (str/join &quot;\n\n&quot;)))

;; (defn create-el ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (els-&gt;css (get-els &quot;.cljcastr&quot;))
       log)
  ;; =&gt; &quot;#episode-container {\n
  ;;       width: 100%;\n
  ;;       display: flex;\n
  ;;       flex-direction: column;\n
  ;;       align-items: center;\n
  ;;     }\n
  ;;     \n
  ;;     #episode-info {\n
  ;;       max-width: 420px;\n
  ;;       text-align: center;\n
  ;;     }\n
  ;;     \n
  ;;     ...

)
</code></pre><p>Casting our gaze upon the console, joy fills our hearts:</p><p><img alt="CSS code" src="assets/2026-11-07-persistence-css.png" title="Such CSS!" class="border" /></p><p>However, (and you knew the however was coming, eh dear reader?) our heart rankles at the repetition inherent in the system.</p><div class="markdown-heading"><h2 id="it’s-your-birthday.-someone-gives-you-a-calfskin-wallet.">It’s your birthday. Someone gives you a calfskin wallet.</h2><a href="#it’s-your-birthday.-someone-gives-you-a-calfskin-wallet." class="anchor" aria-label="Permalink: It’s your birthday. Someone gives you a calfskin wallet."><img src="assets/link.svg" /></a></div><p>What people do when they write CSS is use classes to combine related sets of elements. We&apos;re not going to be able to do that completely programmatically, but we can at least spit out something that&apos;s a better starting point for a person to pick up and shape to their liking.</p><p>How might we go about this?</p><pre><code class="language-clojure">(comment

  ;; ...

  (def style-groups
    (-&gt;&gt; (get-els &quot;.cljcastr&quot;)
         (map el-&gt;clj)
         (remove (comp empty? :styles))
         (group-by :styles)))
  ;; =&gt; #&apos;cljcastr.player/style-groups

  (count style-groups)
  ;; =&gt; 13

  (-&gt;&gt; style-groups
       (map (fn [[_styles els]]
              (map #(select-keys % [:tag :id :classes]) els))))
  ;; =&gt; (({:tag &quot;div&quot;, :id &quot;progress-container&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;div&quot;, :id &quot;progress&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;progress&quot;, :id &quot;progress-bar&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;img&quot;, :id &quot;episode-art&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;input&quot;, :id &quot;progress-slider&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;span&quot;, :id &quot;episode-date&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;div&quot;, :id &quot;episode-info&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;img&quot;, :id &quot;button-backward-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-play-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-pause-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-forward-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-speed-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)})
  ;;     ({:tag &quot;audio&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;span&quot;, :id &quot;elapsed-time&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;button&quot;, :id &quot;button-backward&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-play&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-pause&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-forward&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-speed&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)})
  ;;     ({:tag &quot;span&quot;, :id &quot;remaining-time&quot;, :classes (&quot;cljcastr&quot;)})
  ;;     ({:tag &quot;div&quot;, :id &quot;episode-container&quot;, :classes (&quot;cljcastr&quot;)}))

)
</code></pre><p>What we&apos;re doing here is getting all the elements having &quot;cljcastr&quot; as one of their classes, turning them into Clojure data structures, removing the ones with no inline styles, then grouping them by their styles. This results in a map where the keys are styles and the values are the list of the elements with those styles (see the documentation for the <a href="https://clojuredocs.org/clojure.core/group-by">group-by</a> function if this is confusing). We then map over that to look at the tag, ID, and classes of the elements with each unique set of styles.</p><p>Grouping elements like this seems useful, so let&apos;s create a function to do it:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el-&gt;clj ...)

(defn group-styles
  &quot;Given a collection of DOM elements, returns a map keyed by styles. The value
   at each key will be a vector of the corresponding elements, in the order they
   appeared in the original list.

   Example:

     (let [els [(create-el {:tag \&quot;div\&quot;, :id \&quot;el1\&quot;, :styles {:color \&quot;red\&quot;}})
                (create-el {:tag \&quot;div\&quot;, :id \&quot;el2\&quot;, :styles {:color \&quot;blue\&quot;}})
                (create-el {:tag \&quot;div\&quot;, :id \&quot;el3\&quot;})
                (create-el {:tag \&quot;div\&quot;, :id \&quot;el4\&quot;, :styles {:color \&quot;red\&quot;}})]]
       (-&gt;&gt; (group-styles els)
            (map (fn [[styles els]]
                   [styles (map #(select-keys % [:id]) els)]))))
     ;; =&gt; ([{:color \&quot;red;\&quot;} ({:id \&quot;el1\&quot;} {:id \&quot;el4\&quot;})]
     ;;     [{:color \&quot;blue;\&quot;} ({:id \&quot;el2\&quot;})])&quot;
  [els]
  (-&gt;&gt; els
       (map el-&gt;clj)
       (remove (comp empty? :styles))
       (group-by :styles)))

;; (defn attrs-&gt;str ...)
;; ...
</code></pre><p>Now that we have this, let&apos;s see how many of these styles apply to multiple elements:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;.cljcastr&quot;)
       group-styles
       (filter (fn [[_ els]] (&gt; (count els) 1)))
       (map (fn [[_styles els]]
              (map #(select-keys % [:tag :id :classes]) els))))
  ;; =&gt; (({:tag &quot;img&quot;, :id &quot;button-backward-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-play-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-pause-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-forward-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-speed-icon&quot;, :classes (&quot;cljcastr&quot; &quot;playback-icon&quot;)})
  ;;     ({:tag &quot;button&quot;, :id &quot;button-backward&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-play&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-pause&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-forward&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-speed&quot;, :classes (&quot;cljcastr&quot; &quot;playback-button&quot;)}))

)
</code></pre><p>These look like great candidates for consolidation! But what selector should we use to write the rule?</p><p>Well, we know that all of our elements share the &quot;cljcastr&quot; class in common, so if we exclude that, we see that both of these groups are left with a single class!</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;.cljcastr&quot;)
       group-styles
       (filter (fn [[_ els]] (&gt; (count els) 1)))
       (map (fn [[_styles els]]
              (map (fn [el]
                     (-&gt; (select-keys el [:tag :id :classes])
                         (update :classes #(remove (fn [cls] (= &quot;cljcastr&quot; cls)) %))))
                   els))))
  ;; =&gt; (({:tag &quot;img&quot;, :id &quot;button-backward-icon&quot;, :classes (&quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-play-icon&quot;, :classes (&quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-pause-icon&quot;, :classes (&quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-forward-icon&quot;, :classes (&quot;playback-icon&quot;)}
  ;;      {:tag &quot;img&quot;, :id &quot;button-speed-icon&quot;, :classes (&quot;playback-icon&quot;)})
  ;;     ({:tag &quot;button&quot;, :id &quot;button-backward&quot;, :classes (&quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-play&quot;, :classes (&quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-pause&quot;, :classes (&quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-forward&quot;, :classes (&quot;playback-button&quot;)}
  ;;      {:tag &quot;button&quot;, :id &quot;button-speed&quot;, :classes (&quot;playback-button&quot;)}))

)
</code></pre><p>Let&apos;s run those through <code>els-&gt;css</code> and see what we get:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;.cljcastr&quot;)
       group-styles
       (filter (fn [[_ els]] (&gt; (count els) 1)))
       (map (fn [[_styles els]]
              (-&gt;&gt; els
                   (map (fn [el]
                          (update el :classes #(remove (fn [cls] (= &quot;cljcastr&quot; cls)) %))))
                   els-&gt;css)))
       (str/join &quot;\n\n&quot;)
       log)
  ;; =&gt; &quot;#button-backward-icon {\n  width: 35px;\n  ...}&quot;

)
</code></pre><p>Looking at the console, we see that we&apos;re back where we started:</p><pre><code class="language-css">#button-backward-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-play-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-pause-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-forward-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-speed-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-backward {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-play {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-pause {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-forward {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-speed {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}
</code></pre><p>What we really want to do is generate a single rule for each group, with the remaining class as the selector. If we update <code>el-&gt;css</code> with a second arity that accepts a selector as an argument, we can accomplish this fairly easily:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn format-css ...)

(defn el-&gt;css
  &quot;Given an element (or the Clojure representation of an element), returns a CSS
   rule corresponding to the element&apos;s ID.&quot;
  ([el]
   (let [el (if (map? el) el (-&gt; (get-el el) el-&gt;clj))
         {:keys [styles id tag classes]} el
         sel (if (not-empty id)
               (str &quot;#&quot; id)
               (str tag (if (seq classes)
                          (str &quot;.&quot; (first classes)))))]
     (el-&gt;css el sel)))
  ([el sel]
   (format-css sel (:styles el))))

;; (defn els-&gt;css ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;.cljcastr&quot;)
       group-styles
       (filter (fn [[_ els]] (&gt; (count els) 1)))
       (map (fn [[_styles [el &amp; _]]]
              (let [sel (str &quot;.&quot; (-&gt;&gt; (:classes el)
                                      (remove (partial = &quot;cljcastr&quot;))
                                      first))]
                (el-&gt;css el sel))))
       (str/join &quot;\n\n&quot;)
       log)
  ;; =&gt; &quot;.playback-icon {\n  width: 35px;\n  ...}&quot;

)
</code></pre><p>And now the console fills our hearts with delight once again!</p><pre><code class="language-css">.playback-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

.playback-button {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}
</code></pre><p>Let&apos;s now take a step back and think about how we want to generate the rules:</p><ol start="1"><li>Group by styles</li><li>For groups with a single element, just call <code>el-&gt;css</code> on it</li><li>For groups with multiple elements, take the first one, drop &quot;cljcastr&quot; from its list of classes, generate a selector from the first remaining class, and then call <code>el-&gt;css</code> on the element, using the custom selector</li></ol><p>And if we say this in Clojure, it looks like this:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;.cljcastr&quot;)
       group-styles
       (map (fn [[_styles [el &amp; rest-els]]]
              (if (seq rest-els)
                (let [sel (str &quot;.&quot; (-&gt;&gt; (:classes el)
                                        (remove (partial = &quot;cljcastr&quot;))
                                        first))]
                  (el-&gt;css el sel))
                (el-&gt;css el))))
       (str/join &quot;\n\n&quot;)
       log)
  ;; =&gt; &quot;#progress-container {\n  position: relative;\n  height: 28px;\n  ...}&quot;

)
</code></pre><p>If we look at the console, it appears that all of our prayers are answered! 🎉</p><pre><code class="language-css">#progress-container {
  position: relative;
  height: 28px;
  clear: both;
}

#progress {
  width: 390px;
  margin: 1.5em auto 0px;
  position: relative;
}

#progress-bar {
  color: rgb(247, 147, 30);
  top: 10px;
  overflow: hidden;
  background-color: lightgray;
  width: 100%;
  z-index: 0;
  appearance: none;
  position: absolute;
  border: 0px;
  border-radius: 4px;
  height: 8px;
  left: 0px;
  margin: 0px;
}

#episode-art {
  width: 400px;
  border-radius: 5%;
  padding: 10px;
}

#progress-slider {
  top: 0px;
  background-color: transparent;
  width: 100%;
  cursor: pointer;
  z-index: 1;
  appearance: none;
  position: absolute;
  border: 0px;
  touch-action: manipulation;
  height: 28px;
  left: 0px;
  margin: 0px;
}

#episode-date {
  color: grey;
}

#episode-info {
  max-width: 420px;
  text-align: center;
}

.playback-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

audio.cljcastr {
  display: none;
}

#elapsed-time {
  margin: 0px 5px;
  font-size: 0.7rem;
  color: grey;
  float: left;
}

.playback-button {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#remaining-time {
  margin: 0px 5px;
  font-size: 0.7rem;
  color: grey;
  float: right;
}

#episode-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</code></pre><p>Now that we have all of these lovely styles, we can write a couple of functions to export them, following the same pattern as for <code>save-html!</code>:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...)

(defn dom-&gt;css []
  (-&gt;&gt; (get-els &quot;.cljcastr&quot;)
       group-styles
       (map (fn [[_styles [el &amp; rest-els]]]
              (if (seq rest-els)
                (let [sel (str &quot;.&quot; (-&gt;&gt; (:classes el)
                                        (remove (partial = &quot;cljcastr&quot;))
                                        first))]
                  (el-&gt;css el sel))
                (el-&gt;css el))))
       (str/join &quot;\n\n&quot;)
       log))

(defn save-css!
  ([]
   (save-css! &quot;main.css&quot;))
  ([filename]
   (save-css! filename (dom-&gt;css)))
  ([filename css]
   (save-file! filename css &quot;text/css&quot;)))

;; (def seek-dur-sec ...)
;; ...

(comment

  ;; ...

  (save-css!)
  ;; =&gt; nil

)
</code></pre><p>We evaluate the <code>save-css!</code> form and save the <code>main.css</code> file alongside our <code>index.html</code>. Now all we have to do to use the styles is two things:</p><ol start="1"><li>Import the stylesheet in <code>index.html</code></li><li>Regenerate our HTML without the inline styles</li></ol><div class="markdown-heading"><h2 id="inline-skating-away-on-the-thin-ice-of-a-new-day">Inline skating away on the thin ice of a new day</h2><a href="#inline-skating-away-on-the-thin-ice-of-a-new-day" class="anchor" aria-label="Permalink: Inline skating away on the thin ice of a new day"><img src="assets/link.svg" /></a></div><p>The first part is simple, we just add one element to the DOM:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; (create-el {:tag &quot;link&quot;,
                   :attrs {:rel &quot;stylesheet&quot;, :href &quot;main.css&quot;}})
       (add-child! &quot;head&quot;))
  ;; =&gt; #object[HTMLHeadElement [object HTMLHeadElement]]

  )
</code></pre><p>And now for the new HTML. Let&apos;s update <code>el-&gt;html</code> to take a new option called <code>:exclude-styles?</code>, and then emit the HTML without inline styles if it&apos;s truthy:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn indent ...)

(defn el-&gt;html
  &quot;Given an element (or the Clojure representation of an element), returns an
   HTML string.&quot;
  ([el]
   (el-&gt;html el {}))
  ([el {:keys [indent-level indent-str exclude-styles?]
        :or {indent-level 0, indent-str &quot;  &quot;}
        :as opts}]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs]} (if (map? el) el (el-&gt;clj el))
           attrs (if exclude-styles? (dissoc attrs :style) attrs)
           attrs-str (attrs-&gt;str attrs)
           ;; Reset indentation for &lt;head&gt; and &lt;body&gt; tags
           indent-level (if (#{&quot;head&quot; &quot;body&quot;} (str/lower-case tag)) 0 indent-level)
           children-html (-&gt;&gt; (get-children el opts)
                              (map #(el-&gt;html % (assoc opts :indent-level
                                                       (inc indent-level))))
                              (str/join &quot;&quot;))
           tag-open (str (indent indent-level indent-str)
                         &quot;&lt;&quot; tag
                         (if (empty? attrs-str) &quot;&quot; (str &quot; &quot; attrs-str))
                         &quot;&gt;&quot;
                         (if (str/ends-with? children-html &quot;\n&quot;)
                           &quot;\n&quot;
                           &quot;&quot;))
           tag-close (str (if (str/ends-with? children-html &quot;\n&quot;)
                            (indent indent-level indent-str)
                            &quot;&quot;)
                          &quot;&lt;/&quot; tag &quot;&gt;\n&quot;)]
       (str tag-open children-html tag-close)))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (get-els &quot;body &gt; .cljcastr&quot;)
       (map #(el-&gt;html % {:exclude-styles? true}))
       (str/join &quot;\n&quot;)
       log)
  ;; =&gt; &quot;&lt;div id=\&quot;episode-container\&quot; class=\&quot;cljcastr\&quot;&gt;\n
  ;;       &lt;div id=\&quot;episode-info\&quot; class=\&quot;cljcastr\&quot;&gt;\n
  ;;         &lt;h3 id=\&quot;podcast-title\&quot; class=\&quot;cljcastr\&quot;&gt;defn&lt;/h3&gt;\n
  ;;         &lt;h2 id=\&quot;episode-title\&quot; class=\&quot;cljcastr\&quot;&gt;876b4c306172 Cora Sutton&lt;/h2&gt;\n
  ;;         &lt;span id=\&quot;episode-date\&quot; class=\&quot;cljcastr\&quot;&gt;July 9, 2025&lt;/span&gt;\n
  ;;       &lt;/div&gt;\n
  ;;       ...
  ;;     &lt;/div&gt;\n
  ;;     &quot;

)
</code></pre><p>Let&apos;s update <code>dom-&gt;html</code> and <code>save-&gt;html!</code> to allow us to exclude styles if we wanna. But how to do it? <code>dom-&gt;html</code> is simple: we just add a 1-arity version of the function that takes an options map. <code>save-html!</code> on the other hand requires a tiny bit of design. We could add yet another arity, but then we have the problem of distinguising between what the arguments mean. Let&apos;s simplify a bit: we&apos;ll have the 0-arity function to fill in all the defaults, and a 1-arity version taking an options map:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn keep-child? ...)

(defn dom-&gt;html
  ([]
   (dom-&gt;html {}))
  ([opts]
   (el-&gt;html &quot;html&quot;
             (merge opts
                    {:filter-children keep-child?}))))

(defn save-html!
  ([]
   (save-html! {}))
  ([{:keys [filename html]
     :or {filename &quot;index.html&quot;}
     :as opts}]
   (let [html (or html (dom-&gt;html opts))]
     (save-file! filename html &quot;text/html&quot;))))

;; (defn save-html! ...)
;; ...
</code></pre><p>Now we can save a new version of <code>index.html</code>, this time without the styles:</p><pre><code class="language-clojure">(comment

  ;; ...

  (save-html! {:exclude-styles? true})
  ;; =&gt; nil

  )
</code></pre><p>After saving, let&apos;s check <code>index.html</code> to make sure things look good:</p><pre><code class="language-html">&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
  &lt;title&gt;cljcastr episode player&lt;/title&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&gt;&lt;/link&gt;
  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
  &lt;script&gt;var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;&lt;/script&gt;
  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;application/x-scittle&quot; src=&quot;player.cljs&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;div id=&quot;episode-container&quot; class=&quot;cljcastr&quot;&gt;
    &lt;div id=&quot;episode-info&quot; class=&quot;cljcastr&quot;&gt;
      &lt;h3 id=&quot;podcast-title&quot; class=&quot;cljcastr&quot;&gt;defn&lt;/h3&gt;
      &lt;h2 id=&quot;episode-title&quot; class=&quot;cljcastr&quot;&gt;876b4c306172 Cora Sutton&lt;/h2&gt;
      &lt;span id=&quot;episode-date&quot; class=&quot;cljcastr&quot;&gt;July 9, 2025&lt;/span&gt;
    &lt;/div&gt;
    ...
  &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre><p>Holding our breath, we reload the page, and... see the same thing we were just looking at. 😅</p><p>But actually, that&apos;s precisely what we were trying to achieve. If we open dev tools and inspect the play button, we see two exciting things:</p><ol start="1"><li>No inline styles in the <strong>button</strong> element</li><li>In the <strong>Styles</strong> panel, there is a <code>.playback-button</code> class being applied, defined in <code>main.css</code></li></ol><p><img alt="Player with just buttons" src="assets/2026-11-07-persistence-stylesheet.png" title="The buttons, the whole buttons, and nothing but the buttons" class="border" /></p><p>At this point, we&apos;ve built a nice podcast player interactively, then created a persistence mechanism so we can safely reload the page. This feels really good, right? 😀</p><p>We bask in the feeling for an altogether brief moment, then start thinking of ways to improve things. Like adding that transcript we were talking about many thousands of word ago? Or maybe not limiting ourselves to a single defn episode (even if it is a 🔥 episode!)?</p><p>Our minds start to fill with the possibilities, but we come to our senses and decide some hammock time (in the form of a nice long walk perhaps—maybe even with one of our favourite human or canine companions?) is in order.</p><p>Next time on <a href="tags/scittlecastr.html">Scittlecastr</a>, we return from our hammock time and get to scittling them features!</p><p><em>The preview image for this post was based on the <a href="https://thenounproject.com/photo/teenager-looking-at-equation-on-chalk-board-48w3K5/">Teenager looking at equation
on chalk
board</a> photo by <a href="https://thenounproject.com/creator/rafa_fernandez/">Rafa Fernandez</a> from his <a href="https://thenounproject.com/browse/photo-shoot/back-to-school-boy-bx9va0/">Back To School
Boy</a> photoshoot. The photo is used under The Noun Project&apos;s <a href="https://thenounproject.com/pricing/#icons">Royalty-Free Commercial
License</a>, and was remixed by hand in the <a href="https://www.gimp.org/">GIMP</a>, which <a href="https://gitlab.gnome.org/GNOME/gimp/-/blob/04e7f69d779d99d32a7c0156ce296f83b84bd600/README?plain=1#L52">does not allow genAI
contributions</a>.</em></p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2026-11-01-scittlecastr.html</id>
    <link href="https://jmglov.net/blog/2026-11-01-scittlecastr.html"/>
    <title>Scittlecastr: The Scittling</title>
    <updated>2026-11-01T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="Arab woman listening to Scittle podcast with earphones and dancing outdoors" src="assets/2026-11-01-scittlecastr-preview.jpg" title="Photo by Javier Sanchez Mingorance from Noun Project" /></p><p><em>This post was entirely written by a human, with no assistance from LLMs or other &quot;AI&quot; technology such as pervert glasses or autonomous weapon systems.</em></p><p>I&apos;ve mentioned cljcastr here before, but <a href="/blog/2024-02-22-cljcastr.html">in a very tongue in cheek
fashion</a>. Since then, cljcastr has turned into a serious project to create a set of tools for producing and self-hosting podcasts. The project has two simple principles:</p><ol start="1"><li><strong>No surveillance. Ever.</strong> cljcastr runs on your computer and only your computer. It does not connect to any external services, store data on the cloud (AKA other people&apos;s computers), or track you in any way, shape, or form.</li><li><strong>No AI.</strong> All cljcastr code is written by hand, by humans. Nothing in this repository has been AI generated, and no AI generated pull requests will even be considered for inclusion.</li></ol><p>cljcastr is hosted on Codeberg at <a href="https://codeberg.org/jmglov/cljcastr">jmglov/cljcastr</a>.</p><p>In this blog post, I&apos;m going to demonstrate the cljcastr ethos by implementing a simple podcast player in ClojureScript, using the mighty <a href="https://github.com/babashka/scittle/">Scittle</a>. This is gonna be a long one (even by my standards), so here&apos;s a table of contents to help us all stay oriented.</p><div class="markdown-heading"><h2 id="table-of-contents">Table of contents</h2><a href="#table-of-contents" class="anchor" aria-label="Permalink: Table of contents"><img src="assets/link.svg" /></a></div><ol start="1"><li><a href="#building-the-skeleton">Building the skeleton</a> - setting up a Babashka project and a Scittle app and connecting a REPL to it</li><li><a href="#interactive-development">Interactive development</a> - getting used to the REPL and logging Clojure data structures in the browser console</li><li><a href="#getting-down-to-brass-html">Getting down to brass HTML</a> - adding a heading</li><li><a href="#play-that-funky-music">Play that funky music</a> - adding an audio player</li><li><a href="#escaping-from-vanilla">Escaping from vanilla</a> - adding custom controls</li><li><a href="#rainbows-and-unicorns">Rainbows and unicorns</a> - applying styles</li><li><a href="#play-it-again,-sam">Play it again, Sam</a> - adding event listeners</li><li><a href="#a11y-spells-ally">A11y spells ally</a> - making controls accessible</li><li><a href="#sweeping-up-the-shop">Sweeping up the shop</a> - adding DOM helper functions and refactoring</li><li><a href="#sweeping-audio-under-the-carpet">Sweeping audio under the carpet</a> - hiding the standard audio player</li><li><a href="#hours,-minutes,-and-seconds,-oh-my!">Hours, minutes, and seconds, oh
    my!</a> - displaying elapsed and remaining time in a human-readable form</li><li><a href="#laying-out-the-law">Laying out the law</a> - adding episode info in a nice layout</li><li><a href="#slipping-and-sliding">Slipping and sliding</a> - adding a progress bar and draggable position slider</li><li><a href="#getting-into-position">Getting into position</a> - combining the progress bar and position slider into a typical scrubbing control</li></ol><div class="markdown-heading"><h2 id="building-the-skeleton">Building the skeleton</h2><a href="#building-the-skeleton" class="anchor" aria-label="Permalink: Building the skeleton"><img src="assets/link.svg" /></a></div><p>To get started, we&apos;re going to need a Babashka project set up to serve files from a local webserver. Let&apos;s create a <code>cljcastr</code> directory:</p><pre><code class="language-text">mkdir cljcastr
</code></pre><p>And now pop a <code>bb.edn</code> into it:</p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;80ec956af5e6610b040089ba62eecb5d223e9e76&quot;}
        io.github.babashka/http-server
        {:git/sha &quot;b38c1f16ad2c618adae2c3b102a5520c261a7dd3&quot;}}

 :tasks
 {http-server {:doc &quot;Starts http server for serving static files&quot;
               :requires ([babashka.http-server :as http])
               :task (do (http/serve {:port 1341 :dir &quot;resources/public&quot;})
                         (println &quot;Serving static assets at http://localhost:1341&quot;))}

  browser-nrepl {:doc &quot;Start browser nREPL&quot;
                 :requires ([sci.nrepl.browser-server :as bp])
                 :task (bp/start! {})}

  -dev {:depends [browser-nrepl http-server]}

  dev {:doc &quot;Development build. Starts webserver and watches for changes.&quot;
       :task (do (run &apos;-dev {:parallel true})
                 (deref (promise)))}}
}
</code></pre><p>Now create a <code>resources/public</code> directory:</p><pre><code class="language-text">mkdir -p resources/public/
</code></pre><p>Drop an <code>index.html</code> in that directory:</p><pre><code class="language-html">&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;

&lt;head&gt;
  &lt;title&gt;cljcastr episode player&lt;/title&gt;

  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
  &lt;script&gt;var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;&lt;/script&gt;
  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;

  &lt;script type=&quot;application/x-scittle&quot; src=&quot;player.cljs&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>And finally, a <code>player.cljs</code> in the same directory that does naught but declare a namespace:</p><pre><code class="language-clojure">(ns cljcastr.player)

(js/console.log &quot;Ready to play!&quot;)
</code></pre><p>Thus equipped, invoke Babashka from the top-level <code>cljcastr</code> directory thusly:</p><pre><code class="language-text">bb dev
</code></pre><p>Babashka will helpfully tell you where you can find your player:</p><pre><code class="language-text">Serving static assets at http://localhost:1341
nREPL server started on port 1339...
Websocket server started on 1340...
</code></pre><p>If you browse to <a href="http://localhost:1341">localhost:1341</a>, you&apos;ll see an amazingly blank page titled &quot;cljcastr episode player&quot;. If you open the JavaScript console in dev tools (<strong>Ctrl + Shift + i</strong> in many browsers), you should see the player reporting for duty:</p><pre><code class="language-text">  Ready to play!                                                    core.cljs:80
&gt; 
</code></pre><p>So let&apos;s play!</p><div class="markdown-heading"><h2 id="interactive-development">Interactive development</h2><a href="#interactive-development" class="anchor" aria-label="Permalink: Interactive development"><img src="assets/link.svg" /></a></div><p>In addition to the HTTP server serving up static files from our <code>resources/public</code> directory, we have an nREPL server listening on port 1339 and a websocket server on port 1340. When we loaded the <code>index.html</code> webpage in the browser, <code>scittle.nrepl</code> opened a websocket connection to port 1340 and started listening for commands. In order to send it some commands, we will need to connect an nREPL client to the nREPL server on port 1339. Let&apos;s do it!</p><p>This section assumes that you are a reasonable person and are thus using Emacs with <a href="https://github.com/clojure-emacs/cider">CIDER</a>, but if you&apos;ve unreasonably chosen to use a lesser editor or one of those new-fangled &quot;IDEs&quot; like <a href="https://cursive-ide.com">Cursive</a> or <a href="https://calva.io">Calva</a>, you probably know how to operate nREPL in that editor, so just translate accordingly.</p><p>First, we open up <code>player.cljs</code> in our editor. Next, we use CIDER&apos;s <code>cider-connect-cljs</code> command (<strong>C-c M-C</strong>) to connect to <code>localhost</code> on port <code>1339</code>, choosing REPL type <code>nbb</code> when prompted. CIDER should open a REPL buffer that says something like this:</p><pre><code class="language-text">;; Connected to nREPL server - nrepl://localhost:1339
;; CIDER 1.12.0 (Split)
;;
;; ClojureScript REPL type: nbb
;;
nil&gt; 
</code></pre><p>Now we&apos;re all set up for interactive development, so let&apos;s interact. First, execute <code>cider-load-buffer</code> (<strong>C-c C-k</strong>) in the <code>player.cljs</code> buffer. If you&apos;re watching the JS console in your browser, you&apos;ll see something like the following pop up:</p><pre><code class="language-text">  Ready to play!                                                   nrepl.cljs:10
&gt; 
</code></pre><p>And meanwhile in your terminal, you&apos;ll see the nREPL server log some output:</p><pre><code class="language-text">:msg &quot;{:value \&quot;nil\&quot;, :id \&quot;246\&quot;, :session \&quot;e443955d-e285-4d5b-bbde-9b7f21f1561c\&quot;, :ns \&quot;cljcastr.player\&quot;}&quot;
:msg &quot;{:status [\&quot;done\&quot;], :id \&quot;246\&quot;, :session \&quot;e443955d-e285-4d5b-bbde-9b7f21f1561c\&quot;, :ns \&quot;cljcastr.player\&quot;}&quot;
</code></pre><p>We&apos;ve now completed the circle of LISP, meaning we can control everything on our player page with ClojureScript! 💥</p><p>Let&apos;s try some simple arithmetic just to get a sense of the power at our fingertips. In the <code>player.cljs</code> buffer, we&apos;ll add a <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a> and some code:</p><pre><code class="language-clojure">(comment

  (+ 1 2)

  )
</code></pre><p>Positioning our cursor right after the <code>(+ 1 2)</code> form, we hit <strong>C-c C-v f c e</strong> to execute <code>cider-pprint-eval-last-sexp-to-comment</code>, and are rewarded by a nice comment being inserted on the next line:</p><pre><code class="language-clojure">(comment

  (+ 1 2)
  ;; =&gt; 3

  )
</code></pre><p>We can also print this result to the browser console by adding another line inside the <code>(comment)</code> form:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (js/console.log (+ 1 2))

  )
</code></pre><p>If you&apos;re using CIDER with an autocomplete setup, you should actually see completion candidates popping up as you type. 🤯</p><p>If you position the cursor after the form and evaluate it again with <strong>C-c C-v f c e</strong>, you&apos;ll get a comment on the next line saying</p><pre><code class="language-clojure">  ;; =&gt; nil
</code></pre><p>This is somewhat underwhelming, but if you take a peek at your browser console, you&apos;ll be more satisfied:</p><pre><code class="language-text">  3                                                                nrepl.cljs:10
&gt; 
</code></pre><p>Can we have our cake and eat it too? (Note that from here on, I&apos;ll assume you&apos;re whacking <strong>C-c C-v f c e</strong> after the new form you add, which will produce the <code>;; =&gt;</code> comment on the next line.)</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (doto (+ 1 2)
    js/console.log)
  ;; =&gt; 3

  )
</code></pre><p>Now we&apos;re cooking with biofuel!</p><p>Let&apos;s try something a little more complex:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (doto (map inc (range 5))
    js/console.log)
  ;; =&gt; (1 2 3 4 5)

  )
</code></pre><p>This is great, but what in the world is happening over in the browser console?</p><pre><code class="language-text">  ‣ $APP.gg {J: null, na: null, I: null, F: 32374988, ma: ƒ, …}    nrepl.cljs:10
&gt; 
</code></pre><p>If we click on the ‣, things get even wilder:</p><pre><code class="language-text">  ‣ $APP.gg {J: null, na: null, I: null, F: 32374988, ma: ƒ, …}    nrepl.cljs:10
      F: 32374988
      I: null
      J: null
      M: 1
      ma: null
    ‣ na: $APP.lg {hc: kg, Zc: $…P.gg, J: null, I: null, F: 31850732, …}
    ‣ [[Prototype]]: Object
&gt;
</code></pre><p>What we&apos;re seeing is a JavaScript representation of a ClojureScript vector. This is of course super cool and all, but not so readable (unless you&apos;re Rich Hickey and you don&apos;t even see the <a href="https://www.cosmiclearn.com/clojure/immutability.php">persistent data
structures</a> but just the <a href="https://matrix.fandom.com/wiki/Woman_in_Red">woman in the red dress</a>). Let&apos;s see if we can do better:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (doto (-&gt;&gt; (map inc (range 5))
             clj-&gt;js)
    js/console.log)
  ;; =&gt; #js [1 2 3 4 5]

  )
</code></pre><p>The browser console is looking good!</p><pre><code class="language-text">  ‣ (5) [1, 2, 3, 4, 5]                                            nrepl.cljs:10
</code></pre><p>But life inside our <code>(comment)</code> form is less idyllic. What&apos;s up with this nonsense?</p><pre><code class="language-clojure">  ;; =&gt; #js [1 2 3 4 5]
</code></pre><p>Now we&apos;re seeing ClojureScript&apos;s JavaScript data literal. 😅</p><p>Let&apos;s try one more thing:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (let [res (map inc (range 5))]
    (js/console.log (clj-&gt;js res))
    res)
  ;; =&gt; (1 2 3 4 5)

  )
</code></pre><p>That&apos;s much better! Now how about we extract this to a function so we can use it to log stuff?</p><pre><code class="language-clojure">(ns cljcastr.player)

(defn log [v]
  (js/console.log (clj-&gt;js v))
  v)

(comment

  ;; ...

  (log (map inc (range 5)))
  ;; =&gt; (1 2 3 4 5)

  )
</code></pre><p>Good stuff. Thus equipped, we can start sprucing up this empty webpage.</p><div class="markdown-heading"><h2 id="getting-down-to-brass-html">Getting down to brass HTML</h2><a href="#getting-down-to-brass-html" class="anchor" aria-label="Permalink: Getting down to brass HTML"><img src="assets/link.svg" /></a></div><p>Let&apos;s add an <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements">h1</a> HTML element to the page to let users know what&apos;s up. The obvious way to do this would be to open up <code>index.html</code> and drop in something like this:</p><pre><code class="language-html">&lt;body&gt;
  &lt;h1&gt;cljcastr player&lt;/h1&gt;
&lt;/body&gt;
</code></pre><p>However, this would require a page reload for us to see the changes, and that would blow away the state we&apos;ve carefully built up in our REPL. 😭</p><p>Let&apos;s see if we can do this in the REPL instead. The basic idea is this:</p><ol start="1"><li>Create an <strong>h1</strong> element.</li><li>Set its inner text to &quot;cljcastr player&quot;.</li><li>Grab the <strong>body</strong> element that we helpfully put in our HTML page skeleton.</li><li>Add the new <strong>h1</strong> element as a child of the <strong>body</strong> element.</li></ol><p>And if we were to call an imaginary <code>eng-&gt;clj</code> function, that would look something like this:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  ;; 1. Create an **h1** element.
  (def h1 (js/document.createElement &quot;h1&quot;))
  ;; =&gt; #&apos;cljcastr.player/h1

  ;; 2. Set its inner text to &quot;cljcastr player&quot;.
  (set! (.-textContent h1) &quot;cljcastr player&quot;)
  ;; =&gt; &quot;cljcastr player&quot;

  ;; 3. Grab the **body** element that we helpfully put in our HTML page skeleton.
  (def body (js/document.querySelector &quot;body&quot;))
  ;; =&gt; #&apos;cljcastr.player/body

  ;; 4. Add the new **h1** element as a child of the **body** element.
  (.appendChild body h1)
  ;; =&gt; #object[HTMLHeadingElement [object HTMLHeadingElement]]

  )
</code></pre><p>Et voilà! Our boring page has been transformed into an amazing feast for the eyes!</p><p>Before moving on, let&apos;s take a brief detour into a new JavaScript literal:</p><pre><code class="language-clojure">  ;; =&gt; #object[HTMLHeadingElement [object HTMLHeadingElement]]
</code></pre><p>This is a bit opaque, but we can always feed it to our <code>log</code> function to make it nicely inspectable in the console:</p><pre><code class="language-clojure">(comment

  ;; ...
  
  (log h1)
  ;; =&gt; #object[HTMLHeadingElement [object HTMLHeadingElement]]

  )
</code></pre><p>The console will render this as:</p><pre><code class="language-text">  &lt;h1&gt;cljcastr player&lt;/h1&gt;                                         nrepl.cljs:10
</code></pre><div class="markdown-heading"><h2 id="play-that-funky-music">Play that funky music</h2><a href="#play-that-funky-music" class="anchor" aria-label="Permalink: Play that funky music"><img src="assets/link.svg" /></a></div><p>Let&apos;s find ourselves the URL of a random podcast episode and add an <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/audio">audio</a> element to the page:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def audio (js/document.createElement &quot;audio&quot;))
  ;; =&gt; #&apos;cljcastr.player/audio

  (set! (.-controls audio) true)
  ;; =&gt; true

  (set! (.-src audio)
        &quot;https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3&quot;)

  (-&gt;&gt; audio
       (.appendChild body))
  ;; =&gt; #object[HTMLAudioElement [object HTMLAudioElement]]

  (log audio)
  ;; =&gt; #object[HTMLAudioElement [object HTMLAudioElement]]

)
</code></pre><p>Now we should see an audio player pop up on screen!</p><p><img alt="Simple podcast player with a heading and an audio player" src="assets/2026-11-01-scittlecastr-1.png" title="Click play, I dare you!" class="border" /></p><p>And if we click play, we hear the <a href="https://zencastr.com/defn">defn</a> theme music.</p><p>We could declare victory right here, but we&apos;re missing a few things that a podcast player usually has, such as:</p><ol start="1"><li>Sweet custom controls instead of the ugly HTML5 default audio player.</li><li>The ability to play any podcast episode, not just one we&apos;ve helpfully downloaded ahead of time.</li><li>If a transcript is available, display it with clickable timestamps.</li></ol><p>Let&apos;s see what we can do about that.</p><div class="markdown-heading"><h2 id="escaping-from-vanilla">Escaping from vanilla</h2><a href="#escaping-from-vanilla" class="anchor" aria-label="Permalink: Escaping from vanilla"><img src="assets/link.svg" /></a></div><p>The standard HTML audio control is functional, but a bit boring. In our hubris, we decide we can do way better than that!</p><p>Let&apos;s look at <a href="https://overcast.fm/+AAdZ_Hp6MfY">a typical podcast player</a> for inspiration:</p><p><img alt="Overcast podcast player" src="assets/2026-11-01-scittlecastr-overcast.png" title="That&apos;s a nice looking player!" class="border" /></p><p>It looks like we&apos;ll want the following buttons:</p><ul><li>Play</li><li>Pause</li><li>Skip backward</li><li>Skip forward</li><li>Playback speed</li></ul><p>Let&apos;s see if we can find some nice vector graphics for our buttons. <a href="https://www.svgrepo.com/">SVG
Repo</a> is a great place to start, and a search there for &quot;play&quot; turns up a nice looking SVG named <a href="https://www.svgrepo.com/svg/436852/play-circle-fill">Play Circle Fill
SVG</a>, which is provided under the <a href="https://www.svgrepo.com/page/licensing/#MIT">MIT Licence</a>. That looks promising!</p><p>Better yet, the SVG is part of a collection called [Framework7 Filled Icons] (<a href="https://www.svgrepo.com/collection/framework7-filled-icons/">https://www.svgrepo.com/collection/framework7-filled-icons/</a>). Let&apos;s click into that and see if we can find some SVGs for other useful media player buttons. Searching within the collection, we find a nice <a href="https://www.svgrepo.com/svg/436829/pause-circle-fill">Pause button</a>, but nothing for the other three we need. 😭</p><p>No matter! We widen our search to all of SVG Repo and find nice graphics for the rest. Here&apos;s where we land:</p><ul><li><a href="https://www.svgrepo.com/svg/436852/play-circle-fill">Play</a></li><li><a href="https://www.svgrepo.com/svg/436829/pause-circle-fill">Pause</a></li><li><a href="https://www.svgrepo.com/svg/495321/forward-15-seconds">Skip forward</a> (from <a href="https://www.svgrepo.com/collection/iconsax-bold-oval-icons/">Iconsax Bold Oval Icons</a>)</li><li><a href="https://www.svgrepo.com/svg/495036/backward-15-seconds">Skip backward</a> (from <a href="https://www.svgrepo.com/collection/iconsax-bold-oval-icons/">Iconsax Bold Oval Icons</a>)</li><li><a href="https://www.svgrepo.com/svg/151785/speed-meter">Playback speed</a> (from <a href="https://www.svgrepo.com/collection/awesome-set/">Awesome Set</a>)</li></ul><p>Let&apos;s create a set of HTML images for each. We&apos;ll start by defining a map to describe them:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def playback-controls
    {:play {:src &quot;https://www.svgrepo.com/show/436852/play-circle-fill.svg&quot;
            :label &quot;Play&quot;}
     :pause {:src &quot;https://www.svgrepo.com/show/436829/pause-circle-fill.svg&quot;
             :label &quot;Pause&quot;}
     :forward {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
               :label &quot;Forward {{seek-dur-sec}} seconds&quot;}
     :backward {:src &quot;https://www.svgrepo.com/show/495036/backward-15-seconds.svg&quot;
             :label &quot;Back {{seek-dur-sec}} seconds&quot;}
     :speed {:src &quot;https://www.svgrepo.com/show/151785/speed-meter.svg&quot;
             :label &quot;Playback speed&quot;}})
  ;; =&gt; #&apos;cljcastr.player/playback-controls

  (def seek-dur-sec 15)
  ;; =&gt; #&apos;cljcastr.player/seek-dur-sec

  )
</code></pre><p>Now we can map over the map (yeah yeah, I know) to create our <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/img">img</a> elements:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def playback-buttons
    (-&gt;&gt; playback-controls
         (map (fn [[control-name {:keys [src label]}]]
                (let [el (js/document.createElement &quot;img&quot;)]
                  (set! (.-id el) (str &quot;button-&quot; (name control-name)))
                  (set! (.-classList el) &quot;cljcastr playback-icon&quot;)
                  (set! (.-src el) src)
                  (set! (.-draggable el) false)
                  el)))
         log))
  ;; =&gt; #&apos;cljcastr.player/playback-buttons

  )
</code></pre><p>Note that we&apos;re adding a <code>playback-icon</code> class to the element in addition to our standard <code>cljcastr</code> class, and also giving the element an ID so it&apos;s easy to grab it with a CSS selector later. We also set the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/draggable">draggable</a> attribute to <code>false</code> to prevent drag-and-drop silliness from happening.</p><p>Now, how about a container to hold them?</p><pre><code class="language-clojure">(comment

  ;; ...

  (def playback-controls-container
    (-&gt; (let [el (js/document.createElement &quot;div&quot;)]
          (set! (.-id el) &quot;playback-controls&quot;)
          (set! (.-classList el) &quot;cljcastr&quot;)
          el)
        log))
  ;; =&gt; #&apos;cljcastr.player/playback-controls-container

  (doseq [el playback-buttons]
    (.appendChild playback-controls-container el))
  ;; =&gt; nil

  )
</code></pre><p>Finally, let&apos;s display the controls!</p><pre><code class="language-clojure">(comment

  ;; ...

  (.appendChild body playback-controls-container)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p><img alt="Player with a huge play button" src="assets/2026-11-01-scittlecastr-huge.png" title="That&apos;s frickin&apos; uuuuge!" class="border" /></p><p>Let&apos;s set the width of the images to a more reasonable size:</p><pre><code class="language-clojure">(comment

  ;; ...

  (doseq [el playback-buttons]
    (set! (.-style el) &quot;width: 35px&quot;))
  ;; =&gt; nil

  )
</code></pre><p>That&apos;s much better! However, this black and white page is starting to bum us out.</p><div class="markdown-heading"><h2 id="rainbows-and-unicorns">Rainbows and unicorns</h2><a href="#rainbows-and-unicorns" class="anchor" aria-label="Permalink: Rainbows and unicorns"><img src="assets/link.svg" /></a></div><p>Since our controls are SVGs, we can use the magic of <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/filter">CSS
filters</a> to colour them.</p><p>Let&apos;s start by picking a colour, and what better colour for the sake of this demo than a lovely amber sort of shade called <code>#f7931e</code>. Of course, CSS filters can&apos;t be specified in something as prosaic as hex colour codes, so we&apos;ll use a <a href="https://codepen.io/sosuke/pen/Pjoqqp">magic CodePen thingy</a> to generate a filter from our hex code. (We could also port the JavaScript from <a href="https://stackoverflow.com/questions/42966641/how-to-transform-black-into-any-given-color-using-only-css-filters/43960991#43960991">this
spectacular StackOverflow
answer</a> to ClojureScript, but we kinda don&apos;t feel like it.)</p><p>What we come up with is this:</p><pre><code class="language-css">filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
</code></pre><p>We can now add this as a style to our <strong>img</strong> tags:</p><pre><code class="language-clojure">(comment

  ;; ...

  (doseq [el playback-buttons]
    (set! (.-style el)
          (str &quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%) &quot;
               &quot;hue-rotate(343deg) brightness(97%) contrast(99%);&quot;)))
  ;; =&gt; nil

  )
</code></pre><p>Better!</p><p><img alt="Player with a orange playback controls" src="assets/2026-11-01-scittlecastr-orange.png" title="Trapped in amber" class="border" /></p><p>One thing that&apos;s slightly annoying is that we had to remember to include to include the width style when we added the filters. Why don&apos;t we write some code that adds a style to an existing element whilst preserving existing styles?</p><p>First, let&apos;s help ourselves out by pulling in <code>clojure.string</code>:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...

(comment

  ;; ...

  ;; What do styles look like?
  (-&gt; playback-buttons
      first
      (.getAttribute &quot;style&quot;))
  ;; =&gt; &quot;width: 35px; filter: invert(59%) sepia(92%) saturate(611%)
  ;;     hue-rotate(343deg) brightness(97%) contrast(99%);&quot;

  ;; Parse into a list of styles
  (-&gt; playback-buttons
      first
      (.getAttribute &quot;style&quot;)
      (str/split #&quot;;\s+&quot;))
  ;; =&gt; [&quot;width: 35px&quot;
  ;;     &quot;filter: invert(59%) sepia(92%) saturate(611%)
  ;;      hue-rotate(343deg) brightness(97%) contrast(99%);&quot;]

  ;; Turn it into a map
  (let [styles (-&gt; playback-buttons
                   first
                   (.getAttribute &quot;style&quot;)
                   (str/split #&quot;;\s+&quot;))]
    (-&gt;&gt; styles
         (map #(let [[k v] (str/split % #&quot;:\s+&quot;)]
                 [(keyword k) v]))
         (into {})))
  ;; =&gt; {:width &quot;35px&quot;,
  ;;     :filter &quot;invert(59%) sepia(92%) saturate(611%)
  ;;              hue-rotate(343deg) brightness(97%) contrast(99%);&quot;}

  )
</code></pre><p>Now we have a thing that we can easily turn into a function!</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; (defn log ...)

(defn get-styles
  &quot;Returns the inline styles of an element as a map of style name to value.&quot;
  [el]
  (let [styles (-&gt; el
                   (.getAttribute &quot;style&quot;)
                   (str/split #&quot;;\s+&quot;))]
    (-&gt;&gt; styles
         (map #(let [[k v] (str/split % #&quot;:\s+&quot;)]
                 [(-&gt; (str/trim k) keyword) (str/trim v)]))
         (into {}))))

;; ...

(comment

  ;; ...

  (-&gt; playback-buttons
      first
      get-styles)
  ;; =&gt; {:width &quot;35px&quot;,
  ;;     :filter &quot;invert(59%) sepia(92%) saturate(611%)
  ;;              hue-rotate(343deg) brightness(97%) contrast(99%);&quot;}

  )
</code></pre><p>How about going the other direction, i.e. turning a map of styles into a style string?</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt;&gt; {:width &quot;35px&quot;, :height &quot;35px&quot;}
       (map (fn [[k v]]
              (str (name k) &quot;: &quot; v)))
       (str/join &quot;; &quot;))
  ;; =&gt; &quot;width: 35px; height: 35px&quot;

  )
</code></pre><p>From this, &apos;tis merely a hop, skip, and a jump to write a function that sets the styles of an element:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; (defn get-styles ...)

(defn set-styles!
  &quot;Sets the styles of an element from a map of style name to value.&quot;
  [el styles]
  (let [styles-str (-&gt;&gt; styles
                        (map (fn [[k v]]
                               (str (name k) &quot;: &quot; v)))
                        (str/join &quot;; &quot;))]
    (set! (.-style el) styles-str))
  el)

;; ...

(comment

  ;; ...

  ;; Back to black!
  (doseq [el playback-buttons]
    (set-styles! el {:width &quot;35px&quot;}))
  ;; =&gt; nil

  )
</code></pre><p>Finally, let&apos;s put this together and create a function that adds a style instead of replacing all the existing ones:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-styles! ...)

(defn add-style!
  &quot;Adds a style to an element&quot;
  [el style-name style-value]
  (let [styles (get-styles el)]
    (set-styles! el (assoc styles (name style-name) style-value)))
  el)

;; ...

(comment

  ;; ...

  ;; Amber is the new black
  (doseq [el playback-buttons]
    (add-style! el :filter
                (str &quot;invert(59%) sepia(92%) saturate(611%) &quot;
                     &quot;hue-rotate(343deg) brightness(97%) contrast(99%)&quot;)))
  ;; =&gt; nil

  )
</code></pre><div class="markdown-heading"><h2 id="play-it-again,-sam">Play it again, Sam</h2><a href="#play-it-again,-sam" class="anchor" aria-label="Permalink: Play it again, Sam"><img src="assets/link.svg" /></a></div><p>Now that we have visually stunning buttons, let&apos;s actually make them do something.</p><p>Or rather, let&apos;s do something that allows us to make them do something. 😅</p><p>Remember how we added a <code>cljcastr</code> class to the buttons so we could easier grab them with <code>js/document.querySelector</code>? Well, we didn&apos;t do this to our poor <strong>audio</strong> element, which will now cause us a problem:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (js/document.querySelector &quot;audio&quot;)
      log)
  ;; =&gt; #object[HTMLAudioElement [object HTMLAudioElement]]

  )
</code></pre><p>Seems OK in the REPL, but if we look at the JS console, things (might not, depending on your browser and which extensions you have installed) look so good:</p><pre><code class="language-text">  &lt;audio class=&quot;audio-for-speech&quot; src&gt;&lt;/audio&gt;                     nrepl.cljs:10
</code></pre><p>Seems like my browser is set up with a screen reader, which is very nice for accessibility, but not nice for Clojure programmers who didn&apos;t get enough <a href="https://youtu.be/f84n5oFoZBc">hammock time</a>. Let&apos;s add a class so we can use a more precise selector:</p><pre><code class="language-clojure">(comment

  ;; ...

  (set! (.-classList audio) &quot;cljcastr&quot;)
  ;; =&gt; &quot;cljcastr&quot;

  (-&gt; (js/document.querySelector &quot;audio.cljcastr&quot;)
      log)
  ;; =&gt; #object[HTMLAudioElement [object HTMLAudioElement]]

  )
</code></pre><p>And now the console looks more like what we expected:</p><pre><code class="language-text">  &lt;audio class=&quot;cljcastr&quot; controls                                 nrepl.cljs:10
  src=&quot;https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3&quot;&gt;
  &lt;/audio&gt;
</code></pre><p>Now we can proceed with making our buttons come alive:</p><pre><code class="language-clojure">(comment

  ;; ...

  ;; Grab the play button
  (def play-button (js/document.querySelector &quot;#button-play&quot;))
  ;; =&gt; #&apos;cljcastr.player/play-button

  ;; Add a click handler
  (.addEventListener play-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (.play (js/document.querySelector &quot;audio.cljcastr&quot;))))
  ;; =&gt; nil

  )
</code></pre><p>If we click the button, we hear the podcast start playing, and can see the playback position in the standard HTML audio element above.</p><p><img alt="Player playing an episode" src="assets/2026-11-01-scittlecastr-play.png" title="Play ball!" class="border" /></p><p>Now we can do the same for the pause button:</p><pre><code class="language-clojure">(comment

  ;; ...

  ;; Grab the pause button
  (def pause-button (js/document.querySelector &quot;#button-pause&quot;))
  ;; =&gt; #&apos;cljcastr.player/play-button

  ;; Add a click handler
  (.addEventListener pause-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (.pause (js/document.querySelector &quot;audio.cljcastr&quot;))))
  ;; =&gt; nil

  )
</code></pre><p>That was easy! Skipping forward will be a little more interesting, since there&apos;s no JS function to tell the audio object &quot;skip forward x seconds&quot;, there&apos;s only a <code>currentTime</code> property that we can query and set:</p><pre><code class="language-clojure">(comment

  ;; ...

  (.-currentTime audio)
  ;; =&gt; 29.396358

  (set! (.-currentTime audio) 15.0)
  ;; =&gt; 15

  )
</code></pre><p>Given this, it&apos;s not too hard to figure out how to skip forward and backward an arbitrary number of seconds:</p><pre><code class="language-clojure">(comment

  ;; ...

  ;; Forward
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (+ cur seek-dur-sec)))
  ;; =&gt; 30

  ;; Backward
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (- cur seek-dur-sec)))
  ;; =&gt; 15

  )
</code></pre><p>It&apos;s probably a good idea not to skip forward past the end of the episode or backward past the beginning, so let&apos;s see if we can put a stop to that silliness:</p><pre><code class="language-clojure">(comment

  ;; ...

  ;; Forward with guard
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (min (+ cur seek-dur-sec)
                                     (.-duration audio))))
  ;; =&gt; 30

  ;; The end is nigh!
  (set! (.-currentTime audio) (- (.-duration audio) 5))
  ;; =&gt; 5365.949958

  ;; Don&apos;t worry, all is well
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (min (+ cur seek-dur-sec)
                                     (.-duration audio))))
  ;; =&gt; 5370.949958

  ;; Hitting 88 miles per hour
  (set! (.-currentTime audio) 5)
  ;; =&gt; 5

  ;; Backward
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (max (- cur seek-dur-sec)
                                     0)))
  ;; =&gt; 0

  )
</code></pre><p>Armed with this code, let&apos;s make some functions:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn skip-forward! [audio-el sec]
  (let [cur (.-currentTime audio-el)]
    (set! (.-currentTime audio-el) (min (+ cur sec)
                                        (.-duration audio-el)))))

(defn skip-backward! [audio-el sec]
  (let [cur (.-currentTime audio-el)]
    (set! (.-currentTime audio-el) (max (- cur sec)
                                        0))))

;; ...

(comment

  ;; ...

  (skip-forward! audio seek-dur-sec)
  ;; =&gt; 15

  (skip-backward! audio seek-dur-sec)
  ;; =&gt; 0

  )
</code></pre><p>Now we can wire up the skip buttons as well:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def forward-button (js/document.querySelector &quot;#button-forward&quot;))
  ;; =&gt; #&apos;cljcastr.player/forward-button

  (def backward-button (js/document.querySelector &quot;#button-backward&quot;))
  ;; =&gt; #&apos;cljcastr.player/backward-button

  (.addEventListener forward-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (skip-forward! audio seek-dur-sec)))
  ;; =&gt; nil

  (.addEventListener backward-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (skip-backward! audio seek-dur-sec)))
  ;; =&gt; nil

  )
</code></pre><p>Look at this! All of our buttons work! (Except the playback speed one, but that&apos;s a little more complicated, so let&apos;s save it for later. 😉)</p><p>The only thing that&apos;s obviously wrong with this amazing player is that it has two sets of controls, the standard HTML one and our amazing buttons. There&apos;s also something that&apos;s not obviously wrong to most readers, unless they happen to be using a screen reader: the accessibility of our buttons sucks! In fact, the only way we know they&apos;re buttons is by their appearance, because we&apos;re using <strong>img</strong> elements, which are semantically just images. They could be images of an elephant for all a screen reader knows.</p><p>Let&apos;s see what we can do about that!</p><div class="markdown-heading"><h2 id="a11y-spells-ally">A11y spells ally</h2><a href="#a11y-spells-ally" class="anchor" aria-label="Permalink: A11y spells ally"><img src="assets/link.svg" /></a></div><p>From the excellent MDN article on <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility">Accessibility</a>:</p><blockquote><p><strong>Accessibility</strong> (often abbreviated to <strong>A11y</strong> — as in, &quot;a&quot;, then 11 characters, and then &quot;y&quot;) in web development means enabling as many people as possible to use websites, even when those people&apos;s abilities are limited in some way.</p><p>For many people, technology makes things easier. For people with disabilities, technology makes things possible. Accessibility means developing content to be as accessible as possible, no matter an individual&apos;s physical and cognitive abilities and how they access the web.</p></blockquote><p>The <a href="https://www.w3.org/standards/webdesign/accessibility">W3C Accessibility
Initiative</a> puts it in even more inspiring terms:</p><blockquote><p><strong>The Web is fundamentally designed to work for all people</strong>, whatever their hardware, software, language, location, or ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability.</p></blockquote><p>We certainly want <strong>all</strong> people to adopt our superior podcast player, so let&apos;s make sure it works for them, using the power of ARIA!</p><p><img alt="Arya Stark after killing the Frey soldier with a knife" src="assets/2026-11-01-scittlecastr-arya.png" title="A girl always pays her debts" class="border" /></p><p>No, not that one. 😉</p><p>This one: <a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Accessibility/WAI-ARIA_basics">ARIA</a>.</p><p>If we wrap each of our <strong>img</strong> elements in a <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/button">button</a> element, we&apos;re now conveying semantic meaning to a screen reader (or any other user agent, for that matter; imagine a script that is trying to identify all the buttons on a page... such as the one we&apos;re in the process of writing). And if we set that button&apos;s <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-label">aria-label</a> attribute, we&apos;re now identifying what the button is meant to do.</p><p>Remember the <code>:label</code> key we included in our <code>playback-controls</code> map but never used way back when?</p><pre><code class="language-clojure">(comment

  ;; ...

  (def playback-controls
    {:play {:src &quot;https://www.svgrepo.com/show/436852/play-circle-fill.svg&quot;
            :label &quot;Play&quot;}
     :pause {:src &quot;https://www.svgrepo.com/show/436829/pause-circle-fill.svg&quot;
             :label &quot;Pause&quot;}
     :forward {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
               :label &quot;Forward {{seek-dur-sec}} seconds&quot;}
     :backward {:src &quot;https://www.svgrepo.com/show/495036/backward-15-seconds.svg&quot;
             :label &quot;Back {{seek-dur-sec}} seconds&quot;}
     :speed {:src &quot;https://www.svgrepo.com/show/151785/speed-meter.svg&quot;
             :label &quot;Playback speed&quot;}})
  ;; =&gt; #&apos;cljcastr.player/playback-controls

  )
</code></pre><p>Turns out we had accessibility in mind all along!</p><p>Let&apos;s try wrapping a button:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [button-name :play
        {:keys [src label]} {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
                             :label &quot;Forward {{seek-dur-sec}} seconds&quot;}]
    (let [button-id (str &quot;button-&quot; (name button-name))
          button-el (js/document.createElement &quot;button&quot;)
          img-el (js/document.createElement &quot;img&quot;)]
      (set! (.-id button-el) button-id)
      (set! (.-classList button-el) &quot;cljcastr&quot;)
      (set! (.-ariaLabel button-el) label)
      (set! (.-id img-el) (str button-id &quot;-icon&quot;))
      (set! (.-classList img-el) &quot;cljcastr playback-icon&quot;)
      (set! (.-src img-el) src)
      (set! (.-draggable img-el) false)
      (.appendChild button-el img-el)
      (log button-el)))
  ;; =&gt; #object[HTMLButtonElement [object HTMLButtonElement]]

  )
</code></pre><p>All of this <code>set!</code> stuff is starting to get annoying. Why don&apos;t we write a nice function that we can call to give us back a fully baked DOM element?</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn create-el [{:keys [tag attrs] :as args}]
  (let [el (js/document.createElement tag)]
    (doseq [[attr v] attrs]
      (.setAttribute el (name attr) v))
    el))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (let [button-name :play
        {:keys [src label]} {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
                             :label &quot;Forward {{seek-dur-sec}} seconds&quot;}]
    (let [button-id (str &quot;button-&quot; (name button-name))
          button-el (create-el {:tag &quot;button&quot;
                                :attrs {:id button-id
                                        :class &quot;cljcastr&quot;
                                        :aria-label label}})
          img-el (create-el {:tag &quot;img&quot;
                             :attrs {:id (str button-id &quot;-icon&quot;)
                                     :class &quot;cljcastr playback-icon&quot;
                                     :src src
                                     :draggable false}})]
      (.appendChild button-el img-el)
      (log button-el)))
  ;; =&gt; #object[HTMLButtonElement [object HTMLButtonElement]]

  )
</code></pre><p>This looks pretty reasonable in the JS console:</p><pre><code class="language-text">  ‣ &lt;button class=&quot;cljcastr&quot; id=&quot;button-play&quot;                      nrepl.cljs:10
            aria-label=&quot;Forward {{seek-dur-sec}} seconds&quot;&gt;
      &lt;img class=&quot;cljcastr playback-icon&quot; id=&quot;button-play-icon&quot;
           src=&quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
           draggable=&quot;false&quot;&gt;
    &lt;/button&gt;
</code></pre><p>Except this bit, that is:</p><pre><code class="language-text">aria-label=&quot;Forward {{seek-dur-sec}} seconds&quot;
</code></pre><p>Looks like we got a bit clever there with some <a href="https://github.com/yogthos/Selmer">Selmer</a>-style templating to allow for changing the number of seconds we&apos;re skipping around. Let&apos;s quickly figure out how to interpolate such strings:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [s &quot;Something {{something}} something&quot;]
    (str/replace s &quot;{{something}}&quot; &quot;SOMETHING&quot;))
  ;; =&gt; &quot;Something SOMETHING something&quot;

  (let [s &quot;Something {{something}} something&quot;
        ctx {:something &quot;SOMETHING&quot;}]
    (str/replace s #&quot;\{\{(something)\}\}&quot; (fn [[_ k]] (get ctx (keyword k)))))
  ;; =&gt; &quot;Something SOMETHING something&quot;

  )
</code></pre><p>This may appear slightly inscrutable at first glance, but if we look at the documentation for <a href="https://clojuredocs.org/clojure.string/replace">clojure.string/replace</a>, we see that the <code>replacement</code> argument can actually be a function, in which case it&apos;s passed the match as an argument and whatever it returns is the replacement string. When the match contains a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group">capturing
group</a>, the argument to the function is a vector of <code>[match group1 group2 ...]</code>. For example:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [s &quot;It&apos;s easy as 123, ABC, baby you and me&quot;]
    (str/replace s #&quot;(\d)+.+([A-Z]+)&quot;
                 (fn [match-vector] (str &quot;&lt;&lt;&lt;&quot; (pr-str match-vector) &quot;&gt;&gt;&gt;&quot;))))
  ;; =&gt; &quot;It&apos;s easy as &lt;&lt;&lt;[\&quot;123, ABC\&quot; \&quot;3\&quot; \&quot;C\&quot;]&gt;&gt;&gt;, baby you and me&quot;

  )
</code></pre><p>Let&apos;s turn this into a proper function:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; (defn log ...)

(defn render
  &quot;Given a string `s` and a context map `ctx`, replaces template variables of the
   form {{k}} with the value of the corresponding key in the context map. If
   the key `k` doesn&apos;t exist in the context map, the template variable won&apos;t be
   replaced (i.e. \&quot;{{foo}}\&quot; will remain \&quot;{{foo}}\&quot; in the interpolated
   string).&quot;
  [s ctx]
  (str/replace s #&quot;\{\{([^}]+)\}\}&quot;
               (fn [[match k]] (get ctx (keyword k) match))))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (render &quot;foo {{bar}} baz {{blah}} {{barf}}&quot; {:bar 27, :blah 42})
  ;; =&gt; &quot;foo 27 baz 42 {{barf}}&quot;

  )
</code></pre><p>Now we can make use of our new <code>render</code> function in our button-wrapping code:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [button-name :play
        {:keys [src label]} {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
                             :label &quot;Forward {{seek-dur-sec}} seconds&quot;}]
    (let [button-id (str &quot;button-&quot; (name button-name))
          button-el (create-el {:tag &quot;button&quot;
                                :attrs {:id button-id
                                        :class &quot;cljcastr&quot;
                                        :aria-label (render label {:seek-dur-sec seek-dur-sec})}})
          img-el (create-el {:tag &quot;img&quot;
                             :attrs {:id (str button-id &quot;-icon&quot;)
                                     :class &quot;cljcastr playback-icon&quot;
                                     :src src
                                     :draggable false}})]
      (.appendChild button-el img-el)
      (log button-el)))
  ;; =&gt; #object[HTMLButtonElement [object HTMLButtonElement]]

  )
</code></pre><p>Quoth the console:</p><pre><code class="language-text">  ‣ &lt;button class=&quot;cljcastr&quot; id=&quot;button-forward&quot;                      nrepl.cljs:10
            aria-label=&quot;Forward 15 seconds&quot;&gt;
      &lt;img class=&quot;cljcastr playback-icon&quot; id=&quot;button-forward-icon&quot;
           src=&quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
           draggable=&quot;false&quot;&gt;
    &lt;/button&gt;
</code></pre><p>Now we can extract a nice function to create a button:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn create-el ...)

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str &quot;button-&quot; (name button-name))
         button-el (create-el {:tag &quot;button&quot;
                               :attrs {:id button-id
                                       :class (render &quot;cljcastr {{button-class}}&quot; ctx)
                                       :aria-label (render label ctx)}})
         img-el (create-el {:tag &quot;img&quot;
                            :attrs {:id (str button-id &quot;-icon&quot;)
                                    :class (render &quot;cljcastr {{img-class}}&quot; ctx)
                                    :src src
                                    :draggable false}})]
     (.addEventListener button-el &quot;click&quot; click-handler)
     (.appendChild button-el img-el)
     button-el)))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (create-button :forward
                      {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
                       :label &quot;Forward {{seek-dur-sec}} seconds&quot;}
                      {:seek-dur-sec seek-dur-sec
                       :button-class &quot;playback-button&quot;
                       :img-class &quot;playback-icon&quot;})
       log)
  ;; =&gt; #object[HTMLButtonElement [object HTMLButtonElement]]

  )
</code></pre><p>We&apos;ve pulled another nice thing out of Clojure&apos;s bag of tricks: <a href="https://clojure.org/guides/learn/functions#_multi_arity_functions">multi-arity
functions</a>:</p><pre><code class="language-clojure">
(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src]} ctx]
   ;; ...
  ))
</code></pre><p>This allows us to call <code>create-button</code> without a context:</p><pre><code class="language-clojure">(create-button :play {:label &quot;Play&quot;, :src &quot;play.svg&quot;})
</code></pre><p>This will call the version of <code>create-button</code> that takes two arguments, which in turn calls the three-argument version, passing along the <code>button-name</code> and <code>button</code> arguments as is, and adding an empty map as the <code>ctx</code> argument.</p><p>OK, now we can use our <code>create-button</code> function to sew new a11y&apos;d buttons onto our <code>playback-controls</code> <strong>div</strong>:</p><pre><code class="language-clojure">(comment

  ;; ...

  ;; Throw away the current crappy buttons
  (.replaceChildren playback-controls-container)
  ;; =&gt; nil

  ;; Let&apos;s fix the order of our buttons whilst we&apos;re at it
  (def playback-buttons
    (-&gt;&gt; [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :button-class &quot;playback-button&quot;
                                                :img-class &quot;playback-icon&quot;})]
                  (-&gt; button-el
                      .-firstChild
                      (set-styles! {:width &quot;35px&quot;
                                    :filter &quot;invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%)&quot;}))
                  button-el)))
         log))
  ;; =&gt; #&apos;cljcastr.player/playback-buttons

  (doseq [el playback-buttons]
    (.appendChild playback-controls-container el))
  ;; =&gt; nil

  ;; Grab the new buttons
  (def play-button (js/document.querySelector &quot;#button-play&quot;))
  ;; =&gt; #&apos;cljcastr.player/play-button

  (def pause-button (js/document.querySelector &quot;#button-pause&quot;))
  ;; =&gt; #&apos;cljcastr.player/play-button

  (def forward-button (js/document.querySelector &quot;#button-forward&quot;))
  ;; =&gt; #&apos;cljcastr.player/forward-button

  (def backward-button (js/document.querySelector &quot;#button-backward&quot;))
  ;; =&gt; #&apos;cljcastr.player/backward-button

  ;; Attach the click handlers to them
  (.addEventListener play-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (.play (js/document.querySelector &quot;audio.cljcastr&quot;))))
  ;; =&gt; nil

  (.addEventListener pause-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (.pause (js/document.querySelector &quot;audio.cljcastr&quot;))))
  ;; =&gt; nil

  (.addEventListener forward-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (skip-forward! (js/document.querySelector &quot;audio.cljcastr&quot;)
                                      seek-dur-sec)))
  ;; =&gt; nil

  (.addEventListener backward-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (skip-backward! (js/document.querySelector &quot;audio.cljcastr&quot;)
                                       seek-dur-sec)))
  ;; =&gt; nil

  )
</code></pre><p><img alt="Player with buttons with backgrounds and borders" src="assets/2026-11-01-scittlecastr-buttons.png" title="But those buttons look like buttons!" class="border" /></p><p>The only problem with this approach is that our buttons now look like, well, buttons. 😅</p><p>Let&apos;s restyle them a bit so they look like they did before:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn create-el ...)

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str &quot;button-&quot; (name button-name))
         button-el (create-el {:tag &quot;button&quot;
                               :attrs {:id button-id
                                       :class (render &quot;cljcastr {{button-class}}&quot; ctx)
                                       :aria-label (render label ctx)}})
         img-el (create-el {:tag &quot;img&quot;
                            :attrs {:id (str button-id &quot;-icon&quot;)
                                    :class (render &quot;cljcastr {{img-class}}&quot; ctx)
                                    :src src
                                    :draggable false}})]
     (set-styles! button-el {:padding 0
                             :margin 0
                             :border 0
                             :background &quot;transparent&quot;
                             :cursor &quot;pointer&quot;})
     (.addEventListener button-el &quot;click&quot; click-handler)
     (.appendChild button-el img-el)
     button-el)))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (.replaceChildren playback-controls-container)
  ;; =&gt; nil

  (def playback-buttons
    (-&gt;&gt; [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :button-class &quot;playback-button&quot;
                                                :img-class &quot;playback-icon&quot;})]
                  (-&gt; button-el
                      .-firstChild
                      (set-styles! {:width &quot;35px&quot;
                                    :filter (str &quot;invert(59%) sepia(92%) saturate(611%) &quot;
                                                 &quot;hue-rotate(343deg) brightness(97%) contrast(99%)&quot;)}))
                  button-el)))
         log))
  ;; =&gt; #&apos;cljcastr.player/playback-buttons

  (doseq [el playback-buttons]
    (.appendChild playback-controls-container el))
  ;; =&gt; nil

  (def play-button (js/document.querySelector &quot;#button-play&quot;))
  ;; =&gt; #&apos;cljcastr.player/play-button

  (def pause-button (js/document.querySelector &quot;#button-pause&quot;))
  ;; =&gt; #&apos;cljcastr.player/play-button

  (def forward-button (js/document.querySelector &quot;#button-forward&quot;))
  ;; =&gt; #&apos;cljcastr.player/forward-button

  (def backward-button (js/document.querySelector &quot;#button-backward&quot;))
  ;; =&gt; #&apos;cljcastr.player/backward-button

  (.addEventListener play-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (.play (js/document.querySelector &quot;audio.cljcastr&quot;))))
  ;; =&gt; nil

  (.addEventListener pause-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (.pause (js/document.querySelector &quot;audio.cljcastr&quot;))))
  ;; =&gt; nil

  (.addEventListener forward-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (skip-forward! audio seek-dur-sec)))
  ;; =&gt; nil

  (.addEventListener backward-button &quot;click&quot;
                     (fn [ev]
                       (log ev)
                       (skip-backward! audio seek-dur-sec)))
  ;; =&gt; nil

  )
</code></pre><p>Now our buttons look like they did before! 🎉</p><p>However, recreating these buttons is getting a little tedious. Let&apos;s do some cleaning up.</p><div class="markdown-heading"><h2 id="sweeping-up-the-shop">Sweeping up the shop</h2><a href="#sweeping-up-the-shop" class="anchor" aria-label="Permalink: Sweeping up the shop"><img src="assets/link.svg" /></a></div><p>First of all, our <code>log</code> function is a little limited. It would be nice if we could include a log message in addition to whatever data we&apos;re logging. In other words, we&apos;d like to do this:</p><pre><code class="language-clojure">(comment

  ;; ...

  (log &quot;Something happened!&quot; {:foo 1, :bar 2})
  ;; =&gt; &quot;Something happened!&quot;

  )
</code></pre><p>But if we look at the console now, we only see the message logged and not the data:</p><pre><code class="language-text">  Something happened!                                                 nrepl.cljs:10
</code></pre><p>Luckily, the fix is pretty straightforward:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

(defn log [&amp; args]
  (apply js/console.log (map clj-&gt;js args))
  (last args))

;; (defn render ...)
;; ...

(comment

  ;; ...

  (log &quot;Something happened!&quot; {:foo 1, :bar 2})
  ;; =&gt; {:foo 1, :bar 2}

  )
</code></pre><p>The value returned is what we wanted, and the console looks good as well:</p><pre><code class="language-text">  Something happened!  ‣ {foo: 1, bar: 2}                             nrepl.cljs:10
</code></pre><p>Next annoyance: all those <code>js/document.querySelector</code> calls. Extraction!</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn render ...)

(defn get-el
  &quot;Returns the element matching the specified CSS selector. If `selector` is
   already an element, just returns the element.&quot;
  [selector]
  (if (instance? js/Element selector)
    selector
    (js/document.querySelector selector)))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (get-el &quot;#button-play&quot;)
  ;; =&gt; #object[HTMLButtonElement [object HTMLButtonElement]]

  )
</code></pre><p>Might as well have a function to get a list of elements too:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-el ...)

(defn get-els
  &quot;Returns a sequence containing the elements matching the specified CSS
   selector.&quot;
  [selector]
  (-&gt;&gt; (js/document.querySelectorAll selector)
       seq))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (get-els &quot;#playback-controls &gt; button&quot;)
  ;; =&gt; (#object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]])

  )
</code></pre><p>How about one to return the children of an element?</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-els ...)

(defn get-children [el]
  (-&gt; (get-el el)
      .-childNodes
      seq))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (-&gt; (get-children &quot;#playback-controls&quot;)
      log)
  ;; =&gt; (#object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]])

  )
</code></pre><p>We added another nicety there: by using <code>get-el</code>, our function can take either an element or a CSS selector as its argument. Let&apos;s continue to use this pattern as we add a function for adding a child to an element:</p><p>But if we look at the console, we see something extremely odd:</p><pre><code class="language-text">                                                                      nrepl.cljs:10
  ‣ he {value: button#backward, Ee: ArrayIterator, Ag: null, F: 8388672, M: 0}
</code></pre><p>The answers, my friend, are blowing in the wind of <code>get-children</code>:</p><pre><code class="language-clojure">(defn get-children [el]
  (-&gt; (get-el el)
      .-childNodes
      seq))
</code></pre><p>We&apos;re taking the <code>childNodes</code> attribute of our <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement">HTMLDivElement</a>, which is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList">NodeList</a> object:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (get-el &quot;#playback-controls&quot;)
      .-childNodes
      log)
  ;; =&gt; #object[NodeList [object NodeList]]

  )
</code></pre><p>This looks great in the console:</p><pre><code class="language-text">                                                                      nrepl.cljs:10
    NodeList(5) [button#button-backward.cljcastr.playback-button,
    button#button-play.cljcastr.playback-button,
  ‣ button#button-pause.cljcastr.playback-button,
    button#button-forward.cljcastr.playback-button,
    button#button-speed.cljcastr.playback-button]
</code></pre><p>But we can&apos;t use it in Clojure all that well:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (get-el &quot;#playback-controls&quot;)
      .-childNodes
      count)
  ;; =&gt; &quot;#error {:message \&quot;No protocol method ICounted.-count defined for type object: [object NodeList]\&quot;, ...}&quot;

  )
</code></pre><p>That&apos;s why <code>get-children</code> adds the call to <a href="https://clojuredocs.org/clojure.core/seq">seq</a> at the end. That lets normal Clojure code deal with the list of children, but as we&apos;ve seen, it doesn&apos;t look good in the console when logged.</p><p>Let&apos;s see what we can do about this:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; (get-children &quot;#playback-controls&quot;)
      vec
      log)
  ;; =&gt; [#object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]]

  )
</code></pre><p>Now the console is looking quite reasonable!</p><pre><code class="language-text">                                                                      nrepl.cljs:10
    (5) [button#button-backward.cljcastr.playback-button,
    button#button-play.cljcastr.playback-button,
  ‣ button#button-pause.cljcastr.playback-button,
    button#button-forward.cljcastr.playback-button,
    button#button-speed.cljcastr.playback-button]
</code></pre><p>Let&apos;s see if we can apply what we&apos;ve learned here to our <code>log</code> function:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

(defn log [&amp; args]
  (let [seq-&gt;vec #(if (seq? %) (vec %) %)]
    (apply js/console.log (map (comp clj-&gt;js seq-&gt;vec) args)))
  (last args))

  ;; (defn render ...)
  ;; ...

(comment

  ;; ...

  (-&gt; (get-children &quot;#playback-controls&quot;)
      log)
  ;; =&gt; (#object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]])

  )
</code></pre><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-children ...)

(defn add-child! [parent-el el]
  (let [parent-el (get-el parent-el)]
    (-&gt; parent-el
        (.appendChild el))
    parent-el))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (add-child! &quot;#playback-controls&quot;
                   (create-el {:tag &quot;span&quot;
                               :text &quot;Some nonsense&quot;}))
       (log &quot;I got a new child&quot;))
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p>Wanna clear all the children of an element?</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-child! ...)

(defn clear-children! [el]
  (let [el (get-el el)]
    (.replaceChildren el)
    el))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (clear-children! &quot;#playback-controls&quot;)
       (log &quot;Empty nest&quot;))
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p>Set the children of an element?</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn clear-children! ...)

(defn set-children! [parent-el els]
  (let [parent-el (get-el parent-el)]
    (clear-children! parent-el)
    (doseq [el els]
      (add-child! parent-el el))
    parent-el))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (-&gt;&gt; (set-children! &quot;#playback-controls&quot; playback-buttons)
       log)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p>Final annoyance: all the repetition in the click handlers. Let&apos;s extract a function for that as well:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn create-el ...)

(defn add-event-listener! [el event-type f]
  (let [el (get-el el)]
    (.addEventListener el event-type
                       (fn [ev]
                         (log (str &quot;Handling &quot; event-type &quot; on&quot;)
                              el ev)
                         (if f
                           (f ev)
                           (log &quot;No event handler function defined&quot;))))
    (log &quot;Added listener for&quot; event-type &quot;events to&quot; el)
    el))

;; (defn create-button ...)
;; ...

(comment

  ;; ...

  (add-event-listener! &quot;#button-speed&quot; &quot;click&quot;
                       #(log &quot;Should probably do something with this event, eh?&quot; %))
  ;; =&gt; #object[HTMLButtonElement [object HTMLButtonElement]]

  )
</code></pre><p>And if we now click the playback speed button, the console rewards us with some rich logging:</p><p><img alt="Console log of event handler" src="assets/2026-11-01-scittlecastr-event.png" title="Now we&apos;re clicking with gas!" class="border" /></p><p>With all these awesome functions, we can finally recreate our buttons much more concisely:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-event-listener! ...)

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str &quot;button-&quot; (name button-name))]
     (-&gt; (create-el {:tag &quot;button&quot;
                     :attrs {:id button-id
                             :class (render &quot;cljcastr {{button-class}}&quot; ctx)
                             :aria-label (render label ctx)}})
         (set-styles! {:padding 0
                       :margin 0
                       :border 0
                       :background &quot;transparent&quot;
                       :cursor &quot;pointer&quot;})
         (add-event-listener! &quot;click&quot; click-handler)
         (add-child! (create-el {:tag &quot;img&quot;
                                 :attrs {:id (str button-id &quot;-icon&quot;)
                                         :class (render &quot;cljcastr {{img-class}}&quot; ctx)
                                         :src src
                                         :draggable false}}))))))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (def playback-controls
    {:play {:src &quot;https://www.svgrepo.com/show/436852/play-circle-fill.svg&quot;
            :label &quot;Play&quot;
            :click-handler #(.play (get-el &quot;audio.cljcastr&quot;))}
     :pause {:src &quot;https://www.svgrepo.com/show/436829/pause-circle-fill.svg&quot;
             :label &quot;Pause&quot;
             :click-handler #(.pause (get-el &quot;audio.cljcastr&quot;))}
     :forward {:src &quot;https://www.svgrepo.com/show/495321/forward-15-seconds.svg&quot;
               :label &quot;Forward {{seek-dur-sec}} seconds&quot;
               :click-handler #(skip-forward! (get-el &quot;audio.cljcastr&quot;) seek-dur-sec)}
     :backward {:src &quot;https://www.svgrepo.com/show/495036/backward-15-seconds.svg&quot;
                :label &quot;Back {{seek-dur-sec}} seconds&quot;
                :click-handler #(skip-backward! (get-el &quot;audio.cljcastr&quot;) seek-dur-sec)}
     :speed {:src &quot;https://www.svgrepo.com/show/151785/speed-meter.svg&quot;
             :label &quot;Playback speed&quot;}})
  ;; =&gt; #&apos;cljcastr.player/playback-controls

  (def playback-buttons
    (-&gt;&gt; [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :class &quot;playback-control&quot;})]
                  (-&gt; (get-children button-el)
                      first
                      (set-styles! {:width &quot;35px&quot;
                                    :filter &quot;invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%)&quot;}))
                  button-el)))
         log))
  ;; =&gt; #&apos;cljcastr.player/playback-buttons

  (set-children! &quot;#playback-controls&quot; playback-buttons)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p>OK, so we&apos;ve fixed the non-obvious (to those of us not using screen readers) problem with the player. Scratching our heads, we try to recall what the obvious problem was. 🤔</p><p>Oh yeah! Two sets of controls, right. Let&apos;s fix.</p><div class="markdown-heading"><h2 id="sweeping-audio-under-the-carpet">Sweeping audio under the carpet</h2><a href="#sweeping-audio-under-the-carpet" class="anchor" aria-label="Permalink: Sweeping audio under the carpet"><img src="assets/link.svg" /></a></div><p>Making our audio element disappear isn&apos;t that hard. Let&apos;s use this as an excuse to create a few more helper functions and spread the <code>get-el</code> pattern a little wider as well:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-els ...)

(defn get-attr
  &quot;Returns the value of the specified attribute.&quot;
  [el attr]
  (let [el (get-el el)]
    (.getAttribute el (name attr))))

(defn set-attr!
  &quot;Sets the value of the specified attribute.&quot;
  [el attr v]
  (let [el (get-el el)]
    (.setAttribute el (name attr) v)
    el))

(defn set-attrs! [el attrs]
  (let [el (get-el el)]
    (doseq [[k v] attrs]
      (.setAttribute el (name k) v))
    el))

(defn get-id
  &quot;Returns the ID of an element.&quot;
  [el]
  (let [el (get-el el)]
    (.-id el)))

(defn set-id!
  &quot;Sets the ID of an element.&quot;
  [el id]
  (let [el (get-el el)]
    (when-not (empty? id)
      (set-attr! el :id id))
    el))

(defn get-name
  &quot;Returns the tag name of an element.&quot;
  [el]
  (let [el (get-el el)]
    (.-localName el)))

(defn get-text
  &quot;Returns the inner text of an element.&quot;
  [el]
  (let [el (get-el el)]
    (or (.-textContent el)
        (.-innerText el))))

(defn set-text! [el text]
  (let [el (get-el el)]
    (when-not (empty? text)
      (set! (.-textContent el) text))
    el))

(defn get-classes
  &quot;Returns the classes of the specified element as a list of class names.&quot;
  [el]
  (let [el (get-el el)]
    (-&gt;&gt; (str/split (.-classList el) #&quot;\s&quot;)
         (remove empty?))))

(defn set-classes!
  &quot;Sets the classes of the specified element. Classes may either be a list or a
   string.

   Example:

     ;; These two are equivalent
     (set-classes el [\&quot;foo\&quot; \&quot;bar\&quot;])
     (set-classes el \&quot;foo bar\&quot;)&quot;
  [el classes]
  (let [el (get-el el)]
    (when-not (empty? classes)
      (set! (.-classList el) (if (string? classes)
                               classes
                               (str/join &quot; &quot; classes))))
    el))

;; (defn get-children ...)
;; ...
;; (defn set-children! ...)

(defn get-styles
  &quot;Returns the inline styles of an element as a map of style name to value.&quot;
  [el]
  (let [styles (-&gt; (get-el el)
                   (.getAttribute &quot;style&quot;)
                   (str/split #&quot;;\s+&quot;))]
    (-&gt;&gt; styles
         (remove empty?)
         (map #(let [[k v] (str/split % #&quot;:\s+&quot;)]
                 [(-&gt; (str/trim k) keyword) (str/trim v)]))
         (into {}))))

(defn set-styles!
  &quot;Sets the styles of an element from a map of style name to value.&quot;
  [el styles]
  (let [el (get-el el)]
    (when-not (empty? styles)
      (set! (.-style el) (-&gt;&gt; styles
                              (map (fn [[k v]]
                                     (str (name k) &quot;: &quot; v)))
                              (str/join &quot;; &quot;))))
    el))

(defn add-styles!
  &quot;Given a map of style name to value, adds the styles to the element.&quot;
  [el styles]
  (-&gt; el
      (set-styles! (merge (get-styles el) styles))))

(defn add-style!
  &quot;Adds a style to an element&quot;
  [el style-name style-value]
  (-&gt; el
      (add-styles! {style-name style-value})))

;; (defn create-el)
;; ...
</code></pre><p>Now that we have all of this awesomeness, we can streamline <code>create-el</code> by accepting a few more keys:</p><ul><li><code>:id &quot;foo&quot;</code> instead of <code>:attrs {:id &quot;foo&quot;}</code></li><li><code>:classes [&quot;foo&quot; &quot;bar&quot;]</code> instead of <code>:attrs {:class &quot;foo bar&quot;}</code></li><li><code>:text</code> to set the text content of the element</li></ul><p>We also have to update <code>create-button</code> to take advantage of this.</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn create-el [{:keys [tag id classes text attrs] :as args}]
  (-&gt; (js/document.createElement tag)
      (set-attrs! attrs)
      (set-id! id)
      (set-classes! classes)
      (set-text! text)))

;; (defn add-event-listener! ...)
;; ...

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str &quot;button-&quot; (name button-name))]
     (-&gt; (create-el {:tag &quot;button&quot;
                     :id button-id
                     :classes [&quot;cljcastr&quot;
                               (render &quot;{{button-class}}&quot; ctx)]
                     :attrs {:aria-label (render label ctx)}})
         (set-styles! {:padding 0
                       :margin 0
                       :border 0
                       :background &quot;transparent&quot;
                       :cursor &quot;pointer&quot;})
         (add-event-listener! &quot;click&quot; click-handler)
         (add-child! (create-el {:tag &quot;img&quot;
                                 :id (str button-id &quot;-icon&quot;)
                                 :classes [&quot;cljcastr&quot;
                                           (render &quot;{{img-class}}&quot; ctx)]
                                 :attrs {:src src
                                         :draggable false}}))))))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (add-style! audio :display &quot;none&quot;)
  ;; =&gt; #object[HTMLAudioElement [object HTMLAudioElement]]

  (def playback-buttons
    (-&gt;&gt; [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :button-class &quot;playback-button&quot;
                                                :img-class &quot;playback-icon&quot;})]
                  (-&gt; (get-children button-el)
                      first
                      (set-styles! {:width &quot;35px&quot;
                                    :filter (str &quot;invert(59%) sepia(92%) saturate(611%) &quot;
                                                 &quot;hue-rotate(343deg) brightness(97%) contrast(99%)&quot;)}))
                  button-el)))
         log))
  ;; =&gt; #&apos;cljcastr.player/playback-buttons

  (set-children! &quot;#playback-controls&quot; playback-buttons)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p><img alt="Player with just buttons" src="assets/2026-11-01-scittlecastr-nude.png" title="The buttons, the whole buttons, and nothing but the buttons" class="border" /></p><p>Testing our controls, we verify that they still work. However, we&apos;ve lost three important things:</p><ol start="1"><li>The progress bar, which gave us a visual indication of where we are and a way to move to an arbitrary point in the episode by clicking or dragging.</li><li>The display of the current position in the episode.</li><li>The display of the duration of the episode.</li></ol><p>Actually, on the third point, we like Overcast&apos;s choice to display the time remaining instead of the duration, so let&apos;s do that as well.</p><p>Having made these bold design decisions, let&apos;s get to implementing! We&apos;ll start with the easy stuff, displaying the time elapsed and remaining:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def elapsed-time (create-el {:tag &quot;span&quot;
                                :text (str (.-currentTime audio))
                                :classes [&quot;cljcastr&quot;]
                                :id &quot;elapsed-time&quot;}))
  ;; =&gt; #&apos;cljcastr.player/cur-time

  (def remaining-time (create-el {:tag &quot;span&quot;
                                  :text (str (- (.-duration audio)
                                                (.-currentTime audio)))
                                  :classes [&quot;cljcastr&quot;]
                                  :id &quot;remaining-time&quot;}))
  ;; =&gt; #&apos;cljcastr.player/remaining-time

  (doseq [el [elapsed-time remaining-time]]
    (add-child! &quot;#playback-controls&quot; el))
  ;; =&gt; nil

  )
</code></pre><p><img alt="Times displayed as fractional seconds" src="assets/2026-11-01-scittlecastr-times.png" title="Too much math, too ugly!" class="border" /></p><p>Well, this is something, at least. Something incredibly confusing and also ugly. 😭</p><p>Let&apos;s enumerate the problems:</p><ol start="1"><li>Times are displayed as fractional seconds, not the more familiar <code>h:mm:ss</code>.</li><li>The spans are side by side with no padding, so it&apos;s not possible to tell where elapsed time ends and remaining time begins.</li><li>The font size is too large compared to the buttons. And maybe black isn&apos;t the best choice of colour anyway.</li><li>We&apos;d like the times displayed above the buttons (and the progress bar, when we get around to adding it).</li></ol><p>Now that we know what&apos;s wrong, let&apos;s tackle things one at a time.</p><div class="markdown-heading"><h2 id="hours,-minutes,-and-seconds,-oh-my!">Hours, minutes, and seconds, oh my!</h2><a href="#hours,-minutes,-and-seconds,-oh-my!" class="anchor" aria-label="Permalink: Hours, minutes, and seconds, oh my!"><img src="assets/link.svg" /></a></div><p>How can we convert from seconds to <code>h:mm:ss</code>?</p><pre><code class="language-clojure">(comment

  ;; ...

  (set! (.-currentTime audio) 3645)
  ;; =&gt; 3645

  (let [secs (.-currentTime audio)
        h (-&gt; secs (/ 3600) int)
        mm (-&gt; secs (/ 60) (- (* h 60)) int)
        ss (-&gt; secs (mod 60) int)]
    (str (int h) &quot;:&quot; (int mm) &quot;:&quot; (int ss)))
  ;; =&gt; &quot;1:0:45&quot;

  )
</code></pre><p>OK, not a bad start. Let&apos;s zero-pad the minutes and seconds, though, because &quot;1:00:45&quot; looks way better than &quot;1:0:45&quot;. 😉</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [secs (.-currentTime audio)
        h (-&gt; secs (/ 3600) int)
        mm (-&gt; secs (/ 60) (- (* h 60)) int)
        ss (-&gt; secs (mod 60) int)
        zero-pad #(-&gt; % int str (str/replace #&quot;^(\d)$&quot; &quot;0$1&quot;))]
    (str (int h) &quot;:&quot; (zero-pad mm) &quot;:&quot; (zero-pad ss)))
  ;; =&gt; &quot;1:00:45&quot;

  (set! (.-currentTime audio) 46)
  ;; =&gt; 46

  (let [secs (.-currentTime audio)
        h (-&gt; secs (/ 3600) int)
        mm (-&gt; secs (/ 60) (- (* h 60)) int)
        ss (-&gt; secs (mod 60) int)
        zero-pad #(-&gt; % int str (str/replace #&quot;^(\d)$&quot; &quot;0$1&quot;))]
    (str (int h) &quot;:&quot; (zero-pad mm) &quot;:&quot; (zero-pad ss)))
  ;; =&gt; &quot;0:00:46&quot;

  )
</code></pre><p>Hrm, maybe one more tweak. It&apos;s conventional to omit the hour(s) portion of timestamps less than an hour:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [secs (.-currentTime audio)
        h (-&gt; secs (/ 3600) int)
        mm (-&gt; secs (/ 60) (- (* h 60)) int)
        ss (-&gt; secs (mod 60) int)
        zero-pad #(-&gt; % int str (str/replace #&quot;^(\d)$&quot; &quot;0$1&quot;))]
    (str (if (pos? (int h))
           (str (int h) &quot;:&quot;)
           &quot;&quot;)
         (zero-pad mm) &quot;:&quot; (zero-pad ss)))
  ;; =&gt; &quot;00:46&quot;

  )
</code></pre><p>Nice! Now let&apos;s turn this into a function:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn render ...)

(defn secs-&gt;ts
  &quot;Given a number of seconds, returns a timestamp of the form h:mm:ss.&quot;
  [secs]
  (let [h (-&gt; secs (/ 3600) int)
        mm (-&gt; secs (/ 60) (- (* h 60)) int)
        ss (-&gt; secs (mod 60) int)
        zero-pad #(-&gt; % int str (str/replace #&quot;^(\d)$&quot; &quot;0$1&quot;))]
    (str (if (pos? (int h))
           (str (int h) &quot;:&quot;)
           &quot;&quot;)
         (zero-pad mm) &quot;:&quot; (zero-pad ss))))

;; (defn get-el ...)
;; ...

(comment

  ;; ...

  ;; Elapsed time
  (secs-&gt;ts (.-currentTime audio))
  ;; =&gt; &quot;00:46&quot;

  ;; Remaining time
  (secs-&gt;ts (- (.-duration audio) (.-currentTime audio)))
  ;; =&gt; &quot;1:28:44&quot;

  (-&gt; elapsed-time
      (set-text! (secs-&gt;ts (.-currentTime audio)))
      log)
  ;; =&gt; #object[HTMLSpanElement [object HTMLSpanElement]]

  (-&gt; remaining-time
      (set-text! (str &quot;-&quot; (secs-&gt;ts (- (.-duration audio) (.-currentTime audio)))))
      log)
  ;; =&gt; #object[HTMLSpanElement [object HTMLSpanElement]]
  
  )
</code></pre><p>OK, we&apos;ve solved problem number 1. 🎉</p><p>Problems 2 and 3 are just styling, so the fixes are pretty straightforward:</p><pre><code class="language-clojure">(comment

  ;; ...

  (doseq [el [elapsed-time remaining-time]]
    (add-styles! el {:margin &quot;0 5px 0 5px&quot;
                     :font-size &quot;0.7rem&quot;
                     :color &quot;grey&quot;}))
  ;; =&gt; nil

  )
</code></pre><p><img alt="Timestamps displayed in smaller, grey text" src="assets/2026-11-01-scittlecastr-grey.png" title="Grey is the new black!" class="border" /></p><p>Whilst we&apos;re at it, let&apos;s fix another annoyance: with our current <code>create-el</code> function, we either have to call <code>add-styles!</code> (or <code>set-styles!</code>) afterwards, or do the stringifying of the styles ourselves:</p><pre><code class="language-clojure">(create-el {:tag &quot;div&quot;
            :attrs {:id &quot;whatever&quot;
                    :style &quot;margin: 0 5px 0 5px; font-size: 0.7rm; color: grey&quot;}})
</code></pre><p>We also have the same issue with classes and ID. 🙁</p><p>But instead of wallowing in misery, let&apos;s modify <code>create-el</code> to take a <code>:styles</code> key:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn create-el [{:keys [tag id classes styles text attrs] :as args}]
  (-&gt; (js/document.createElement tag)
      (set-attrs! attrs)
      (set-id! id)
      (set-classes! classes)
      (set-styles! styles)
      (set-text! text)))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (let [el (-&gt; (create-el {:tag &quot;span&quot;
                           :id &quot;elapsed-time&quot;
                           :classes [&quot;cljcastr&quot;]
                           :text (secs-&gt;ts 123)
                           :styles {:margin &quot;0 5px 0 5px&quot;
                                    :font-size &quot;0.7rem&quot;
                                    :color &quot;grey&quot;}})
               log)]
    (add-child! &quot;#playback-controls&quot; el))
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p>Now, let&apos;s address the last problem.</p><div class="markdown-heading"><h2 id="laying-out-the-law">Laying out the law</h2><a href="#laying-out-the-law" class="anchor" aria-label="Permalink: Laying out the law"><img src="assets/link.svg" /></a></div><p>It is now time to employ the most awesome technology known to humankind to figure out our layout: ASCII art!</p><pre><code class="language-text">+-----------------------------------+
|            Podcast title          |
+-----------------------------------+
|            Episode title          |
+-----------------------------------+
|            Release date           |
+-----------------------------------+
|            Episode art            |
+-----------------------------------+
|     Elapsed time | Remaining time |
+-----------------------------------+
|            Progress bar           |
+-----------------------------------+
| Backward | Play | Pause | Forward |
+-----------------------------------+
|           Playback speed          |
+-----------------------------------+
</code></pre><p>We&apos;ve been using the <strong>body</strong> element to hold our player, but we should probably deploy a <strong>div</strong> at this point so we can style things according to our liking. We can also group similar things together in <strong>div</strong>s, something like this:</p><pre><code class="language-text">+ episode-container ----------------------------+
|                                               |
| + episode-intro ----------------------------+ |
| |                Podcast title              | |
| +-------------------------------------------+ |
| |                Episode title              | |
| +-------------------------------------------+ |
| |                Release date               | |
| +-------------------------------------------+ |
|                                               |
+-----------------------------------------------+
|                  Episode art                  |
+-----------------------------------------------+
|                Audio (hidden)                 |
+-----------------------------------------------+
|                                               |
| + progress ---------------------------------+ |
| |       Elapsed time | Remaining time       | |
| +-------------------------------------------+ |
| |                Progress bar               | |
| +-------------------------------------------+ |
|                                               |
+-----------------------------------------------+
|                                               |
| + playback-controls ------------------------+ |
| | Backward | Play | Pause | Forward | Speed | |
| +-------------------------------------------+ |
|                                               |
+-----------------------------------------------+
</code></pre><p>Let&apos;s start by creating the new nested containers (we already have one for playback controls) and populating them with some hard-coded data:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def episode-container (create-el {:tag &quot;div&quot;
                                     :id &quot;episode-container&quot;
                                     :classes [&quot;cljcastr&quot;]
                                     :styles {:width &quot;100%&quot;
                                              :display &quot;flex&quot;
                                              :flex-direction &quot;column&quot;
                                              :align-items &quot;center&quot;}}))
  ;; =&gt; #&apos;cljcastr.player/episode-container

  (def episode-info
    (-&gt; (create-el {:tag &quot;div&quot;
                    :id &quot;episode-info&quot;
                    :classes [&quot;cljcastr&quot;]
                    :styles {:max-width &quot;420px&quot;
                             :text-align &quot;center&quot;}})
        (set-children! [(create-el {:tag &quot;h3&quot;
                                    :id &quot;podcast-title&quot;
                                    :classes [&quot;cljcastr&quot;]
                                    :text &quot;defn&quot;})
                        (create-el {:tag &quot;h2&quot;
                                    :id &quot;episode-title&quot;
                                    :classes [&quot;cljcastr&quot;]
                                    :text &quot;876b4c306172 Cora Sutton&quot;})
                        (create-el {:tag &quot;span&quot;
                                    :id &quot;episode-date&quot;
                                    :classes [&quot;cljcastr&quot;]
                                    :styles {:color &quot;grey&quot;}
                                    :text &quot;July 9, 2025&quot;})])
        log))
  ;; =&gt; #&apos;cljcastr.player/episode-info

  (def episode-art
    (-&gt; (create-el {:tag &quot;div&quot;
                    :id &quot;episode-art-container&quot;
                    :classes [&quot;cljcastr&quot;]})
        (add-child! (create-el {:tag &quot;img&quot;
                                :id &quot;episode-art&quot;
                                :classes [&quot;cljcastr&quot;]
                                :styles {:width &quot;400px&quot;
                                         :border-radius &quot;5%&quot;
                                         :padding &quot;10px&quot;}
                                :attrs {:src &quot;https://media.zencastr.com/image-files/5d9048546bacd9001de88f1c/a5b922ac-7294-4d58-9a33-4308f5d4f50b.png&quot;}}))
        log))
  ;; =&gt; #&apos;cljcastr.player/episode-art

  (def progress (create-el {:tag &quot;div&quot;
                            :id &quot;progress&quot;
                            :classes [&quot;cljcastr&quot;]
                            :styles {:width &quot;390px&quot;
                                     :margin &quot;1.5em auto 0 auto&quot;}}))
  ;; =&gt; #&apos;cljcastr.player/progress

  (def playback-controls-container (-&gt; (create-el {:tag &quot;div&quot;
                                                   :id &quot;playback-controls&quot;
                                                   :classes [&quot;cljcastr&quot;]})
                                       (set-children! playback-buttons)
                                       log))
  ;; =&gt; #&apos;cljcastr.player/playback-controls-container

  (def playback-speed (create-el {:tag &quot;div&quot;
                                  :id &quot;playback-speed&quot;
                                  :classes [&quot;cljcastr&quot;]}))
  ;; =&gt; #&apos;cljcastr.player/playback-speed

  (-&gt; episode-container
      (set-children! [episode-info
                      episode-art
                      (-&gt; audio
                          (set-styles! {:display &quot;none&quot;}))
                      progress
                      playback-controls-container
                      playback-speed])
      log)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  (set-children! &quot;body&quot; [episode-container])
  ;; =&gt; #object[HTMLBodyElement [object HTMLBodyElement]]

  )
</code></pre><p><img alt="Player with defn episode" src="assets/2026-11-01-scittlecastr-bagomaps.png" title="They&apos;re always after me bag&apos;o&apos;maps!" class="border" /></p><p>This is looking really good (relatively speaking), but there&apos;s one major component missing.</p><div class="markdown-heading"><h2 id="slipping-and-sliding">Slipping and sliding</h2><a href="#slipping-and-sliding" class="anchor" aria-label="Permalink: Slipping and sliding"><img src="assets/link.svg" /></a></div><p>We have no idea where in the episode we are! Let&apos;s see about getting that progress bar in place.</p><p>Luckily, HTML has got us covered! There just so happens to be a <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/progress">progress</a> element designed exactly for what we want to do!</p><pre><code class="language-clojure">(comment

  ;; ...

  (def progress-bar
    (create-el {:tag &quot;progress&quot;
                :id &quot;progress-bar&quot;
                :classes [&quot;cljcastr&quot;]
                :attrs {:min 0
                        :max (.-duration audio)
                        :value (.-currentTime audio)}
                :styles {:appearance &quot;none&quot;
                         :height &quot;8px&quot;
                         :width &quot;100%&quot;
                         :border &quot;0&quot;
                         :border-radius &quot;4px&quot;
                         :margin &quot;0&quot;
                         :overflow &quot;hidden&quot;
                         :background-color &quot;lightgray&quot;
                         :color &quot;#f7931e&quot;}}))
  ;; =&gt; #&apos;cljcastr.player/progress-bar

  )
</code></pre><p>Now that we have the progress bar, let&apos;s add it to our <code>#progress</code> div, along with the current and elapsed time spans we created before:</p><pre><code class="language-clojure">(comment

  ;; ...

  (-&gt; progress
      (set-children! [(-&gt; elapsed-time
                          (add-styles! {:float &quot;left&quot;}))
                      (-&gt; remaining-time
                          (add-styles! {:float &quot;right&quot;}))
                      progress-bar])
      log)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p><img alt="Progress bar added" src="assets/2026-11-01-scittlecastr-progress.png" title="Now that&apos;s progress!" class="border" /></p><p>Hurrah! I mean, it&apos;s a bit ugly, but at least it&apos;s there! 😅</p><p>Let&apos;s click the play button, then skip forward a few times. Now, we can try setting the value of the progress bar to the current time of the audio element:</p><pre><code class="language-clojure">(comment

  ;; ...

  (set! (.-value progress-bar) (.-currentTime audio))
  ;; =&gt; 370.277385

  )
</code></pre><p>We should see the progress bar move along a bit.</p><p>This is great and all, but it would be lovely to have a way to actually move forward and backward in the episode by clicking or dragging on the progress bar. You know, the way every audio player ever works?</p><p>Sadly, the progress bar itself isn&apos;t really designed for this. We could certainly hack it up with some &quot;click&quot; event listeners and a lot of arithmetic, but surely there must be a better way, right?</p><p>And indeed there is! HTML has an <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/range">input element of
type
range</a> that is designed for exactly this case! Let&apos;s try it out:</p><pre><code class="language-clojure">(comment

  ;; ...

  (def progress-slider
    (create-el {:tag &quot;input&quot;
                :id &quot;progress-slider&quot;
                :classes [&quot;cljcastr&quot;]
                :attrs {:type &quot;range&quot;
                        :min 0
                        :max (.-duration audio)
                        :value (.-currentTime audio)
                        :step &quot;any&quot;
                        :aria-label &quot;Seek&quot;
                        :aria-valuetext (str (secs-&gt;ts (.-currentTime audio))
                                             &quot; of &quot;
                                             (secs-&gt;ts (.-duration audio)))
                        :aria-valuemax (.-duration audio)}
                :styles {:appearance &quot;none&quot;
                         :cursor &quot;pointer&quot;
                         :height &quot;28px&quot;
                         :width &quot;100%&quot;
                         :border &quot;0&quot;
                         :margin &quot;0&quot;
                         :touch-action &quot;manipulation&quot;}}))
  ;; =&gt; #&apos;cljcastr.player/progress-slider

  (-&gt; progress
      (set-children! [(-&gt; elapsed-time
                          (add-styles! {:float &quot;left&quot;}))
                      (-&gt; remaining-time
                          (add-styles! {:float &quot;right&quot;}))
                      progress-slider
                      progress-bar])
      log)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p>OK, a blue dot has appeared. Let&apos;s skip forward in the episode a bit more, then update the value of the slider to the current playback position. Oh yeah, might as well update the value of the progress bar as well, whilst we&apos;re at it:</p><pre><code class="language-clojure">(comment

  ;; ...

  (doseq [el [progress-slider progress-bar]]
    (set! (.-value el) (.-currentTime audio)))
  ;; =&gt; nil

  )
</code></pre><p>Now, how about setting the playback position in the episode when we click or drag the slider?</p><pre><code class="language-clojure">(comment

  ;; ...

  (add-event-listener! progress-slider &quot;input&quot;
                       #(-&gt;&gt; % .-target .-value (set! (.-currentTime audio))))
  ;; =&gt; #object[HTMLInputElement [object HTMLInputElement]]

  )
</code></pre><p>We now have a pretty good representation of playback position:</p><ul><li>A span showing the elapsed time</li><li>A span showing the remaining time</li><li>A slider letting us control the playback position</li><li>A progress bar giving us a visual indication of the playback position</li></ul><p>Let&apos;s see if we can keep all of these in sync. First, some code to update them all in one go:</p><pre><code class="language-clojure">(comment

  ;; ...

  (let [secs (.-currentTime audio)
        duration-secs (.-duration audio)]
    (set-text! elapsed-time (secs-&gt;ts secs))
    (set-text! remaining-time (str &quot;-&quot; (secs-&gt;ts (- duration-secs secs))))
    (.setAttribute progress-slider &quot;aria-valuetext&quot;
                   (str (secs-&gt;ts secs) &quot; of &quot; (secs-&gt;ts duration-secs)))
    (doseq [el [progress-slider progress-bar]]
      (set! (.-value el) (.-currentTime audio))))
  ;; =&gt; nil

  )
</code></pre><p>Looks like that works, so let&apos;s extract it into a function. And whilst we&apos;re at it, maybe we can extract functions for the attribute and value setting so we don&apos;t have to expose the raw DOM interactions. And for the sake of completeness, we can add getters as well:</p><pre><code class="language-clojure">(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-text! ...)

(defn get-value
  &quot;Returns the value attribute of the specified element.&quot;
  [el]
  (let [el (get-el el)]
    (.-value el)))

(defn set-value!
  &quot;Sets the value attribute of the specified element.&quot;
  [el v]
  (let [el (get-el el)]
    (set! (.-value el) v)))

;; (defn set-classes! ...)
;; ...
;; (defn skip-backward! ...)

(defn update-playback-position-indicators!
  &quot;Given a current playback time and duration (both in seconds) and a map of
   elements, updates the elements to reflect the current playback position. The
   element map should contain the following keys:
   `:elapsed-time` - text element (for example: label, span, etc.)
   `:remaining-time` - text element (for example: label, span, etc.)
   `:progress-slider` - input element of type range
   `:progress-bar` - progress element&quot;
  [current-secs duration-secs
   {:keys [elapsed-time remaining-time progress-slider progress-bar]}]
  (set-text! elapsed-time (secs-&gt;ts current-secs))
  (set-text! remaining-time (str &quot;-&quot; (secs-&gt;ts (- duration-secs current-secs))))
  (set-attr! progress-slider :aria-valuetext
             (str (secs-&gt;ts current-secs) &quot; of &quot; (secs-&gt;ts duration-secs)))
  (doseq [el [progress-slider progress-bar]]
    (set-value! el current-secs)))

;; ...

(comment

  ;; ...

  (update-playback-position-indicators! (.-currentTime audio) (.-duration audio)
                                        {:elapsed-time elapsed-time
                                         :remaining-time remaining-time
                                         :progress-slider progress-slider
                                         :progress-bar progress-bar})
  ;; =&gt; nil

  )
</code></pre><p>There&apos;s one final touch we should apply here before we move on. It&apos;s getting a bit silly to have to manually update these elements, right? How about we update them automatically as the episode plays? For this, we can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event">timeupdatechange</a> event of our <strong>audio</strong> element:</p><pre><code class="language-clojure">(comment

  ;; ...

  (add-event-listener! audio &quot;timeupdate&quot;
                       #(update-playback-position-indicators!
                         (.-currentTime audio) (.-duration audio)
                         {:elapsed-time elapsed-time
                          :remaining-time remaining-time
                          :progress-slider progress-slider
                          :progress-bar progress-bar}))
  ;; =&gt; #object[HTMLAudioElement [object HTMLAudioElement]]

  )
</code></pre><p>Now things are running smoothly, but there&apos;s another thing that&apos;s bothering us. The progress slider that we use to control the playback position is above the progress bar, which just looks weird, and also goes against the expectations of our hordes of users that there should be a handle on the progress bar itself that they can drag around. You know, like this:</p><p><img alt="Overcast web player" src="assets/2026-11-01-scittlecastr-overcast.png" title="That&apos;s a nice looking player!" class="border" /></p><div class="markdown-heading"><h2 id="getting-into-position">Getting into position</h2><a href="#getting-into-position" class="anchor" aria-label="Permalink: Getting into position"><img src="assets/link.svg" /></a></div><p>What we&apos;d really like is to set our slider down right on top of the progress bar. This will give us the seeking we seek (sorry) as well as a visual indication of the current playback position. In order to do this, we&apos;re going to have to learn a bit about <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/position">CSS
positioning</a>.</p><p>Basically, we&apos;ll need to create a new container to hold the progress bar and the slider, and set its <code>position</code> style to &quot;relative&quot;. Then, we can add our progress bar and slider as children of it, setting their position to &quot;absolute&quot; (relative to their parent container). Yes, I know, this is enough to make our heads explode, but I guess it makes sense once you achieve enlightenment or something?</p><p>We also need to set the z-indexes of the two elements. We set the progress bar to 0 to put it at the bottom of the stack, and the slider to 1 so it&apos;s on top. That means we need to make the background colour of the slider transparent so the progress bar can shine through in all its glory.</p><p>Finally, we position both elements 0 pixels from the left of the enclosing container, then the slider 0 pixels from the top and the progress bar 10 pixels from the top. Why 10 pixels? Well, because:</p><ul><li>The slider is 28 pixels high.</li><li>The progress bar is 8 pixels high.</li><li>We want to vertically centre the progress bar underneath the slider.</li><li>20 - 8 is 10.</li></ul><p>With that advanced mathematics out of the way, let&apos;s make it happen!</p><pre><code class="language-clojure">(comment

  ;; ...

  (def progress-container
    (create-el {:tag &quot;div&quot;
                :id &quot;progress-container&quot;
                :classes [&quot;cljcastr&quot;]
                :styles {:position &quot;relative&quot;
                         :height &quot;28px&quot;
                         :clear &quot;both&quot;}}))
  ;; =&gt; #&apos;cljcastr.player/progress-container

  (-&gt; progress-container
      (set-children! [(-&gt; progress-bar
                          (add-styles! {:position &quot;absolute&quot;
                                        :top &quot;10px&quot;
                                        :left &quot;0px&quot;
                                        :z-index 0}))
                      (-&gt; progress-slider
                          (add-styles! {:position &quot;absolute&quot;
                                        :top &quot;0px&quot;
                                        :left &quot;0px&quot;
                                        :z-index 1
                                        :background-color &quot;transparent&quot;}))])
      log)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  (-&gt; progress
      (add-styles! {:position &quot;relative&quot;})
      (set-children! [(-&gt; elapsed-time
                          (add-styles! {:float &quot;left&quot;}))
                      (-&gt; remaining-time
                          (add-styles! {:float &quot;right&quot;}))
                      progress-container])
      log)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p><img alt="Player with a nice progress bar and slider" src="assets/2026-11-01-scittlecastr-position.png" title="Perfection on a plate!" class="border" /></p><p>This is looking pretty good! There are a few more things we might want to do, but just as we&apos;re about to start doing some of those things, a bone-chilling thought occurs to us: what if we reload the page? We&apos;ve been building our player up in the REPL one s-expression at a time, but our HTML file still has a <strong>body</strong> that looks like this:</p><pre><code class="language-html">&lt;body&gt;
&lt;/body&gt;
</code></pre><p>Should a feline friend prance across the keyboard, stepping on the Ctrl and r keys simultaneously (or Apple-r, if you&apos;re one of those too-cool-for-school types), all will be lost!</p><p>Before giving in to despair, we realise that we have the awesome power of ClojureScript at our fingertips, and thus can make a permanent record of what we&apos;ve done so far. And that, my dear readers, we shall endeavour to do in the new post in this series, which shall be called <a href="2026-11-07-persistence.html">Scittlecastr: All You Need is
Persistence</a>.</p><p><em>The preview image for this post was based on the <a href="https://thenounproject.com/photo/arab-woman-listening-to-music-with-earphones-and-dancing-outdoors-5wEnZb/">Arab woman listening to music
with earphones and dancing
outdoors</a> photo by <a href="https://thenounproject.com/creator/javiindy/">Javier Sanchez
Mingorance</a> from his <a href="https://thenounproject.com/browse/photo-shoot/woman-in-overall-dress-4mdJv5/">Woman In
Overall
Dress</a> photoshoot. The photo is used under The Noun Project&apos;s <a href="https://thenounproject.com/pricing/#icons">Royalty-Free Commercial
License</a>, and was remixed by hand in the <a href="https://www.gimp.org/">GIMP</a>, which <a href="https://gitlab.gnome.org/GNOME/gimp/-/blob/04e7f69d779d99d32a7c0156ce296f83b84bd600/README?plain=1#L52">does not allow genAI
contributions</a>.</em></p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2026-10-25-func-prog-conf-2026.html</id>
    <link href="https://jmglov.net/blog/2026-10-25-func-prog-conf-2026.html"/>
    <title>Func Prog Conf 2026</title>
    <updated>2026-10-25T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="Func Prog Conf 2026 logo projected onto an empty stage" src="assets/2026-10-25-func-prog-conf-2026-preview.jpg" title="It&apos;s about to go down" /></p><p><s>Last Wednesday</s> The Wednesday before last (fine blogging takes time to cook, you know), I attended <a href="https://funcprogconf.com/">Func Prog Conf</a> here in Stockholm. It was my first time at the conference, having missed the inaugural instantiation last year somehow. In fact, I would have missed this year as well had not Arne texted to ask if I was going. I played it cool, &quot;Maybe. Because I totally knew about this all along and I just wasn&apos;t sure if I could fit it into my awesome life with all the totally rad stuff that I&apos;m always doing.&quot; Having maintained my street cred, I ran to my <a href="https://www.qwant.com/">search engine of
choice</a> and tried to figure out what the hell he was talking about. 😅</p><p>It turns out that Func Prog Conf is a small one day event in Stockholm, just five talks and 180 people. It&apos;s organised by the great people over at <a href="https://adabeat.com/functional-programming/func-prog-sweden/">Func Prog
Sweden</a>, who run a meetup group with an interesting twist: every other meetup is online, so they&apos;re able to have speakers from all over Europe (and occasionally further afield). Their <a href="https://www.youtube.com/@FuncProgSweden">YouTube channel</a> is definitely worth a look. They are quite ecumenical, with talks from the hardcore type enthusiasts to the Lisp hippies with their laid-back approach to the serious engineers who are down with <a href="https://www.erlang.org/doc/system/design_principles.html">OTP</a> (<a href="https://youtu.be/idx3GSL2KWs">yeah you know
me</a>). I&apos;d definitely recommend checking out their <a href="https://www.meetup.com/func-prog-sweden/events/316293102/">next meetup</a>, whether in person if you happen to be in Stockholm, or <a href="https://youtube.com/live/ucX88M3_wFc">streaming live on
YouTube</a> if you happen to be in a compatible timezone or a shifted sleep schedule or high on life or whatever.</p><p>Anyway, back to the conference. It was held at a really cool venue in Slussen called <a href="https://sodrateatern.com/en/meetings-events/kagelbanan/">Kägelbanan</a>, high up on the cliff overlooking the Baltic Sea. It&apos;s part of the <a href="https://sodrateatern.com/">Södra
Teatern</a> complex, which has a really nice brunch on Sunday mornings. Definitely worth a visit in the summer, as much for the view as the food itself.</p><p>Sorry, I just realised that I went on a tangent again when I really really intended to talk about the conference itself. 🤦🏼</p><p>Oh wait, there&apos;s just one more thing. 😅</p><div class="markdown-heading"><h2 id="just-one-more-thing">Just one more thing</h2><a href="#just-one-more-thing" class="anchor" aria-label="Permalink: Just one more thing"><img src="assets/link.svg" /></a></div><p>The story of the conference actually starts the day before, at least for me. You see, our local Clojure group, sthlm.clj, had organised a <a href="https://www.meetup.com/sthlm-clj/events/315905210">Func Prog Conf
Prep</a> on the previous evening, which I only found out about because Arne mentioned that he would also be there (with customary humility, he didn&apos;t mention that he was giving a talk at the meetup, of course). The meetup was scheduled to start at 16:00, and I was just a tiny bit late due to a frenetic work schedule (every manager knows that the pleasure of taking a day off is accompanied by the pain of having to shift all of the work you would have done on that day to other days). When I walked in a few minutes after 16:00, there was already a talk underway. I slunk into a seat in the back row, eyes downcast as I radiated shame.</p><p>Safely ensconced in my seat, I finally looked up at the speaker, and got a lovely shock as I realised it was none other than Christoph Neumann, Clojure developer advocate and all around fine fellow. It turned out that Christoph was doing a run-through off the talk he would be presenting at the conference the next day, a fact to which I was not privy, due to me not having actually read the speaker lineup for the conference.</p><p>After he finished, I went over to say hi, and right around the same time, Arne rolled in. Hugs were dispensed, conversation flowed, and the food arrived. As we were chowing down and chatting, Arne said something about his talk, and when I asked for clarification, it turned out that he was giving a talk at this very meetup, a fact to which I was not privy, due to me not having actually read the speaker lineup for the meetup.</p><p>If one were feeling particularly generous, one could describe my approach to life as being in the moment; whereas a more ungenerous interpretation would go more along the lines of wtf is wrong with you Josh do you actually read bro?</p><p>I throw myself upon the mercy of the readership to adopt a view more akin to the generous one. 🙏</p><p>Anyway, as I said, much milling about was occurring, and I made another astute observation:</p><p><img alt="A man wearing a shirt that says &quot;we do it with rich comments&quot;" src="assets/2026-10-25-func-prog-conf-2026-rich.jpg" title="Unlike the rich man, the Rich comment shall surely pass through the gates of heaven with ease." /></p><p>Christoph was wearing a Calva t-shirt with a wicked awesome Clojure in-joke! Readers of the <a href="tags/clojure.html">Clojure posts in this
blog</a> are likely already familiar with the Rich comment, but for those who aren&apos;t:</p><blockquote><p>&quot;These comments are rich because they provide rich detail about the development process and because they were written by a person named Rich.&quot;</p><ul><li>Stuart Halloway, <a href="https://youtu.be/Qx0-pViyIDU?t=1229">Running With Scissors</a></li></ul></blockquote><p>There&apos;s a good explanation of Rich comments on the <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Between Two
Parens</a> blog, which I encourage y&apos;all to read.</p><p>19:00 arrived, and with it, the first of the evening&apos;s two talks: Markus Holmström&apos;s: <a href="https://youtu.be/DLFrMWeInLA">Cellsify – A take on Spreadsheets you didn&apos;t expect and now you
need it in your life</a>. This talk was as funny as it was mind expanding (spoiler alert: it&apos;s spreadsheets all the way down), and the second it was over, I DM&apos;d Markus on Clojurians Slack to invite him on <a href="http://zencastr.com/defn">defn</a>.</p><p>Next up was (a.k.a Arne Brasseur a.k.a. plexus), with <a href="https://youtu.be/sR0yrp2wDUU">Datastar – how to use it
with Clojure and some of the architectural
choices</a>. I had read some about Datastar, but had gotten it confused with some other frontend thingy that used Datalog that was maybe developed by <a href="https://romanliutikov.com/blog/">Roman Liutikov</a> but maybe not since I can&apos;t find it in my memory or in my search engine... send paramedics please!</p><p>But like, yeah, Datastar. Seems pretty cool. But don&apos;t take my word for it; watch the talk! 😉</p><p>Even before the applause died down, I was on my feet, sprinting out of the <a href="https://www.agical.se/">Agical</a> office and through <a href="https://en.wikipedia.org/wiki/Gamla_Stan">Gamla
Stan</a> to catch my train.</p><p>I shall spare you the details of the rest of my evening (don&apos;t worry, I caught my train) and finally get around to talking about the conference itself.</p><div class="markdown-heading"><h2 id="the-conference-itself">The conference itself</h2><a href="#the-conference-itself" class="anchor" aria-label="Permalink: The conference itself"><img src="assets/link.svg" /></a></div><p>Fast forward then to the next morning. The doors were set to open at 08:00, so I got myself to Slussen in good time, then walked up to the venue and arrived at about 07:50. Being a good Swede, I lurked just outside so I could be exactly punctual—not a minute early, not a minute late. Unfortunately, I rolled a 5 on my lurk check, and was detected by one of the Kägelbanan staff, who was out on the terrace in front of the venue having a crafty cig. Like, a real cigarette, with tobacco and all, not one of those new-fangled e-cigarettes that all the damn kids are puffing away on these days (get off my lawn, you damn kids!). That was surprising, but super cool, because you rarely see people going full James Dean in Stockholm anymore.</p><p>Even more surprisingly, she struck up a conversation with me. 🤯</p><p>You see, Stockholmers rarely so much as make eye contact with strangers, and <strong>never</strong> actually say so much as &quot;hej&quot; to them (unless out hiking, in which case they are downright friendly; or neighbours, in which case they might give a curt nod, a &quot;hej&quot; if they&apos;re feeling friendly, or even a &quot;hej hej&quot; if they&apos;re high on ecstasy or whatever). I guess this woman was primed for interacting with a bunch of foreigners (or maybe high on ecstasy, I dunno), but converse she did. I stumbled through the conversation in my barely functional Swedish, thinking I was getting away with it until she asked &quot;Pratar du engelska på jobbet eller?&quot; I hung my head and admitted that yes, I did in fact speak English at work, and yes, I was embarrassed that I hadn&apos;t learned Swedish in my 16 years here. Luckily, she wasn&apos;t the <a href="https://en.wikipedia.org/wiki/Sweden_Democrats">SD</a> type, so she let me off the hook with the standard &quot;Men svenskar alskar att prata engelska, så bli det tufft att lära sig svenska.&quot; I nodded, still appropriately ashamed of my laziness.</p><p>Anyway, we chatted away for a few minutes, then she told me it was actually OK to go in a couple minutes early (and by this, I mean a literal couple, since it was 07:58). I thanked her effusively, then headed inside to find my badge. I said hi to Magnus, one of the organisers of both the Func Prog Sweden group and the conference itself, and he told me that I wasn&apos;t in fact the first attendee to arrive—apparently someone else had been there since just after 07:00!</p><p>Grabbing my badge, I headed into the mingle area and armed myself with a coffee and a nice breakfast roll. I spotted Felix Alm setting up the <a href="https://multiply.co/">Multiply</a> booth, and walked over to chat. A few more people started arriving, and I had a really nice chat with a guy named Mauricio about Scala and Clojure and Lisp and programming philosophy and so on. He helped me distribute some <a href="http://zencastr.com/defn">defn</a> and <a href="https://pitch.com/">Pitch</a> stickers whilst we talked, then finally it was nearing 09:00, when the conference officially kicked off.</p><p><img alt="People mingling" src="assets/2026-10-25-func-prog-conf-2026-mingle.jpg" title="Functional programmers being functionally social" /></p><p>I made a beeline for the auditorium so I could get the perfect seat (third row, right side, aisle), and luxuriated in the sounds of silence as I checked out the setup. After a minute or two, Magnus walked out on stage and gave his opening remarks one last look as people started to file into the auditorium and find their seats. I snapped a quick picture, then whipped out my trusty <a href="https://babashka.org/">Babashka</a>-branded notebook and settled back in my seat, ready to be entertained and educated by the <a href="https://funcprogconf.com/#speakers">stellar lineup of speakers</a> that had been assembled for the day.</p><p><img alt="A man stands on stage, studying his phone as he prepares his remarks" src="assets/2026-10-25-func-prog-conf-2026-ready.jpg" title="Magnus prepares to rock the mic right" /></p><p>Christoffer Ekeroth from <a href="https://functionalsoftware.se/">Functional Software</a> (a Swedish recruitment agency specialising in functional programming roles) appeared in the wings, surveying the crowd. When he felt the moment was right, he strode onto stage and with a gesture, invoked the spotlights. He and Magnus assumed b-boy stances (OK, maybe that was just in my mind) and a hush fell on the crowd. They kicked off the event by introducing themselves, giving a brief history of the conference, and introducing <a href="https://funcprogconf.com/#sponsors">the
sponsors</a>.</p><p><img alt="Two men on stage" src="assets/2026-10-25-func-prog-conf-2026-intro.jpg" title="It&apos;s on!" /></p><p>After brief remarks from each sponsor, it was time for the opening keynote: &quot;Transforming Software Evolution: Lessons from 10 Years of Clojure in Production&quot;, by Adam Tornhill.</p><div class="markdown-heading"><h2 id="transforming-software-evolution">Transforming Software Evolution</h2><a href="#transforming-software-evolution" class="anchor" aria-label="Permalink: Transforming Software Evolution"><img src="assets/link.svg" /></a></div><p><img alt="Adam Tornhill prepares to start his talk" src="assets/2026-10-25-func-prog-conf-2026-adam.jpg" title="Adam&apos;s talk as a crime scene" /></p><p>I learned two things in the first 30 seconds of Adam&apos;s talk:</p><ol start="1"><li>He is a Clojurist (which I learned from his title slide)</li><li>He is a Swede</li></ol><p>The reasons for the first one were twofold: I hadn&apos;t actually looked at the talk lineup before the conference (as mentioned above), and another super embarrassing reason that shall be revealed presently.</p><p>The reason for the second one was far simpler: I had never seen Adam speak or heard him interviewed on a podcast (the former is now solved, whilst the latter is pending).</p><p>So anyway, in that first 30 seconds, Adam introduced himself, then started walking us through his path to Clojure. Apparently he got started pretty early!</p><p><img alt="A toddler holding a copy of the &quot;Practical Common Lisp&quot; book" src="assets/2026-10-25-func-prog-conf-2026-early.jpg" title="Getting started early" /></p><p>It turned out that this precocious hacker wasn&apos;t Adam, but his son. Shortly after this picture was taken, his son started tearing pages out of the book, which Adam noticed were from the section on Common Lisp&apos;s type system. &quot;So he was way ahead of me,&quot; Adam noted, drawing a chuckle from the crowd and a few mock scowls from some of the hardcore Haskellites in the crowd. Ah, &apos;twas all in good fun, &apos;twasn&apos;t it? A friendly trolling amongst friends, nothing more. 😉</p><p><img alt="Adam presents a slide labelled &quot;My Road To Functional Programming&quot;" src="assets/2026-10-25-func-prog-conf-2026-road.jpg" title="Why&apos;s it always gotta be Paul Graham?" /></p><p>There were many parallels to my own introduction to programming, which started out early in life on a primitive but beloved machine on which we used primitive but beloved programming languages (assembly, C, and Pascal for Adam; Motorola 6502 assembly, C, and BASIC for me), then moving on to slightly less primitive but slightly less beloved languages like C++ and Java, before reading Paul Graham&apos;s &quot;Beating the Averages&quot; essay (which I won&apos;t link to here because Paul Graham is an odious person) and seeing the Light of LISP. This is where our paths diverged a little bit, as Adam went for Common Lisp, even writing a book entitled <a href="https://leanpub.com/lispweb/">Lisp
for the Web</a> (which you can access on the web for any price between <span class="formula">0 - </span>20—your choice!), whereas I went for the elegant weapon for a more civilised age that is Scheme.</p><p>I loved me some Scheme, but knew that I wasn&apos;t likely to be able to use it at work (even though one of my colleagues was writing a Lisp implementation in C++ as a hobby project at the time), so Lisp remained merely a source of personal pleasure for me. Until 2009, that is, when I encountered Stuart Halloway&apos;s &quot;Programming Clojure&quot;. Lisp on the JVM sounded like a thing I might be able to sneak in, especially given the fact that my company was in the midst of a massive migration from Perl (yay!) to Java (less yay, but still OK). But then I moved from Japan to Ireland, trading a Perl-but-soon-to-be-Java team for a team doing operations for a big C++ search engine with many lovely Bash and Perl scripts, so poor Clojure had to wait.</p><p>It was somewhere around 2012 that I first used Clojure at work, building an end-to-end testing system for our product. Judging from his timeline, it seems that Adam was getting into Erlang and C# around the same time. In late 2013, I took my first real Clojure job, building the backend of a rock&apos;n&apos;roll trivia game in Clojure on AWS. Sometime in the next year, I too picked up C#, writing the network stack for our game&apos;s new frontend, which was built on Unity. I actually used Clojure there too (unbeknownst to my colleagues), thanks to Tims Gardner and Ramsey Nasser&apos;s amazing <a href="https://arcadia-unity.github.io/">Arcadia</a>, which was a port of <a href="https://github.com/clojure/clojure-clr">ClojureCLR</a> to Unity. 🤯</p><p>Thanks to Acadia, I was able to sit in a REPL and use the powers of interactive programming to prototype a network stack, one evaluated S-expression at a time. Oh happy times! That is, until I had to take my pristine Clojure code and translate it into C#. 😢</p><p>Whilst I was messing around with Unity, Adam was writing a book: <a href="https://pragprog.com/titles/atcrime2/your-code-as-a-crime-scene-second-edition/">Your Code as a
Crime
Scene</a>. As a brief aside (surprise surprise) I just love the description of the book:</p><blockquote><p>Jack the Ripper and legacy codebases have more in common than you’d think. Inspired by forensic psychology methods, you can apply strategies to identify problems in your existing code, assess refactoring direction, and understand how your team influences the software architecture. With its unique blend of criminal psychology and code analysis, Your Code as a Crime Scene arms you with the techniques you need to take on any codebase, no matter what programming language you use.</p></blockquote><p>I have a copy of the book, but have only read the introduction. Which is why I didn&apos;t realise that Adam was a Clojurist. 😬</p><p>But back in 2015, I didn&apos;t have a copy of the book, because I only heard about it somewhere in the Long 2020. What I did have a copy of in 2015 was Joe Armstrong&apos;s <a href="https://pragprog.com/titles/jaerlang2/programming-erlang-2nd-edition/">Programming
Erlang</a>. Why I had this is somewhat unclear to me. My friend Ryan had dabbled in Erlang back in the winter of 2000-2001, and gushed about lightweight processes and live reloading and supervisors and stuff, but when I looked at Erlang back then, I had never seen an immutable, functional language before, so it looked like complete gibberish to me (this was before the infamous Programming Languages course I took in university that made me a first-class Lisp Hater).</p><p>But taking a page out of Adam&apos;s book (in a metaphorical fashion, don&apos;t worry), I can examine the dusty crime scene that was 2015 and uncover some clues:</p><ol start="1"><li>The games company I was working for was rapidly running out of money</li><li>One of the angel investors bought out the rest of the investors and laid off all of the engineering staff but me</li><li>That guy was a real d-bag</li><li>I had grown to hate my job</li><li>I wanted a new job</li><li>Recruiters could sense this</li><li>One of the companies the recruiters aimed me at was this Swedish fintech that had the world&apos;s largest Erlang system and employed all the Erlang developers in Stockholm and the surrounding environs</li><li>I figured I should learn Erlang if I was interviewing for a job as an Erlang developer</li><li>The way I learn a new programming language is to read the book first, then work through some of the more interesting exercises in the book, then write a somewhat non-trivial system using that language (these days, I write a Scheme implementation; back then, I guess I wrote some sort of webservice that did something something?)</li></ol><p>From this evidence, I can surmise that I bought the book because I wanted to learn Erlang. And I did get an offer from that fintech, but I decided instead to join a streaming TV company to do Scala webservices (I actually did know Scala, having worked with it professionally for about a year at the same company where I built that Clojure end-to-end testing thingy). Of course, when I started at that company, I was dropped into a team that did low-level video transcoding in C and Python. But then we got this potential deal with a big TV company to do video on demand, and to win the deal, we had to demonstrate that we could transcode and stream arbitrary titles from their catalogue, and we had a week to do it. So I reached for the most obvious tool: <a href="https://github.com/pixie-lang/pixie">Pixie</a>. 😅</p><p>You see, this was many years before Babashka would make it possible to write Clojure shell scripts that started up immediately, and many many years before <a href="https://github.com/babashka/ffi">babashka.ffi</a>, and I needed to call into <a href="https://ffmpeg.org/">libffmpeg</a> from my scripts (I actually ended up abandoning that and just shelling out to the <code>ffmpeg</code> command-line tool).</p><p>The team I was part of consisted of me, two hardcore Finnish consultants who worked remotely from Helsinki, and this Swedish guy who worked together with me in the Stockholm office. At that point, I had been working for the company for maybe three months, and I had learned a little bit about video streaming (I had worked with my Swedish colleague on a <a href="https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP">DASH</a> server in Golang) and maybe a little bit more about video transcoding, but I wouldn&apos;t really say I knew what I was doing.</p><p>Somehow, we made enough progress that we were very close by Wednesday morning. But not quite there. And the company we were trying to win the deal with was based in Qatar. And the Qatari working week runs from Sunday to Thursday. Which meant that we had until Thursday morning to have a working demo of our system. 😱</p><p>So my colleague and I loaded up on coffee and sat down at my desk and started what would turn out to be a nearly 15 hour pairing session. I would hack some Pixie, then he would take the keyboard to tweak our DASH server, then we&apos;d switch again for more Pixie, then we&apos;d get stuck and ping the Finns on our IRC channel (I think it was still IRC back then, but maybe we had Slack?), and they&apos;d give us some ffmpeg incantation that was waaaaay over my head and just grazing the top of my Swedish colleague&apos;s head, and then back to the DASH server, and so on and so forth.</p><p>Around midnight, we successfully ingested, transcoded, and served our first video asset (I seem to remember it being a Champions League match). By 1 AM, we were scratching our heads wondering why the second asset we tried didn&apos;t work. But by 2 AM, we had fixed that, and by 3 AM, we had ingested five assets in a row, chosen completely at random (by <code>shuffle</code>-ing a list of asset IDs, natch). By 4 AM, I was in bed, trying to convince my caffeine-addled brain to stop projecting ffmpeg commands on the inside of my eyelids. And by 10 AM, I was somehow back at my desk, giving our demo system one last poke before we sent it over to the client.</p><p>And it worked! And we won the deal, which wouldn&apos;t have been possible without Lisp. So naturally, when it was time to build the production version of the system, we chose to do it in... <a href="https://elixir-lang.org/">Elixir</a>. 😂</p><p>It turns out that my Swedish colleague had an irrational fear of Lisp, and an undying love of Ruby, and the things I loved most about Clojure were functional programming, immutable data structures, and interactive development, so we compromised on a language that had all of those things for me and looked a lot like Ruby for him.</p><p>It was the best decision we ever made. Elixir was absolutely perfect for the task. We had a set of processes that scanned the catalogue for new assets, then fired events to another set of processes that downloaded the assets, then another set that transcoded downloaded assets, and of course a DASH server. We built the thing interactively in Emacs with the amazing <a href="https://github.com/tonini/alchemist.el">Alchemist.el</a>, and after the first week of development to get a skeletal cluster up, we didn&apos;t restart the system more than once or twice in the three months it took to finish the thing.</p><p>Try that with C++, I dare you. 😉</p><p>But anyway, back to 2026, and this functional programming conference that I&apos;m allegedly writing about (though there is a reason I took the Elixir detour, I promise). 😅</p><p>Like I said, there are a lot of parallels in Adam&apos;s and my roads to Clojure, but there&apos;s a decisive split circa 2025, when Adam Go(es) agentic and Rusty, and I very much don&apos;t. As I mentioned, I had done some Go at the video streaming company, with very mixed results. On the one hand, writing a service that listened to UDP multicast from a satellite downlink station and served it up on a TCP socket was like 50 lines of code. 🏆 On the other hand, writing a DASH server that read some JSON and then generated an MPD manifest was like a hundred million lines of code. 😭</p><p>And Rust? Well, if I was still doing much systems programming, it seems like a reasonable choice, and there&apos;s some really interesting stuff in the language, but my few forays into the community surrounding the language have left me with an incredibly bad taste in my mouth.</p><p>And agents? Well, any Clojurians reading this probably know how I feel about LLMs (a scourge upon humanity, etc). But more on this anon.</p><p>What Adam is doing in this talk is explaining why Clojure was a great choice for building <a href="https://codescene.com/">CodeScene</a>, the system he built for analysing the health of big codebases. And one of the key characteristics of Clojure is that it&apos;s a functional programming language. And a functional programming language is...</p><p><img alt="Adam presents a slide labelled &quot;What&apos;s Functional Programming&quot;" src="assets/2026-10-25-func-prog-conf-2026-what.jpg" title="What indeed?" /></p><p>Well, what exactly? As Fogus and chouser quip on this slide, it&apos;s not an easy question to answer:</p><blockquote><p>&quot;If you ask 100 programmers for their definition, you&apos;ll likely receive 100 different answers.&quot;</p></blockquote><p>But Adam actually answers the question quite succinctly on his previous slide:</p><p><img alt="A slide labelled &quot;Functional programming benchmark&quot;" src="assets/2026-10-25-func-prog-conf-2026-fun.jpg" title="Fun indeed?" class="border" /></p><p>Less code, more features, more <code>fun</code>... in Erlang, that is. In Clojure, it&apos;s more <code>fn</code>, proving once again its superior expressiveness. 😉</p><p>Interestingly enough, Adam is trained as a psychologist. So of course he had to give us an IQ test, showing us a set of patterns with one missing, and asking the audience to shout out the number corresponding to the missing pattern.</p><p>It started out with a reasonably straightforward one:</p><p><img alt="A slide labelled &quot;Let&apos;s do an IQ Test&quot;" src="assets/2026-10-25-func-prog-conf-2026-iq1.jpg" title="Is spatial reasoning really intelligence tho?" class="border" /></p><p>Got it? Many people in the audience did too, yelling out &quot;8&quot; with gusto.</p><p>But then, the friendly IQ test turned into this:</p><p><img alt="A slide labelled &quot;...and a slightly harder test&quot;" src="assets/2026-10-25-func-prog-conf-2026-iq2.jpg" title="omg what even is this?" class="border" /></p><p><img alt="Adam presents a slide labelled &quot;...and a slightly harder test&quot;" src="assets/2026-10-25-func-prog-conf-2026-harder.jpg" title="Don&apos;t forget to show your work" /></p><p>If you struggled with this one, you are far from alone. Only one brave voice in the audience called out the answer (which is 5).</p><p>Having humbled us with the IQ test, Adam made a recommendation: &quot;Do not turn your code into an IQ test.&quot; Sage advice indeed!</p><p>He then explained the goal of Code Health, the central concept behind the CodeScene platform he had developed in Clojure: to bring visibility to code and code quality:</p><p><img alt="Adam presents a slide labelled &quot;Code Health: bring visibility to code and code quality&quot;" src="assets/2026-10-25-func-prog-conf-2026-health.jpg" title="Recommendation: add a broccoli module" /></p><p>At a high level, what CodeScene does is:</p><ol start="1"><li>Parse the source</li><li>Identify code smells<ul><li>Module / class level smells: e.g. low cohesion, God Classes</li><li>Function level smells: e.g. copy-pasted logic, God Functions, primitive obsession</li><li>Implementation smells: e.g. deep nested logic, complex conditionals</li></ul></li><li>Score, aggregate, and categorise:<ul><li>💚 Healthy code with low risk defect</li><li>⚠️ Increased maintenance efforts</li><li>🛑 Unhealthy code with significant issues and defect risks</li></ul></li></ol><p>This allows CodeScene to build really cool visualisations to identify areas of the code where technical debt is lurking. Of course, when you have a massive codebase like the Linux kernel, with 21.4 million lines of code, contributed by over 15,000 authors...</p><p><img alt="Adam presents a slide labelled &quot;The Need For Concurrency: Analysing massive codebases&quot;" src="assets/2026-10-25-func-prog-conf-2026-massive.jpg" title="Concurrency made easy^W possible" /></p><p>...you can&apos;t exactly just</p><pre><code class="language-clojure">(map calculate-code-health-of files)
</code></pre><p>Of course, with Clojure, you can just add a character to turn the serial into the parallel:</p><pre><code class="language-clojure">(pmap calculate-code-health-of files)
</code></pre><p>According to Adam, &quot;That single character gave me a 10x speedup. It was the most efficient character I&apos;ve ever written!&quot;</p><p>But other than the magic of the letter <code>p</code>, what does Adam look for in a programming language?</p><p><img alt="Adam presents a slide labelled &quot;What do I look for in a programming language?&quot;" src="assets/2026-10-25-func-prog-conf-2026-lang.jpg" title="Fun: yet another thing agents destroy" /></p><p>When he first chose Clojure for CodeScene back in 2015, it was:</p><ul><li>✅ <strong>Productivity:</strong> fast to change the code</li><li>✅ <strong>Interactive:</strong> easy to iterate</li><li>✅ <strong>Fun:</strong> &quot;I&apos;ll spend a lot of time with this code...&quot;</li></ul><p>And in 2026, with his agents:</p><ul><li>❌ <strong>Productivity:</strong> fast to change the code</li><li>✅ <strong>Interactive:</strong> <s>easy</s> fast to iterate</li><li>❌ <strong>Fun:</strong> &quot;I&apos;ll spend a lot of time with this code...&quot;</li><li>✅ <strong>Validation:</strong> easy to inspect and review</li><li>✅ <strong>AI-optimised:</strong> program close to the domain</li></ul><p>Clojure still wins.</p><p>Anytime I write the word &quot;AI&quot;, I of course need to give the 🤮 disclaimer.</p><p>Here&apos;s a fun code health problem for us:</p><p><img alt="Adam presents a slide labelled &quot;Meet a Code Health problem: Deep Nested Complexity&quot;" src="assets/2026-10-25-func-prog-conf-2026-hadouken.jpg" title="Can Ken code?" /></p><p>Looks like Ryu needs to learn recursion. 😂</p><p>One way to think about programming is that you have two models:</p><ol start="1"><li>A <a href="https://en.wikibooks.org/wiki/Cognitive_Psychology_and_Cognitive_Neuroscience/Situation_Models_and_Inferencing">situation
   model</a>, which is the programmer&apos;s mental representation of the problem domain</li><li>The corresponding <strong>system model</strong>, which is how the programmer models the domain in software</li></ol><p><img alt="Adam presents a slide showing a diagram of situation model and system model" src="assets/2026-10-25-func-prog-conf-2026-model.jpg" title="Mind the gap" /></p><p>The situation model is used to express knowledge, which is encoded in the system model, then data is input and the outcome is observed by the programmer, allowing them to update their situation model (this is where learning occurs). The bigger the gap between these two, the more cognitive load is placed on the programmer, thus increasing the chance of defects in the system.</p><p>The programmer&apos;s goal then becomes to close the gap between the two models, and one way Adam proposes to do this is to build domain-specific languages, such as:</p><pre><code class="language-clojure">(defn costs-by-file
  &quot;Given a sequence of task durations (e.g from Jira),
   what are the development costs per file?
   Development costs are expressed in work days, wd.&quot;
  [duration-by-task]
  (-&gt;&gt; duration-by-task
       (map (partial assign-to-files file-name-&gt;ticket))
       (filter passes-minimum-thresholds?)
       (reduce by-file-name)
</code></pre><p>And you can take this a step further with an embedded DSL, using the great and terrible power of macros!</p><p><img alt="Gandalf saying &quot;I would use this macro from a desire to do good...&quot;" src="assets/2026-10-25-func-prog-conf-2026-gandalf.jpg" title="...but through me, it would wield a power too great and terrible to imagine." /></p><p>You could define a macro along these lines:</p><pre><code class="language-clojure">(defmacro enable-code-health-suppressions-for
  [&amp; suppressions]
  (-&gt;&gt; suppressions
       (map (fn [s]
              `(defmethod apply-directive-to ~s [parsed-code#]
                 (apply-shared-logic parsed-code#)
                 (remove-warning ~s parsed-code#))))))
</code></pre><p>And then write code like this:</p><pre><code class="language-clojure">(enable-code-health-suppressions-for
  :complex-method
  :bumpy-road
  :deep-nested-complexity)
</code></pre><p>which would expand at compile time to this:</p><pre><code class="language-clojure">(defmethod apply-directive-to :complex-method [parsed-code]
  (apply-shared-logic parsed-code)
  (remove-warning :complex-method parsed-code))

(defmethod apply-directive-to :bumpy-road [parsed-code]
  (apply-shared-logic parsed-code)
  (remove-warning :bumpy-road parsed-code))

(defmethod apply-directive-to :deep-nested-complexity [parsed-code]
  (apply-shared-logic parsed-code)
  (remove-warning :deep-nested-complexity parsed-code))
</code></pre><p>So it looks like macros can be used for good after all... for a time. But continuing down this road leads to Common Lisp, and Common Lisp leads to:</p><p><img alt="Cover of the book &quot;Let Over Lambda&quot;" src="assets/2026-10-25-func-prog-conf-2026-lol.jpg" title="Friends don&apos;t let friends use macros" /></p><p>Adam&apos;s claim is that judicious use of macros can move the programmer from instructing a machine (which is slow) to expressing a domain (which is powerful).</p><p><img alt="Adam presents a slide showing a diagram of moving from instructing a machine to expressing a domain" src="assets/2026-10-25-func-prog-conf-2026-express.jpg" title="Expressiveness wins again!" /></p><p>And all jokes aside, Clojurists do use macros, but as a tool of last resort. The Clojure philosophy is something like this:</p><ol start="1"><li>Use data whenever possible</li><li>When you can&apos;t use data, use a function</li><li>When you can&apos;t use a function, say a little prayer and use a macro</li></ol><p>Whereas the Common Lisp philosophy is more like this:</p><ol start="1"><li>Use macros everywhere, especially reader macros, so you can write code that doesn&apos;t even look like Lisp anymore and is so powerful that no mere mortal can comprehend it</li></ol><p>Having made a series of compelling points about how to keep complexity under control with the power of functional programming in Clojure and enticed us to try out CodeScene (I&apos;m starting the free trial as soon as I have a few free days in my calendar to point it at my company&apos;s fairly large Java, TypeScript / JavaScript + React, and .NET codebases to see where be the dragons), Adam summarises why we should all be using Clojure in 2026 (🤮 disclaimer on the first point):</p><p><img alt="Adam presents a slide labelled &quot;Why Clojure?&quot;" src="assets/2026-10-25-func-prog-conf-2026-why.jpg" title="Why not?" /></p><p>This was a fantastic talk and a great way to kick off the conference! I would recommend that everyone watches the talk as soon as it goes up (and I&apos;ll try to remember to update this blog post with the link to the recording when that happens), but in the meantime, you can also check out <a href="https://drive.google.com/file/d/17PEdPaeAqeRUpa-Nri_I1e48N7W8oPa3/view?pli=1">Adam&apos;s
slides</a>.</p><p>After the thunderous applause died down and Adam answered a question from the audience (which I didn&apos;t note down, but I remember as being an actual question, not the infamous Tech Bro &quot;Question&quot;) and folks started filing out, I took up my lurker&apos;s position near the stage, ready to intercept Adam before he could escape the auditorium.</p><p>I thanked him for his talk, admitted that I had only read the intro to his book, and invited him to come on defn and talk about all this awesome stuff. We&apos;re trying to find a date as I write this, so hopefully it works out and you&apos;ll have something to feast your ears on in a few weeks (and I&apos;ll try to remember to update this blog post with the link to the episode when that happens). 🎉</p><p>After a coffee break, the next talk began, and it was of a very different character to Adam&apos;s: Eric Torreborre&apos;s &quot;Beyond the Expression Problem&quot;.</p><div class="markdown-heading"><h2 id="beyond-the-expression-problem">Beyond the Expression Problem</h2><a href="#beyond-the-expression-problem" class="anchor" aria-label="Permalink: Beyond the Expression Problem"><img src="assets/link.svg" /></a></div><p>I have to admit that this one was tough going for me, so whilst the Haskellers and Scalars in the crowd nodded knowingly throughout, I took copious notes, which helps my brain decomplect.</p><p>Eric&apos;s talk was basically about the holy grail of compositional programming:</p><p><img alt="Eric presents a slide labelled &quot;Compositional programming&quot;" src="assets/2026-10-25-func-prog-conf-2026-comp.jpg" title="Seems good?" /></p><p>If you have no idea what that slide means, fear not! Eric explained it. And his explanation made sense to me at the time, but looking back at my notes as I write this, it seems that my absorption of the topic was limited to the absorption of ink into my notebook, and did not indeed penetrate my thick skull. Ah well, I can at least share a couple of slides that I enjoyed!</p><p><img alt="Eric presents a slide labelled &quot;Modularity is great!&quot;" src="assets/2026-10-25-func-prog-conf-2026-mod.jpg" title="An uncontroversial statement" /></p><p>Legos! And the Millennium Falcon! And <a href="https://www.lego.com/sv-se/product/millennium-falcon-75192">the Millennium Falcon made out of
Legos</a>! And yes, that does in fact cost basically 10,000 Swedish Crowns, which as of this writing is about 900 Euros or 1000 US Dollars. 🤯</p><p>So modularity is good, but</p><p><img alt="Eric presents a slide labelled &quot;In practice&quot;, showing a game of Tetris about to be lost" src="assets/2026-10-25-func-prog-conf-2026-tetris.jpg" title="Вот эта катастроф!" /></p><p>But not to worry</p><p><img alt="Eric presents a slide labelled &quot;Modularity is difficult, but there&apos;s hope!&quot;" src="assets/2026-10-25-func-prog-conf-2026-difficult.jpg" title="On Snowpiercer, 1001 cars long" /></p><p>Because the type system can save us!</p><p><img alt="Eric presents a slide labelled &quot;In practice&quot;" src="assets/2026-10-25-func-prog-conf-2026-magic.jpg" title="Pick a trait, any trait" /></p><p>&quot;That&apos;s a very simple lambda calculus in a way,&quot; quoth Eric, as my head exploded.</p><p>But then there&apos;s a twist: one has to actually implement this, which Eric illustrates as follows:</p><p><img alt="Eric presents a slide labelled &quot;In practice&quot;" src="assets/2026-10-25-func-prog-conf-2026-owl.jpg" title="Pick a trait, any trait" /></p><p>Eric&apos;s face falls. &quot;It sounds like the whole type system is useless.&quot; 😭</p><p>But there was a happy ending, and Eric concluded that it may be possible to implement this in a new programming language that he is working on together with some researchers.</p><p>Despite the type magic going a bit over my head, the talk was extremely engaging, and Eric got a few good questions at the end.</p><p>Mulling it over afterwards, I thought back to his explanation of the <a href="https://en.wikipedia.org/wiki/Expression_problem">expression
problem</a>, which is that it&apos;s difficult to extend types and functions at the same time. Unless I&apos;m missing something, it feels like Clojure makes this pretty easy: we have <a href="https://clojure.org/reference/multimethods">multimethods</a>, which cover the most common cases, and <a href="https://clojure.org/reference/protocols">protocols</a>, which &quot;avoid the &apos;expression problem&apos; by allowing independent extension of the set of types, protocols, and implementations of protocols on types&quot;.</p><p>I was reminded of a Haskell team that I managed a few years back. They had a huge amount of fun, constructing elegant cathedrals of types and typeclasses and higher-kinded types to solve problems that they had created for themselves. Meanwhile, our stakeholders were becoming increasingly desperate for us to like actually ship the software so we could actually like solve an important problem for our customers.</p><p>I don&apos;t claim this is representative of static type enthusiasts working in industry, only that a significant portion of my interaction with the statically typed programming language communities (both at work and conferences) tends toward the esoteric and academic. And no shade, that&apos;s very interesting. I often enjoy Haskell and Scala talks at conferences (even when my comprehension level is usually 25% at best), and definitely like the vibe of a group of people excitedly expanding their minds in communion with each other.</p><p>But here&apos;s my problem: I&apos;ve ended up in one too many conversations over the years where I magnanimously offer that statically typed and dynamically typed languages are equally valid, offer different tradeoffs, and ultimately tend toward the shape of the programmer&apos;s mind, rather than an inherent superiority of one over the other, only to be told confidently &quot;you don&apos;t get it&quot; (almost certainly true, but I feel that validates rather than invalidates my assertion), or &quot;you probably just haven&apos;t worked on large enough systems to have seen the limitations of dynamic typing&quot; (I always have to bite my tongue not to be That Guy™ and mention a certain e-commerce website that I worked on for a few years, in a dynamically typed language). I don&apos;t go around trying to convince people that Clojure is better than their favourite statically typed programming language, I just make the statement that Clojure is better <strong>for me</strong> than their favourite statically typed programming language.</p><p>Anyway, after this feast for the mind came a feast for the body, in the form of lunch. I had some kind of vegan salad thingy with falafel and other stuff, which was as delicious as a deftly placed <code>defmethod</code>, especially with a side of conversation with Arne and Christoph, which continued whilst relaxing on some comfortable sofas on a mezzanine overlooking the stage, which I must shamefully admit caused us to pay only cursory attention to Adam Warski&apos;s &quot;The Scala 3 Features for Agentic Development, Today and Tomorrow&quot; (🤮 disclaimer on the middle part of the title). But such is the cost of fellowship, and it&apos;s one I&apos;ll gladly pay!</p><p>The next talk, however, drew me downstairs and into the auditorium like a moth to a flame: Giuseppe Castagna and Guillaume Duboc presenting &quot;All Set: Bringing Static Types to Elixir&quot;. See, I told you there was a point to my previous rhapsody on Elixir!</p><div class="markdown-heading"><h2 id="the-iron-fist-of-josé-valim">The iron fist of José Valim</h2><p><img alt="Giuseppe being introduced by Christoffer Ekeroth" src="assets/2026-10-25-func-prog-conf-2026-allset.jpg" title="This Elixir heals damage of all types, even higher-kinded ones" /></p><p>I absolutely loved this talk! Of course, I am extremely partial to Elixir. In fact, if every Lisp disappeared from the world tomorrow, I would shed a single tear, and then, like a <a href="https://www.phoenixframework.org/">Phoenix</a> rising from the ashes, be reborn as an Elixir programmer.</p><p>The talk started with Giuseppe showing some code with type annotations in a comment above each function, but they were different from the type of type annotations (sorry, I promise that wasn&apos;t intentional) I&apos;m used to seeing. In fact, these type annotations read more like pseudocode, which, like, I can get behind.</p><p>Giuseppe admitted that all wasn&apos;t rainbows and unicorns, however:</p><p><img alt="Giuseppe presents a slide labelled &quot;Precise typing of pattern matching&quot;" src="assets/2026-10-25-func-prog-conf-2026-precise.jpg" title="omg wtf etc" /></p><p>I mean... I can&apos;t help but deploy this meme:</p><p><img alt="Charlie Day gestures wildly in front of a board with papers connected by a web of red string" src="assets/2026-10-25-func-prog-conf-2026-charlie.jpg" title="T/p is the type for the capture variables in p when it is matched against values in T" /></p><p>But wait, Giuseppe is about to turn my frown upside down!</p><blockquote><p>&quot;The hard part is to derive algorithms to decide if a type <strong>s</strong> is a subtype of a type <strong>t</strong>. But don&apos;t worry, we know how to do that, so you don&apos;t have to do it yourself.&quot;</p></blockquote><p>Hurrah!</p><p>I don&apos;t remember the exact context for this quote, but it amused me enough for me to jot it down in my notebook:</p><blockquote><p>&quot;That seems silly, but is actually very smart.&quot;</p></blockquote><p>The coolest part of the talk was when Giuseppe revealed Elixir creator José Valim&apos;s reaction to their work. &quot;Very cool,&quot; quoth he, &quot;but here are my requirements for adding it to the compiler&quot;:</p><ol start="1"><li>You don&apos;t have to annotate the entire codebase in order to start seeing benefits (gradual typing!)</li><li>Types don&apos;t modify the runtime semantics of your program</li></ol><p>The rest of the talk was about how they implemented their type system within José&apos;s constraints, and it was a very clever solution indeed, as it ended up not requiring any annotations (I think), but rather using type inference to make the type checking as strict as it could be whilst not pushing the programmer into that annoying situation where you know your code is correct, but end up arguing with the compiler for hours before giving up and just throwing an <code>Any</code> or <code>void *</code> or whatever at it just to shut it up.</p><p>They also measured the type checking time as a proportion of the overall compilation time, with the goal of keeping it under 10% (I think—I didn&apos;t write down the actual target, for some reason).</p><p>So yeah, great talk!</p><p>And finally, it was time for Christoph Neumann to deploy some game theory to help us navigate the challenges of industrial programming.</p><h2 id="infinite-coding">Infinite Coding</h2><a href="#the-iron-fist-of-josé-valim">The iron fist of José Valim</h2><p><img alt="Giuseppe being introduced by Christoffer Ekeroth" src="assets/2026-10-25-func-prog-conf-2026-allset.jpg" title="This Elixir heals damage of all types, even higher-kinded ones" /></p><p>I absolutely loved this talk! Of course, I am extremely partial to Elixir. In fact, if every Lisp disappeared from the world tomorrow, I would shed a single tear, and then, like a <a href="https://www.phoenixframework.org/">Phoenix</a> rising from the ashes, be reborn as an Elixir programmer.</p><p>The talk started with Giuseppe showing some code with type annotations in a comment above each function, but they were different from the type of type annotations (sorry, I promise that wasn&apos;t intentional) I&apos;m used to seeing. In fact, these type annotations read more like pseudocode, which, like, I can get behind.</p><p>Giuseppe admitted that all wasn&apos;t rainbows and unicorns, however:</p><p><img alt="Giuseppe presents a slide labelled &quot;Precise typing of pattern matching&quot;" src="assets/2026-10-25-func-prog-conf-2026-precise.jpg" title="omg wtf etc" /></p><p>I mean... I can&apos;t help but deploy this meme:</p><p><img alt="Charlie Day gestures wildly in front of a board with papers connected by a web of red string" src="assets/2026-10-25-func-prog-conf-2026-charlie.jpg" title="T/p is the type for the capture variables in p when it is matched against values in T" /></p><p>But wait, Giuseppe is about to turn my frown upside down!</p><blockquote><p>&quot;The hard part is to derive algorithms to decide if a type <strong>s</strong> is a subtype of a type <strong>t</strong>. But don&apos;t worry, we know how to do that, so you don&apos;t have to do it yourself.&quot;</p></blockquote><p>Hurrah!</p><p>I don&apos;t remember the exact context for this quote, but it amused me enough for me to jot it down in my notebook:</p><blockquote><p>&quot;That seems silly, but is actually very smart.&quot;</p></blockquote><p>The coolest part of the talk was when Giuseppe revealed Elixir creator José Valim&apos;s reaction to their work. &quot;Very cool,&quot; quoth he, &quot;but here are my requirements for adding it to the compiler&quot;:</p><ol start="1"><li>You don&apos;t have to annotate the entire codebase in order to start seeing benefits (gradual typing!)</li><li>Types don&apos;t modify the runtime semantics of your program</li></ol><p>The rest of the talk was about how they implemented their type system within José&apos;s constraints, and it was a very clever solution indeed, as it ended up not requiring any annotations (I think), but rather using type inference to make the type checking as strict as it could be whilst not pushing the programmer into that annoying situation where you know your code is correct, but end up arguing with the compiler for hours before giving up and just throwing an <code>Any</code> or <code>void *</code> or whatever at it just to shut it up.</p><p>They also measured the type checking time as a proportion of the overall compilation time, with the goal of keeping it under 10% (I think—I didn&apos;t write down the actual target, for some reason).</p><p>So yeah, great talk!</p><p>And finally, it was time for Christoph Neumann to deploy some game theory to help us navigate the challenges of industrial programming.</p><h2 id="infinite-coding" class="anchor" aria-label="Permalink: Infinite Coding"><img src="assets/link.svg" /></a></div><p><img alt="Christoph presents a slide labelled &quot;Finite and Infinite Games&quot;" src="assets/2026-10-25-func-prog-conf-2026-games.jpg" title="Wasn&apos;t this a Marvel movie?" /></p><p>Before revealing the meaning behind the titillating title of his talk, however, Christoph poses what I can only assume is a rhetorical question:</p><p><img alt="Christoph presents a slide labelled &quot;What is your favorite programming language?&quot;" src="assets/2026-10-25-func-prog-conf-2026-fav.jpg" title="I&apos;m guessing the answer ain&apos;t gonna be Ada" /></p><p>But then, he posed a tougher question: if you could not use your favourite programming language, what language would you use instead?</p><p>This question was actually posed in the <a href="https://clojure.org/news/2026/02/18/state-of-clojure-2025#_1_in_10_clojure_developers_would_quit_programming_without_clojure">2025 State of
Clojure</a> survey, and the top five answers were mostly unsurprising:</p><ol start="1"><li>Java - 11.40% 🤷🏼</li><li>Python - 10.09% 🐍</li><li>Quit programming - 9.89% 😲</li><li>Elixir - 9.08% 💜💜💜</li><li>TypeScript - 7.06% 😬</li></ol><p>But wait, what&apos;s going on at #3 there?</p><p>Apparently, <strong>nearly 1 in 10 Clojure programmers would actually quit programming altogether if they could not use Clojure</strong>! 🤯</p><p>I&apos;m one of the 9 out of 100 that would use Elixir (unless I could sneak Scittle or Babashka or Jank or Clojerl or Cherry or Squint past the Ministry of Love), as noted above, but I totally get the sentiment.</p><p>Most of the Clojurists in the audience had already seen this, either when the State of Clojure results were published back in February, or the day before during Christoph&apos;s dry run at the sthlm.clj meetup, but minds were clearly blown in the audience, and many a furrowed brow was spotted as Haskellers and Scalars contemplated life without their powerful types and slow compilers (sorry! I jest out of love for my fellow Functionalistas) and Elixirians despaired at the thought of letting it crash only to find it&apos;s unsupervised.</p><p>Having gotten the audience&apos;s attention, Christoph made a statement that I think everyone in the room would have agreed with two years ago: making software is hard. He then issued an update which I hope is uncontroversial amongst the people in the audience and readership of this blog, even in 2026: making <strong>excellent</strong> software is hard. If this is the case, a deeper question emerges:</p><p><img alt="Christoph presents a slide labelled &quot;What makes software excellent?&quot;" src="assets/2026-10-25-func-prog-conf-2026-excellent.jpg" title="It&apos;s written in Clojure! By a human!" /></p><p>Christoph ended his talk early by just giving us the answer: functional programming! (and monads), drawing a hearty laugh from the crowd. But of course he wasn&apos;t actually done, and like the good Clojurian he is, he pointed out that there&apos;s no way to answer a question such as &quot;what makes software excellent?&quot; without defining the word &quot;excellent&quot;:</p><p><img alt="Christoph presents a slide labelled &quot;excellent = surpass, be superior&quot;" src="assets/2026-10-25-func-prog-conf-2026-definition.jpg" title="Gotta own a copy of the OED to write Clojure" /></p><p>And <strong>now</strong> it&apos;s officially a Clojure talk!</p><p>OK, but now that we know what &quot;excellent&quot; means, we must ask ourselves what our software should be excellent at. Christoph offers some common options:</p><ul><li>Performance</li><li>Speed of creation</li><li>Reliability</li><li>Feature set</li><li>Usability</li><li>Maintainability</li><li>Correctness</li><li>Code expressiveness</li><li>Token spend 🤮</li></ul><p>But then there&apos;s a twist! Excellence at any of these matters not a whit if you&apos;re not solving real-world problems!</p><p><img alt="Christoph presents a slide labelled &quot;Real-World Problems&quot;" src="assets/2026-10-25-func-prog-conf-2026-real.jpg" title="I gotta be real with you" /></p><p>And to solve problems, we must make choices. But there&apos;s a paradox here: choosing an option reduces our options! 😱</p><p>There is a way to manage this paradox, though. If we separate our choices, make them truly independent of each other, a choice in one space only affects that part of the solution, leaving options open elsewhere. And this, my dear friends, is why we decomplect. If you&apos;re not a Clojurist, &quot;decomplect&quot; means something like &quot;to take apart a complex thing by unbraiding it into its constituent pieces, each of which can now be used independently&quot;. I actually couldn&apos;t find a good reference for the definition, so if anyone reading this can point me at one, that would be wonderful. Rich Hickey does however clearly define the word &quot;complect&quot; in his epic <a href="https://youtu.be/SxdOUGdseq4?t=1896">Simple Made
Easy</a> talk: &quot;to interleave, entwine, or braid&quot;. (By the way, there&apos;s an amazing repo on GitHub called <a href="https://github.com/matthiasn/talk-transcripts/tree/master">talk-transcripts</a>, which has full transcripts for loads of talks by such luminaries as Rich Hickey, Alan Kay, David Nolan, Guy Steele, Evan Czaplicki, etc.)</p><p>OK, back to Christoph. Having elucidated the paradox of choice and offering us a way out, Christoph asserts that changeability (and of course he includes a definition slide: the ability to make the changes that we want or need) is the central factor of longevity of an excellent codebase. Remembering the paradox of choice, one of the best design questions we can ask ourselves is &quot;what choices can we defer?&quot; I can&apos;t remember where I read this, but someone said that what we should be doing is not making choices at the last possible moment, but rather at the last <strong>responsible</strong> moment, and I think that&apos;s what Christoph is getting at here.</p><p>And now another definition. Optionality: preservation of choices. We want to preserve optionality for as long as <s>possible</s> responsible, allowing us to decide later when we have more information. Having now presented the concepts of changeability and optionality, Christoph tells us what they have to offer us:</p><ul><li>Changeability avoids rigidity, but</li><li>Optionality avoids choices</li></ul><p>And optionality is more important to us as programmers than changeability.</p><p>Finally, Christoph reveals why his talk is titled &quot;Infinite Coding&quot;. In a book from 1986 called <a href="https://en.wikipedia.org/wiki/Finite_and_Infinite_Games">Finite and Infinite
Games</a>, the philosopher James P. Carse proposed that</p><blockquote><p>all human behavior can be categorized into two types of play. Finite games, such as chess or politics, have defined boundaries, fixed rules, and clear winners, played with the sole purpose of bringing the game to an end. In contrast, infinite games, such as culture, love, and life itself, have evolving rules and open boundaries; they are played for the purpose of continuing play and welcoming new participants.</p></blockquote><p>Christoph thinks this is a very useful theoretical construct for talking about programming, and he simplifies the concept for us:</p><ul><li>The goal of a finite game is to win.</li><li>The goal of an infinite game is to keep playing indefinitely.</li></ul><p>Finite games have boundaries, such as time, rules, and players, whereas in order to keep playing an infinite game (which is the goal), the rules <strong>must</strong> change, and play is in fact threatened by boundaries of the sort imposed by finite games.</p><p>So what does this have to do with software?</p><p><img alt="Christoph presents a slide labelled &quot;Working on software is indefinite, therefore an infinite game&quot;" src="assets/2026-10-25-func-prog-conf-2026-software.jpg" title="Most definitely infinite" /></p><p>For systems that solve real-world problems, which tend to evolve over time, we want to be able to evolve our software for as long as the problem exists; in other words, we want to keep playing indefinitely. When our software becomes so rigid that we cannot change it anymore, the game ends, and we lose.</p><p>So what kinds of things end the infinite game of software?</p><ul><li>Constraint deadlock: you modelled the problem one way, necessarily accepting a set of constraints, but now you realise you got the model wrong, and those constraints make it difficult to change the model.</li><li>Intractability: the code becomes difficult to understand, and therefore difficult to safely change.</li><li>Too many bugs: software that is unreliable is often worse than no software at all.</li><li>Burnout: you get so worn out by trying to work on a system that you just can&apos;t anymore.</li><li>Inability to bring in a new player: if you can&apos;t onboard a new developer, you&apos;re stuck carrying the load yourself.</li></ul><p>Like all infinite games, as we play the game of software, we encounter many finite games along the way, such as:</p><ul><li>The optimisation game: we specialise code, thus sacrificing optionality for the sake of performance.</li><li>The feature game: we add feature after feature after feature, which requires making choice after choice after choice.</li><li>The metrics game: story points, velocity, lines of code, tokens (🤮); line go up good!</li><li>The framework game: the One Framework makes so many promises, but we are all of us ultimately betrayed and fall into the walking death that is constraint deadlock.</li><li>The programming language game: the One Language makes so many promises, but demands of us fealty to its theory of computation.</li><li>The hiring game: as our system grows, we want to bring in new players, but it is hard to find the right players with the right skills and the right potential at the right time. And the cost of bringing in the wrong player can be incredibly high.</li><li>The pain-shifting game: we sacrifice tomorrow to win today (AKA incur &quot;technical debt&quot;—a phrase I don&apos;t love, for reasons that Eric Normand <a href="https://ericnormand.substack.com/p/its-time-to-stop-saying-technical">elucidates so eloquently in his
  newsletter</a>), or we suffer and management wins.</li></ul><p>As any programmer will attest, playing finite games is necessary. However, finite games may harm the infinite game, and it&apos;s possible to win our way into failure. What we want to do is to win the finite games we play, but choose to play only the ones that don&apos;t threaten the infinite game.</p><p>To keep the infinite game going, we want to:</p><ul><li>Avoid limits (insofar as we can),</li><li>isolate change (when we must change),</li><li>and avoid the need to change in the first place.</li></ul><p>To avoid the need to change, we need to identify the things that don&apos;t change, which is of course easier said than done. There is hope, however, as Christoph points us at a book by Morgan Housel called <a href="https://www.penguinrandomhouse.com/books/672339/same-as-ever-by-morgan-housel/">Same As
Ever</a>, and then offers some examples from the programming game:</p><ul><li>Data: data formats may change, but yesterday&apos;s weather data is forever. It was 14 degrees and mostly cloudy in Stockholm at 16:19 at the Södermalm weather station, and so it shall remain until the death of the universe and therefore time itself.</li><li>Generic solutions (but not specific ones): <code>map</code>, <code>filter</code>, and <code>reduce</code> are eternal, regardless of which functions we&apos;re mapping over, filtering by, and reducing with.</li><li>Parts of the software (but not the whole code base): if you haven&apos;t seen Clojure&apos;s <a href="https://blog.sbensu.com/posts/demand-for-visual-programming/#code_retention_diagram">code retention
  diagram</a> (from Rich Hickey&apos;s <a href="https://dl.acm.org/doi/pdf/10.1145/3386321">History of
  Clojure</a> paper), which shows when code in the Clojure codebase was introduced, and how long it was retained, check it out below.</li><li>The loose (but not the tight): the more loosely coupled the parts of our system are, the more easily we can handle change, growth, and movement.</li><li>Separate things (but not combined things): or, to translate this into Clojurese, simple things, not complected things.</li></ul><p><img alt="Graph labelled &quot;Clojure codebase - Introduction and retention of code&quot;" src="assets/2026-10-25-func-prog-conf-2026-burndown.png" title="Sick burndown!" /></p><p>Christoph now poses the question of what keeps the infinite game going? And then of course offers some answers:</p><ul><li>Keep data central and behavior separate and independent.</li><li>Keep data open, not closed (e.g. include in your schemas only the fields you need to do your job, and allow other fields to be there).</li><li>Apply consistency when it&apos;s useful but not for its own sake (Rich Hickey refers to this as &quot;pouring concrete&quot;; don&apos;t do it until you&apos;re sure you have the right shape).</li><li>Avoid unnecessary dependencies, which come with their own sets of constraints that someone else has chosen.</li><li>Maintain locality: constraints applied to an independent part of the system do not limit our choices in other parts of the system.</li><li>Avoid unnecessary specification: what is specified cannot be easily changed.</li><li>Avoid boilerplate (if we remember <a href="#transforming-software-evolution">Adam&apos;s
  talk</a>, he offered one solution: embedded DSLs).</li><li>Make current code do more instead of adding lots of new code.</li></ul><p>But here comes the real world again:</p><p><img alt="Christoph presents a slide labelled &quot;The real world threatens play&quot;" src="assets/2026-10-25-func-prog-conf-2026-threat.jpg" title="Snap back to reality, oh there goes gravity" /></p><p>To play any game, we need a good strategy, and Christoph proposes one here:</p><ul><li>Avoid limits: opt into constraints really than accepting them unthinkingly.</li><li>Isolate change: by decomplecting, we get a set of simple pieces that we can compose as we see fit.</li><li>Avoid change: by identifying the unchanging, we can build with lasting pieces.</li></ul><p>By applying this strategy skilfully, we can maximise both changeability and optionality.</p><p><img alt="Christoph presents a slide labelled &quot;Maximize changeability and optionality&quot;" src="assets/2026-10-25-func-prog-conf-2026-maximise.jpg" title="A truly global maximum" /></p><p>And now for Christoph&apos;s mic drop moment:</p><blockquote><p>We are human. Playing must be fun and worthwhile!</p></blockquote><p>🫳🏻🎤💥</p><p>As you may have gathered from the number of words I expended writing about this talk, I thoroughly enjoyed it. My notes runneth to five pages, and verily did I consult <a href="https://christophneumann.dev/talks/2026-10-14/infinite-code.html">Christoph&apos;s
slides</a> to make sense of them.</p><p>With that, the conference was over... except it wasn&apos;t!</p><div class="markdown-heading"><h2 id="the-aftermath">The aftermath</h2><a href="#the-aftermath" class="anchor" aria-label="Permalink: The aftermath"><img src="assets/link.svg" /></a></div><p><img alt="Onstage from left to right: Giuseppe Castagna, Guillaume Duboc, Eric Torreborre, Adam Warski, Christoph Neumann, and Christoffer Ekeroth" src="assets/2026-10-25-func-prog-conf-2026-panel.jpg" title="Let&apos;s get ready to rumble!" /></p><p>The organisers gathered most of the speakers onstage for a panel discussion, which was lively and fun, with some disagreement expressed cordially. I wish I had taken notes, because I don&apos;t remember many of the questions (one was something like &quot;what is the future of functional programming?&quot; and I&apos;m sure there was an &quot;AI all the things?&quot; 🤮 one in there somewhere) or answers, but I do remember one of the panellists saying something about mutability and me getting so excited that I literally pointed at Christoph, willing him to mention transients in transducers, and getting even more excited when he asked for the mic, then less excited when he said something awesome but not as awesome as transients in transducers. 😂</p><p>Finally, Christoffer thanked the speakers, shooed them off the stage, and gave some closing words. Amongst those closing words were words hyping up some upcoming conferences, and amongst those were the <a href="https://2027.euroclojure.org/">EuroClojure
2027</a> reboot (May 19-21 in Prague), and Arne&apos;s own <a href="https://2027.heartconf.eu/">HeartConf</a>, the expansion of the legendary <a href="https://2024.heartofclojure.eu/">Heart of Clojure</a> conference (August 18-19 in Mechelen, Belgium).</p><p><img alt="Christoffer in front of a slide displaying the lineage of HeartConf" src="assets/2026-10-25-func-prog-conf-2026-heartconf.jpg" title="HeartConf is the heart of not just Clojure, but of humanity in programming" /></p><p>I&apos;ll definitely be at HeartConf (I&apos;ve already got several ideas brewing, just waiting for that sweet sweet CFP to open)—whether that&apos;s an enticement or deterrent I can&apos;t say—so hope to see you there!</p><p>With that, Christoffer thanked the sponsors for making the conference possible, the speakers for making the conference contentful, the organisers for making the conference, and the audience for making the conference awesome. He all but promised that there will be a Func Prog Conf 2027, and after basking in a huge round of applause, released us to go mingle. Which we did. My social batteries were running low, but I did have just enough juice to grab some juice of the barley (big thanks to the organisers for making sure non-alcoholic beer was available!) and making one last circumnavigation of the mingle zone, saying my thank yous and goodbyes and exchanging LinkedIn profiles and email addresses and Clojurians Slack usernames.</p><p>Arne was also feeling the need to recharge, so the two of us shook hands with Christoph and Magnus on our way out the door, then strolled through Södermalm to the place where Arne was staying, taking in the scenery (the clouds had parted and the sky was blue, though rapidly turning into dusk because it was after 17:00 in Stockholm in October) and enjoying some relaxed conversation which was not about Trump or AI (the rules of engagement at the Belgian Clojure meetup in Leuven, if you ever happen to be in the neighbourhood), then finally parted ways, he turning rightwards and I trying to orient myself in order to locate the nearest tunnelbana station.</p><p>I had done a pretty good job of keeping my phone in my pocket (except for photos and networking) and my attention in the moment all day, so I resisted the urge to whip out <a href="https://organicmaps.app/">Organic Maps</a>, and instead ducked into a restaurant to actually ask a human being for directions. The human was most obliging, and pointed me &quot;rakt fram&quot; down Folkungagatan, and I enjoyed a leisurely 20 minute stroll through the heart of Söder, the lights coming on as the sky darkened, people going about their business, bicycles cruising past; in short, the city breathing.</p><p>What a lovely end to a lovely day.</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-09-18-podcast-soundcljoud.html</id>
    <link href="https://jmglov.net/blog/2024-09-18-podcast-soundcljoud.html"/>
    <title>Building a podcast with Clojure</title>
    <updated>2024-09-18T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>In addition to spending far too much of my time doing silly things with Clojure and then even farther too much of my time writing about doing silly things with Clojure, I spend some of my time thinking about, talking about, and participating in labour organising here in Sweden. As I was talking about unions and such to Ray one day, no doubt six tangents into one of my usual rambling explorations of an idea, he interrupted my flow. &quot;Stop!&quot; he said, &quot;for I have a plan so cunning you could pin a tail on it and call it a weasel!&quot; Curiosity piqued, I enquired as to the nature of said plan. &quot;We should make a podcast,&quot; he continued, &quot;and on this podcast, we should talk about tech workers and why it makes sense for them to unionise. And we should focus on Sweden, since it&apos;s a fairly unique labour market, plus you know interesting people who we could interview.&quot;</p><p>&quot;Ray,&quot; I rejoined, &quot;that truly is a plan of weasel-grade cunning. I have but one suggestion that will turn this good idea into a great one.&quot; &quot;And what,&quot; quoth he, &quot;pray tell, is that suggestion?&quot; &quot;Babashka! Scittle! Clojure!&quot; I exclaimed, so full of excitement I was having troubling supporting my proper nouns with clauses of explanatory power. &quot;We could use all of this amazing technology for all of the heavy lifting around making a podcast! We could <a href="2022-06-24-s3-https.html">build a website
using S3 static hosting</a>, then we could use an approach similar to <a href="https://jmglov.net/blog/tags/blog.html">how I built my
blog</a> to create pages for episodes with show notes and transcripts and all that good stuff!&quot;</p><p>So it was agreed, and thus <a href="https://orgtech.se">Organising Tech in Sweden</a> came to be.</p><p><img alt="The words &apos;Organising Tech in Sweden&apos; superimposed on raised fists with a Swedish flag with a circuit board pattern in the background" src="assets/2024-09-18-podcast-soundcljoud-orgtech.png" title="Divided we beg, united we bargain!" width="512px" /></p><div class="markdown-heading"><h2 id="building-the-website">Building the website</h2><a href="#building-the-website" class="anchor" aria-label="Permalink: Building the website"><img src="assets/link.svg" /></a></div><p>As with any of my recent projects, my first step is always to create a directory and drop a <a href="https://github.com/babashka/scittle/">Scittle</a>-enabled <code>bb.edn</code> in it:</p><pre><code class="language-text">: ~; mkdir ~/code/orgtech-se
: ~; cd !$
</code></pre><p><strong>bb.edn</strong></p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;2f8a9ed2d39a1b09d2b4d34d95494b56468f4a23&quot;}
        io.github.babashka/http-server
        {:git/sha &quot;e203166a020509d126149ff8046489857ce5c89f&quot;}}
 :tasks
 {http-server {:doc &quot;Starts http server for serving static files&quot;
               :requires ([babashka.http-server :as http])
               :task (do (http/serve {:port 1341 :dir &quot;public&quot;})
                         (println &quot;Serving static assets at http://localhost:1341&quot;))}

  browser-nrepl {:doc &quot;Start browser nREPL&quot;
                 :requires ([sci.nrepl.browser-server :as bp])
                 :task (bp/start! {})}

  -dev {:depends [http-server browser-nrepl]}

  dev {:task (do (run &apos;-dev {:parallel true})
                 (deref (promise)))}}}
</code></pre><p>Since this is a static website, we can create a static <code>public/index.html</code> for it, with the <a href="2022-07-05-hacking-blog-favicon.html">usual favicon</a> and <a href="2022-08-17-hacking-blog-sharing.html">social
sharing</a> stuff:</p><pre><code class="language-html">&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;

&lt;head&gt;
  &lt;title&gt;Organising Tech in Sweden Podcast&lt;/title&gt;

  &lt;meta charset=&quot;utf-8&quot; /&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot; /&gt;

  &lt;link rel=&quot;stylesheet&quot; href=&quot;/css/main.css&quot;&gt;

  &lt;!-- Favicon from https://realfavicongenerator.net/ --&gt;
  &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;180x180&quot; href=&quot;/apple-touch-icon.png&quot;&gt;
  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;32x32&quot; href=&quot;/favicon-32x32.png&quot;&gt;
  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;16x16&quot; href=&quot;/favicon-16x16.png&quot;&gt;
  &lt;link rel=&quot;manifest&quot; href=&quot;/site.webmanifest&quot;&gt;
  &lt;link rel=&quot;mask-icon&quot; href=&quot;/safari-pinned-tab.svg&quot; color=&quot;#5bbad5&quot;&gt;
  &lt;meta name=&quot;msapplication-TileColor&quot; content=&quot;#da532c&quot;&gt;
  &lt;meta name=&quot;theme-color&quot; content=&quot;#ffffff&quot;&gt;

  &lt;!-- Social sharing (Facebook, Twitter, LinkedIn, etc.) --&gt;
  &lt;meta name=&quot;title&quot; content=&quot;Organising Tech in Sweden&quot;&gt;
  &lt;meta name=&quot;twitter:title&quot; content=&quot;Organising Tech in Sweden&quot;&gt;
  &lt;meta property=&quot;og:title&quot; content=&quot;Organising Tech in Sweden&quot;&gt;
  &lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;

  &lt;meta name=&quot;description&quot; content=&quot;A limited podcast series exploring union organising in Swedish tech companies&quot;&gt;
  &lt;meta name=&quot;twitter:description&quot;
    content=&quot;A limited podcast series exploring union organising in Swedish tech companies&quot;&gt;
  &lt;meta property=&quot;og:description&quot; content=&quot;A limited podcast series exploring union organising in Swedish tech companies&quot;&gt;

  &lt;meta name=&quot;twitter:url&quot; content=&quot;https://orgtech.se/&quot;&gt;
  &lt;meta property=&quot;og:url&quot; content=&quot;https://orgtech.se/&quot;&gt;

  &lt;meta name=&quot;twitter:image&quot; content=&quot;https://orgtech.se/img/orgtech-se-preview.jpg&quot;&gt;
  &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot;&gt;
  &lt;meta property=&quot;og:image&quot; content=&quot;https://orgtech.se/img/orgtech-se-preview.jpg&quot;&gt;
  &lt;meta property=&quot;og:image:alt&quot;
    content=&quot;Podcast logo: &apos;Organising Tech in Sweden&apos; superimposed on raised fists with a Swedish flag with a circuit board pattern in the background&quot;&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;div id=&quot;wrapper&quot;&gt;
    &lt;div id=&quot;left-side&quot;&gt;
      &lt;div id=&quot;cover-image&quot;&gt;
        &lt;img src=&quot;/img/orgtech-se-cover.jpg&quot;
          title=&quot;Organising Tech in Sweden&quot;
          alt=&quot;Podcast logo: &apos;Organising Tech in Sweden&apos; superimposed on raised fists with a Swedish flag with a circuit board pattern in the background&quot; /&gt;
      &lt;/div&gt;
      &lt;div id=&quot;aggregators-1&quot;&gt;
        &lt;div id=&quot;apple&quot;&gt;
          &lt;a class=&quot;apple-button&quot;
            href=&quot;https://podcasts.apple.com/us/podcast/organising-tech-in-sweden/id1766442275?itsct=podcast_box_badge&amp;amp;itscg=30200&amp;amp;ls=1&quot;&gt;
            &lt;img src=&quot;https://tools.applemediaservices.com/api/badges/listen-on-apple-podcasts/badge/en-us?size=250x83&amp;amp;releaseDate=1725494400&quot;
              title=&quot;Listen on Apple Podcasts&quot;
              alt=&quot;Listen on Apple Podcasts&quot;
              class=&quot;apple-button&quot;&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div id=&quot;spotify&quot;&gt;
          &lt;a href=&quot;https://open.spotify.com/show/53psoLoX187axvmgb80l1x&quot;&gt;
            &lt;img src=&quot;/img/spotify-podcast-badge-blk-grn-330x80.svg&quot;
              title=&quot;Listen on Spotify&quot;
              alt=&quot;Listen on Spotify&quot;&gt;
          &lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div id=&quot;aggregators-2&quot;&gt;
        &lt;div id=&quot;podbean&quot;&gt;
          &lt;a href=&quot;https://www.podbean.com/podcast-detail/2r2tz-31b053/Organising-Tech-in-Sweden-Podcast&quot;
            rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;
            &lt;img src=&quot;https://pbcdn1.podbean.com/fs1/site/images/badges/w600_1.png&quot;
              title=&quot;Listen on Podbean&quot;
              alt=&quot;Listen on Podbean&quot;&gt;
          &lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div id=&quot;main&quot;&gt;
      &lt;div id=&quot;header&quot;&gt;
        &lt;h1 id=&quot;title&quot; class=&quot;header&quot;&gt;Episode 1 is out now!&lt;/h1&gt;
        &lt;!-- &lt;h1 id=&quot;title&quot; class=&quot;header&quot;&gt;&lt;a href=&quot;episodes/&quot;&gt;Episodes&lt;/a&gt;&lt;/h1&gt; --&gt;
        &lt;div id=&quot;socials&quot;&gt;
          &lt;a href=&quot;https://x.com/orgtech_se&quot;&gt;
            &lt;img src=&quot;/img/twitter-color-svgrepo-com.svg&quot;
              title=&quot;Follow us on Twitter!&quot;
              alt=&quot;Twitter logo&quot; /&gt;
          &lt;/a&gt;
          &lt;a href=&quot;https://bsky.app/profile/orgtech-se.bsky.social&quot;&gt;
            &lt;img src=&quot;/img/bluesky-logo.svg&quot;
              title=&quot;Follow us on Bluesky!&quot;
              alt=&quot;Bluesky logo&quot; /&gt;
          &lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=&quot;text&quot;&gt;
        &lt;p&gt;
          Organising Tech in Sweden is a limited podcast series exploring union
          organising in Swedish tech companies. Join us as we sit down with some
          of the people involved in the campaigns to win collective bargaining
          rights at two of Sweden&apos;s tech unicorns, Klarna and Spotify.
        &lt;/p&gt;
        &lt;div id=&quot;production-info&quot;&gt;
          &lt;div&gt;
            &lt;p&gt;
              Listen to our latest episode:&lt;br /&gt;
              🔊 &lt;a href=&quot;/episodes/ep01-klarna-part1&quot;&gt;Organising Klarna - Part 1&lt;/a&gt;
            &lt;/p&gt;
            &lt;p&gt;
              Produced by Hakuna Matata Produktion
            &lt;/p&gt;
            &lt;p&gt;
              Cover art by &lt;a href=&quot;https://anyakjordan.com/&quot;&gt;Anya K. Jordan&lt;/a&gt;
              &lt;a href=&quot;https://bsky.app/profile/anyakjordan.bsky.social&quot;&gt;@anyakjordan.bsky.social&lt;/a&gt;
            &lt;/p&gt;
            &lt;p&gt;
              Theme music by &lt;a href=&quot;https://soundcloud.com/ptzery&quot;&gt;Ptzery&lt;/a&gt;
            &lt;/p&gt;
          &lt;/div&gt;
          &lt;div id=&quot;hmp-logo&quot;&gt;
            &lt;img src=&quot;/img/hakuna-matata-produktion.png&quot;
              title=&quot;Hakuna Matata Produktion&quot;
              alt=&quot;Hakuna Matata Produktion logo&quot;&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div id=&quot;news&quot;&gt;
    &lt;h1&gt;News&lt;/h1&gt;
    &lt;h2&gt;Episode 1 is out!&lt;/h2&gt;
    &lt;p&gt;🔊 &lt;a href=&quot;/episodes/ep01-klarna-part1&quot;&gt;Organising Klarna - Part 1&lt;/a&gt;&lt;/p&gt;
    &lt;p&gt;
      We kick off Organising Tech in Sweden in style by recounting the story of
      how a collective bargaining agreement (CBA) was won at Klarna, a major
      Swedish fintech. In fact, Klarna was the first unicorn in Sweden to be
      unionised (and probably the first unicorn in Europe as well)!
    &lt;/p&gt;
    &lt;p&gt;
      To hear all about how this went down, your co-hosts Josh and Ray are joined by
      Thomas, the founder of the Klarna Unionen Club (a union &quot;local&quot;, to use
      terminology that might be more familiar to US listeners); Sen, the chair of
      the club who won the bargaining agreement against the odds; and Kim, a former
      Klarna employee with extensive knowledge of Swedish labour law and market
      policy.
    &lt;/p&gt;
  &lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>We can grab all the nice images and such from the interwebs:</p><pre><code class="language-text">: ~/code/orgtech-se; curl \
  https://orgtech.se/orgtech-se-favicon-and-img.tar.gz \
  | tar xvz -C public
</code></pre><p>And of course we need to make it nice and responsive so it looks good both on a computer screen and a mobile phone screen. Let&apos;s create <code>public/css/main.css</code> and drop some stylish styles therein:</p><pre><code class="language-css">body {
  font:
    1.2em Helvetica,
    Arial,
    sans-serif;
  margin: 20px;
  padding: 0;
}

body &gt; div {
  max-width: 100%;
  margin-left: auto;
  margin-right: auto;
}

img {
  max-width: 100%;
}

a {
  text-decoration: none;
  &amp;:hover {
    text-decoration: underline;
  }
}

#header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

h1 {
  font-weight: bold;
  font-size: larger;
}

#socials {
  display: flex;
  gap: 10px;
}

#socials img {
  max-width: 32px;
  &amp;:hover {
    transform: scale(1.1);
  }
}

@media screen and (min-width: 600px) {

  body &gt; div {
    max-width: 800px;
    margin-top: 1em;
  }

  #wrapper {
    display: flex;
  }

  #cover-image {
    margin-right: 20px;
    max-width: 40%;
  }

}
</code></pre><p>Now we can fire up a local webserver:</p><pre><code class="language-text">: ~/code/orgtech-se; bb dev
Serving assets at http://localhost:1341
Serving static assets at http://localhost:1341
nREPL server started on port 1339...
Websocket server started on 1340...
</code></pre><p>Gaze ye now upon the glories of <a href="http://localhost:1341">http://localhost:1341</a>!</p><p><img alt="The words &apos;Organising Tech in Sweden&apos; superimposed on raised fists with a Swedish flag with a circuit board pattern in the background" src="assets/2024-09-18-podcast-soundcljoud-index.png" title="What even is a computer?" class="border" /></p><div class="markdown-heading"><h2 id="publishing-the-website">Publishing the website</h2><a href="#publishing-the-website" class="anchor" aria-label="Permalink: Publishing the website"><img src="assets/link.svg" /></a></div><p>We of course have already registered a domain and done the intricate dance of <a href="2022-06-24-s3-https.html">setting up S3 static website hosting and CloudFront and all of
that</a>, so all we need to do to publish our website is copy some files into our S3 bucket. And of course, what better way to do this than with a <a href="https://book.babashka.org/#tasks">Babashka task</a>?</p><p>As avid REPL-drivers, we want to use our REPL for task development as well, so the first thing we do is create a <code>tasks.clj</code> with a boring <code>publish</code> function in it:</p><pre><code class="language-clojure">(ns tasks)

(defn publish [{:keys [website-bucket out-dir] :as opts}]
  (println (format &quot;Publishing %s/ to s3://%s/&quot;
                   out-dir website-bucket)))
</code></pre><p>Now we need to hook that up to <code>bb.edn</code> by setting the classpath appropriately, pulling in our new <code>tasks</code> namespace, defining some options, and adding a <code>publish</code> task:</p><pre><code class="language-clojure">{:deps { ... }
 :paths [&quot;.&quot;]
 :tasks
 {:requires ([tasks])
  :init (def opts
          {:website-bucket &quot;orgtech.se&quot;
           :out-dir &quot;public&quot;})
  ;; ...
  publish (tasks/publish opts)}}
</code></pre><p>We can now test this:</p><pre><code class="language-text">: ~/code/orgtech-se; bb publish
Publishing public/ to s3://orgtech.se/
</code></pre><p>Jumping back to <code>tasks.clj</code>, we fire up a trusty <a href="https://docs.cider.mx/cider/index.html">CIDER</a> REPL with a <strong>C-c M-j</strong> (<code>cider-jack-in-clj</code>) flourish, followed by <strong>C-c C-k</strong> (<code>cider-load-buffer</code>) to evaluate the buffer (readers following along with an <a href="https://www.vim.org/">inferior</a> <a href="https://www.jetbrains.com/idea/">text</a> <a href="https://code.visualstudio.com/">editor</a> will have to perform whatever complex ritual necessary to start a REPL and connect to it and then evaluate the &quot;file&quot; or whatever your text editor calls the thing you&apos;re editing).</p><p>Thus equipped, we can open up a <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a>, define some <code>opts</code>, and evaluate our <code>publish</code> function:</p><pre><code class="language-clojure">(comment

  (def opts {:website-bucket &quot;orgtech.se&quot;
             :out-dir &quot;public&quot;})  ; C-c C-v f c e
  ;; =&gt; #&apos;tasks/opts

  (publish opts)  ; C-c C-e

  )
</code></pre><p>Our REPL buffer now looks something like this:</p><pre><code class="language-text">Started nREPL server at 127.0.0.1:44571
For more info visit: https://book.babashka.org/#_nrepl
;; Connected to nREPL server - nrepl://127.0.0.1:44571
;; CIDER 1.12.0 (Split), babashka.nrepl 0.0.6-SNAPSHOT
;; Babashka 1.3.188
;;     Docs: (doc function-name)
;;           (find-doc part-of-name)
;;   Source: (source function-name)
;;  Javadoc: (javadoc java-object-or-class)
;;     Exit: &lt;C-c C-q&gt;
;;  Results: Stored in vars *1, *2, *3, an exception in *e;
;;  Startup: /home/jmglov/.nix-profile/bin/bb nrepl-server localhost:0
Publishing public/ to s3://orgtech.se/
user&gt; 
</code></pre><p>OK, now it&apos;s time to figure out how to do the actual copying of files to S3. We could of course use the spectacular <a href="https://github.com/grzm/awyeah-api">awyeah-api</a> to do stuff to AWS right from our Clojure code, but that smacks of effort. 🤔</p><p>Fortunately, we remember that Babashka was originally conceived as a replacement for Bash shell scripting (I mean, the &quot;bash&quot; is right there in the name, so that&apos;s kind of a major clue), and we know that there&apos;s an <a href="https://aws.amazon.com/cli/">AWS command line
tool</a> that knows how to sync stuff from a local directory to S3:</p><pre><code class="language-text">: ~/code/orgtech-se; aws s3 sync help
SYNC()                                                                  SYNC()

NAME
       sync -

DESCRIPTION
       Syncs  directories  and S3 prefixes. Recursively copies new and updated
       files from the source directory to the destination. Only creates  fold-
       ers in the destination if they contain one or more files.

SYNOPSIS
            sync
          &lt;LocalPath&gt; &lt;S3Uri&gt; or &lt;S3Uri&gt; &lt;LocalPath&gt; or &lt;S3Uri&gt; &lt;S3Uri&gt;

[...]

EXAMPLES

       The following sync command syncs objects from a local diretory  to  the
       specified  prefix and bucket by uploading the local files to s3.  A lo-
       cal file will require uploading if the size of the local file  is  dif-
       ferent  than  the  size of the s3 object, the last modified time of the
       local file is newer than the last modified time of the  s3  object,  or
       the  local  file  does not exist under the specified bucket and prefix.
       In this example, the user syncs the bucket mybucket to the  local  cur-
       rent  directory.   The  local  current  directory  contains  the  files
       test.txt and test2.txt.  The bucket mybucket contains no objects:

          aws s3 sync . s3://mybucket

       Output:

          upload: test.txt to s3://mybucket/test.txt
          upload: test2.txt to s3://mybucket/test2.txt

[...]
</code></pre><p>This looks like just the thing we need, so let&apos;s use the power of <a href="https://github.com/babashka/process">babashka.process</a> to invoke <code>aws s3 sync</code>:</p><pre><code class="language-clojure">(ns tasks
  (:require [babashka.process :as p]))

(defn publish [{:keys [website-bucket out-dir] :as opts}]
  (let [sync-cmd [&quot;aws s3 sync&quot;
                  (format &quot;%s/&quot; out-dir)
                  (format &quot;s3://%s/&quot; website-bucket)]]
    (apply println sync-cmd)
    (apply p/shell sync-cmd)))

(comment

  (def opts {:website-bucket &quot;orgtech.se&quot;
             :out-dir &quot;public&quot;})  ; C-c C-v f c e
  ;; =&gt; #&apos;tasks/opts

  (publish opts)  ; C-c C-e

  )
</code></pre><p>After a brief delay, our REPL buffer now helpfully tells us:</p><pre><code class="language-text">aws s3 sync public/ s3://orgtech.se/
user&gt; 
</code></pre><p>And if we have a look in that there bucket, we see some files:</p><pre><code class="language-text">: ~/code/orgtech-se; aws s3 ls --recursive s3://orgtech.se/
2024-08-23 10:40:05     102613 android-chrome-192x192.png
2024-08-23 10:40:05     337153 android-chrome-512x512.png
2024-08-23 10:40:05      96934 apple-touch-icon.png
2024-08-23 10:40:05        246 browserconfig.xml
2024-08-23 10:40:05        720 css/main.css
2024-08-23 10:40:05      47189 favicon-16x16.png
2024-08-23 10:40:05      48597 favicon-32x32.png
2024-08-23 10:40:05      12014 favicon.ico
2024-08-23 10:40:05        745 img/bluesky-logo.svg
2024-08-23 10:40:05    3231594 img/orgtech-se-cover.jpg
2024-08-23 10:40:05     513884 img/orgtech-se-preview.jpg
2024-08-23 10:40:05       1943 img/twitter-color-svgrepo-com.svg
2024-08-23 10:40:05       1933 img/volume.png
2024-08-23 10:40:05       3074 index.html
2024-08-23 10:40:05      33084 mstile-150x150.png
2024-08-23 10:40:05        426 site.webmanifest
</code></pre><p>And now browsing to <a href="https://orgtech.se/">https://orgtech.se/</a> reveals a lovely little website that looks just like the one on <a href="http://localhost:1341">http://localhost:1341</a>. 🎉</p><p>Let&apos;s change the header in <code>public/index.html</code> to test out the syncing:</p><pre><code class="language-html">        &lt;h1 id=&quot;title&quot; class=&quot;header&quot;&gt;Coming Thursday, 12 September!&lt;/h1&gt;
</code></pre><p>Before we YOLO eval our <code>publish</code> function again, we notice that <code>aws s3 sync</code> has a lovely little <code>--dryrun</code> option, which doesn&apos;t actually do the stuff but rather prints out what stuff it would do. Let&apos;s implement this!</p><p><strong>tasks.clj</strong></p><pre><code class="language-clojure">(defn publish [{:keys [website-bucket out-dir dryrun]
                :as opts}]
  (let [sync-cmd (concat [&quot;aws s3 sync&quot;]
                         (when dryrun [&quot;--dryrun&quot;])
                         [(format &quot;%s/&quot; out-dir)
                          (format &quot;s3://%s/&quot; website-bucket)])]
    (apply println sync-cmd)
    (apply p/shell sync-cmd)))

(comment

  (publish (assoc opts :dryrun true))  ; C-c C-e

  )
</code></pre><p>The REPL window helpfully says:</p><pre><code class="language-text">aws s3 sync --dryrun public/ s3://orgtech.se/
user&gt; 
</code></pre><p>but we don&apos;t see the output of the <code>aws s3 sync</code> command itself. This is due to the REPL not capturing stdout for the subprocess, I guess. We can handle this thusly:</p><pre><code class="language-clojure">(ns tasks
  (:require [babashka.process :as p]))

(defn shell [&amp; args]
  (let [p (apply p/shell {:out :string
                        :err :string
                        :continue true}
                 args)]
    (println (:out p))
    (when-not (zero? (:exit p))
      (println (:err p)))
    p))

(defn publish [{:keys [website-bucket out-dir dryrun]
                :as opts}]
  (let [sync-cmd (concat [&quot;aws s3 sync&quot;]
                         (when dryrun [&quot;--dryrun&quot;])
                         [(format &quot;%s/&quot; out-dir)
                          (format &quot;s3://%s/&quot; website-bucket)])]
    (apply println sync-cmd)
    (apply shell sync-cmd)))

(comment

  (publish (assoc opts :dryrun true))  ; C-c C-e

  )
</code></pre><p>And now the REPL sez:</p><pre><code class="language-text">aws s3 sync --dryrun public/ s3://orgtech.se/
(dryrun) upload: public/index.html to s3://orgtech.se/index.html

user&gt; 
</code></pre><p>This is what we expect to see: only <code>index.html</code> will be uploaded, since it&apos;s the only thing that has changed.</p><p>It would be nice to run this from the command line, but we currently have no way of passing the <code>dryrun</code> option through short of adding it to the <code>opts</code> map in <code>bb.edn</code>. Fortunately for us, there&apos;s <a href="https://github.com/babashka/cli">babashka-cli</a>, which does all sorts of awesome command-line parsing! Let&apos;s put it to work:</p><pre><code class="language-clojure">(ns tasks
  (:require [babashka.cli :as cli]
            [babashka.process :as p]))

;; ...

(comment

  (cli/parse-opts [&quot;--website-bucket&quot; &quot;orgtech.se&quot;
                   &quot;--out-dir&quot; &quot;public&quot;
                   &quot;--dryrun&quot;])
  ;; =&gt; {:website-bucket &quot;orgtech.se&quot;, :out-dir &quot;public&quot;, :dryrun true}

  )
</code></pre><p>Now we can use <code>parse-opts</code> in our <code>publish</code> function like so:</p><pre><code class="language-clojure">(defn publish [default-opts]
  (let [{:keys [website-bucket out-dir dryrun]
         :as opts} (merge default-opts
                          (cli/parse-opts *command-line-args*))
        sync-cmd (concat [&quot;aws s3 sync&quot;]
                         (when dryrun [&quot;--dryrun&quot;])
                         [(format &quot;%s/&quot; out-dir)
                          (format &quot;s3://%s/&quot; website-bucket)])]
    (apply println sync-cmd)
    (apply shell sync-cmd)))
</code></pre><p>Running this from the command line, we get the desired result:</p><pre><code class="language-text">: ~/code/orgtech-se; bb publish --dryrun
aws s3 sync --dryrun public/ s3://orgtech.se/
(dryrun) upload: public/index.html to s3://orgtech.se/index.html
</code></pre><p>And if we omit the <code>--dryrun</code> arg:</p><pre><code class="language-text">: ~/code/orgtech-se; bb publish --dryrun
aws s3 sync --dryrun public/ s3://orgtech.se/
upload: public/index.html to s3://orgtech.se/index.html
</code></pre><p>Amazing!</p><div class="markdown-heading"><h2 id="do-you-invalidate-parking?">Do you invalidate parking?</h2><a href="#do-you-invalidate-parking?" class="anchor" aria-label="Permalink: Do you invalidate parking?"><img src="assets/link.svg" /></a></div><p>If we open <a href="https://orgtech.se/index.html">https://orgtech.se/index.html</a> in a browser and view source, however, we get a nasty surprise: the lovely newline we added at the end of the file isn&apos;t there! What in the world is going on here?</p><p>Well, it turns out that one of the primary functions of a CDN (Content Distribution Network) like CloudFront is to cache responses so every request that hits an endpoint doesn&apos;t have to go all the way back to the origin (in this case, our S3 bucket) to serve the response. So we&apos;ve fallen prey to #2 in the list of the 4 hardest problems in Computer Science:</p><ol start="1"><li>Naming things</li><li>Caching things</li><li>Off by one errors</li></ol><p>What to do, what to do?</p><p>Luckily for us, CloudFront gives us a way to invalidate the cache so the first request for a given endpoint re-fetches from the origin. Even more luckily for us, the AWS CLI surfaces this:</p><pre><code class="language-text">: ~/code/orgtech; aws cloudfront create-invalidation help
CREATE-INVALIDATION()                                    CREATE-INVALIDATION()

NAME
       create-invalidation -

DESCRIPTION
       Create a new invalidation.

       See also: AWS API Documentation

SYNOPSIS
            create-invalidation
          --distribution-id &lt;value&gt;
          [--paths &lt;value&gt;]
[...]

OPTIONS
       --distribution-id (string)  The distribution&apos;s id.
       --paths  (string)           The space-separated  paths to be invalidated.
[...]
</code></pre><p>So what we can do is create an invalidation right after syncing to the S3 bucket in our <code>publish</code> function. In order to do this, we&apos;ll need a distribution ID. Let&apos;s ask CloudFront about the distributions we have:</p><pre><code class="language-text">: ~/code/orgtech; aws cloudfront list-distributions \
  | bb -i &apos;(let [ds (-&gt; (str/join &quot;\n&quot; *input*)
                    (json/parse-string true)
                    (get-in [:DistributionList :Items]))]
             (map (juxt #(get-in % [:Aliases :Items 0]) :Id) ds))&apos;
([&quot;www.jmglov.net&quot; &quot;F2ABC12UVWXYZ9&quot;]
 [&quot;politechspod.com&quot; &quot;F7E33IJKLMN0P6&quot;]
 [&quot;www.orgtech.se&quot; &quot;FDCBA42RSTUV3&quot;])
</code></pre><p>This looks like the one we&apos;re after:</p><pre><code class="language-text">[&quot;www.orgtech.se&quot; &quot;FDCBA42RSTUV3&quot;]
</code></pre><p>Let&apos;s go ahead and add the distribution ID to our <code>bb.edn</code>:</p><pre><code class="language-clojure">{ ; ...
 {:requires ([tasks])
  :init (def opts
          {:website-bucket &quot;orgtech.se&quot;
           :out-dir &quot;public&quot;
           :distribution-id &quot;FDCBA42RSTUV3&quot;})
  ;; ...
  }}
</code></pre><p>Now we can use this in <code>tasks.clj</code>:</p><pre><code class="language-clojure">(defn publish [default-opts]
  (let [{:keys [website-bucket out-dir distribution-id dryrun]
         :as opts} (merge default-opts
                          (cli/parse-opts *command-line-args*))
        sync-cmd (concat [&quot;aws s3 sync&quot;]
                         (when dryrun [&quot;--dryrun&quot;])
                         [(format &quot;%s/&quot; out-dir)
                          (format &quot;s3://%s/&quot; website-bucket)])
        invalidate-cmd [&quot;aws cloudfront create-invalidation&quot;
                        &quot;--distribution-id&quot; distribution-id
                        &quot;--paths&quot; :???]]
        ;; ...
      ))
</code></pre><p>OK, now where can we get our paths? Well, recall that <code>aws s3 sync --dryrun</code> helpfully outputs what is to be done:</p><pre><code class="language-text">aws s3 sync --dryrun public/ s3://orgtech.se/
(dryrun) upload: public/index.html to s3://orgtech.se/index.html
</code></pre><p>Let&apos;s consume this from Babashka to grab the paths! First, we&apos;ll dirty the dishes:</p><pre><code class="language-text">: orgtech-se; touch public/index.html public/css/main.css 

: orgtech-se; aws s3 sync --dryrun public/ s3://orgtech.se/
(dryrun) upload: public/css/main.css to s3://orgtech.se/css/main.css
(dryrun) upload: public/index.html to s3://orgtech.se/index.html
</code></pre><p>And then parse that output in our <code>tasks.clj</code>:</p><pre><code class="language-clojure">(ns tasks
  (:require ; ...
            [clojure.string :as str]))

(comment

  (def default-opts {:website-bucket &quot;orgtech.se&quot;
                     :out-dir &quot;public&quot;
                     :distribution-id &quot;FDCBA42RSTUV3&quot;})  ; C-c C-v f c e
  ;; =&gt; #&apos;tasks/default-opts

  (-&gt;&gt; (shell &quot;aws s3 sync --dryrun public/ s3://orgtech.se/&quot;)
       :out
       str/split-lines
       (map #(str/replace % #&quot;^[(]dryrun[)] upload: public(/\S+) to .+$&quot; &quot;$1&quot;)))
  ;; =&gt; (&quot;/css/main.css&quot; &quot;/index.html&quot;)

  )
</code></pre><p>Now that we know how to determine which files have changed, let&apos;s plug this into our <code>publish</code> function to add to the <code>aws cloudfront create-invalidation</code> command:</p><pre><code class="language-clojure">(defn publish [default-opts]
  (let [{:keys [website-bucket out-dir distribution-id dryrun]
         :as opts} (merge default-opts
                          (cli/parse-opts *command-line-args*))
        sync-cmd (concat [&quot;aws s3 sync&quot;]
                         (when dryrun [&quot;--dryrun&quot;])
                         [(format &quot;%s/&quot; out-dir)
                          (format &quot;s3://%s/&quot; website-bucket)])
        ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
        paths-re (re-pattern (format &quot;^[(]dryrun[)] upload: %s(/\\S+) to .+$&quot;
                                     out-dir))
        invalidate-cmd (concat [&quot;aws cloudfront create-invalidation&quot;
                                &quot;--distribution-id&quot; distribution-id
                                &quot;--paths&quot;]
                               (-&gt;&gt; (apply shell (concat sync-cmd [&quot;--dryrun&quot;]))
                                    :out
                                    str/split-lines
                                    (map #(str/replace % paths-re &quot;$1&quot;))))
        ;; 👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆
        ]
    (apply println sync-cmd)
    (apply shell sync-cmd)
    ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇
    (apply println invalidate-cmd)
    (when-not dryrun
      (apply shell invalidate-cmd))
    ;; 👆👆👆👆👆👆👆👆👆👆👆👆👆👆
    ))

(comment

  (publish (assoc default-opts :dryrun true)) ; C-c C-e

  )
</code></pre><p>Our REPL buffer duly notes:</p><pre><code class="language-text">aws s3 sync --dryrun public/ s3://orgtech.se/
(dryrun) upload: public/css/main.css to s3://orgtech.se/css/main.css
(dryrun) upload: public/index.html to s3://orgtech.se/index.html

aws cloudfront create-invalidation --distribution-id FDCBA42RSTUV3
                                   --paths /css/main.css /index.html
</code></pre><p>Looks good, so let&apos;s try it for realz:</p><pre><code class="language-text">: ~/code/orgtech; bb publish
aws s3 sync public/ s3://orgtech.se/
aws cloudfront create-invalidation --distribution-id FDCBA42RSTUV3
                                   --paths /css/main.css /index.html
{
    &quot;Location&quot;: &quot;https://cloudfront.amazonaws.com/2020-05-31/distribution/FDCBA42RSTUV3/invalidation/ICECSBHVIW089I89RLYODUBMXI&quot;,
    &quot;Invalidation&quot;: {
        &quot;Id&quot;: &quot;ICECSBHVIW089I89RLYODUBMXI&quot;,
        &quot;Status&quot;: &quot;InProgress&quot;,
        &quot;CreateTime&quot;: &quot;2024-08-25T07:14:55.130Z&quot;,
        &quot;InvalidationBatch&quot;: {
            &quot;Paths&quot;: {
                &quot;Quantity&quot;: 2,
                &quot;Items&quot;: [
                    &quot;/css/main.css&quot;,
                    &quot;/index.html&quot;
                ]
            },
            &quot;CallerReference&quot;: &quot;cli-1724570094-253923&quot;
        }
    }
}
</code></pre><p>This is promising. Let&apos;s refill our coffee and then check to see if the invalidation has finishing invalidating:</p><pre><code class="language-text">: ~/code/orgtech; aws cloudfront get-invalidation \
  --distribution-id FDCBA42RSTUV3 \
  --id ICECSBHVIW089I89RLYODUBMXI
{
    &quot;Invalidation&quot;: {
        &quot;Id&quot;: &quot;ICECSBHVIW089I89RLYODUBMXI&quot;,
        &quot;Status&quot;: &quot;Completed&quot;,
        &quot;CreateTime&quot;: &quot;2024-08-25T07:14:55.130Z&quot;,
        &quot;InvalidationBatch&quot;: {
            &quot;Paths&quot;: {
                &quot;Quantity&quot;: 2,
                &quot;Items&quot;: [
                    &quot;/css/main.css&quot;,
                    &quot;/index.html&quot;
                ]
            },
            &quot;CallerReference&quot;: &quot;cli-1724570094-253923&quot;
        }
    }
}
</code></pre><p>If we now Shift-reload the page in our browser, we&apos;ll see the wonderful new header! 🎉</p><div class="markdown-heading"><h2 id="transcription-made-easy">Transcription made easy</h2><a href="#transcription-made-easy" class="anchor" aria-label="Permalink: Transcription made easy"><img src="assets/link.svg" /></a></div><p>Now that we have an amazing website and a way to publish it, let&apos;s record an episode and then make a nice trailer to get people pumped up! We&apos;ll use <a href="https://zencastr.com/">Zencastr</a> to do this, which produces a lovely MP3 for us as well as a transcript. For now, we have the following files on disk:</p><pre><code class="language-text">: organising-tech-in-sweden; tree
.
├── bb.edn
├── ep00-trailer
│   ├── otis-ep00-trailer.mp3
│   └── otis-ep0-trailer_transcription.txt
├── ep01-klarna-part1
│   ├── otis-ep01-klarna-part1.mp3
│   └── otis-ep01-klarna-part1_transcription.txt
├── public
│   ├── ...
│   └── index.html
└── tasks.clj
</code></pre><p>Zencastr&apos;s transcripts are, um, functional, shall we say, but any machine transcription tool will require a human who speaks the actual language being transcribed (in this case, English) to clean things up. Luckily, there&apos;s an amazing free (as in source <strong>and</strong> as in beer!) browser-based tool called <a href="https://otranscribe.com/">oTranscribe</a> that lets us listen to our lovely audio whilst editing the transcript, with keyboard shortcuts for pausing and resuming playback, rewinding and fast forwarding, adjusting playback speed, etc.</p><p>To unlock all this goodness, we&apos;ll need to convert our boring Zencastr transcripts, which look like this:</p><pre><code class="language-text">00:02.00
jmglov
Already and we are live now. So welcome everyone to organizing tech in Sweden
I am here my name is Josh I&apos;m here with a ah. Cast of characters that will
delight in a maze and I will introduce them here in a minute but before we get
to the cool people. Let me introduce. My co-host Ray joining us all the way from
Belgium Ray you want to say hey.

00:30.61
Ray
Yeah on uncool Belgium hello everyone? Well it&apos;s a bit warmer than Sweden now.
But okay I yeah you were talking about being oh yeah, okay fine.

00:42.78
jmglov
Yeah, all right? So we are here like I said to talk about organizing tech in
Sweden and um, basically what we want to do is introduce. Folks who might not
know much about Sweden other than Ekea is from here and chocolate. Oh no wait.
That&apos;s Switzerland for some reason and the us. Oh you know Belgium sure sure.
Sure. Um.

[...]
</code></pre><p>into amazing OTR (oTranscribe&apos;s file format) ones, which look like some HTML stuffed into some JSON.</p><p>To do this converting, we could use <a href="https://github.com/jmglov/transcribble">Transcribble</a>, which I wrote a while back and forgot to blog about. Or we could just open up <a href="https://otranscribe.com/">https://otranscribe.com/</a> in our browser and click the big blue &quot;Start transcribing&quot; button, then click the &quot;Choose audio (or video) file&quot; button and choose our ~/code/orgtech-se/ep01-klarna-part1/otis-ep01-klarna-part1.mp3 file, and then paste in our Zencastr transcript, warts and all. If we click the Play button (or hit Esc, which is oTranscribe&apos;s play/pause keyboard shortcut), our episode will start playing, and we can hit Ctrl+J to add a timestamp to the transcript when we hear me say &quot;So, welcome everyone to Organising Tech in Sweden&quot;. After much listening and editing, which we will just handwave away here, we now have a pristine transcript!</p><p><img alt="The oTranscribe transcription UI" src="assets/2024-09-18-podcast-soundcljoud-otr.png" title="Cleaning this up is an exercise for the reader" class="border" /></p><p>We&apos;ll now click the &quot;Export&quot; button to pop up the &quot;Download transcript as...&quot; dialog, select &quot;oTranscribe format (.otr)&quot;, and save as a new file named ~/code/orgtech-se/ep01-klarna-part1/otis-ep01-klarna-part1.otr.</p><div class="markdown-heading"><h2 id="feed-me-some-episodes">Feed me some episodes</h2><a href="#feed-me-some-episodes" class="anchor" aria-label="Permalink: Feed me some episodes"><img src="assets/link.svg" /></a></div><p>Now that we have some files, we need to stuff those in a feed. Luckily, <a href="2024-07-09-soundcljoud.html#faking_a_podcast_with_selmer">we have
some experience with podcast
feeds</a>. Using <a href="https://github.com/yogthos/Selmer">Selmer</a> to write the feed worked out pretty nicely then, so let&apos;s elect to do the same thing again. In fact, since we already did the hard work of creating code that knows how to write an RSS file for a music album, why don&apos;t we see if we can modify it a bit to support podcasts as well?</p><p>Let&apos;s pop over to ~/code/soundcljoud/processor/main.clj and remind ourselves how we turned an album into an RSS feed:</p><pre><code class="language-clojure">(defn process-album [opts dir]
  (let [info (album-info opts dir)
        tmpdir (fs/create-temp-dir {:prefix &quot;soundcljoud.&quot;})
        info (update info :tracks (partial map #(process-track % tmpdir)))]
    (spit (fs/file tmpdir &quot;album.rss&quot;) (rss/album-feed opts info))
    (assoc info :out-dir tmpdir)))
</code></pre><p>In this case, we fetched Discogs metadata for the album in the <code>album-info</code> function, created a temporary directory, did some transcoding in <code>process-track</code>, then used <code>rss/album-feed</code> to apply a Selmer template to our album metadata. Opening up the <code>soundcljoud.rss</code> namespace, we see that the <code>album-feed</code> function is extremely specific to music albums:</p><pre><code class="language-clojure">(defn album-feed [opts album-info]
  (let [template (-&gt; (io/resource &quot;album-feed.rss&quot;) slurp)]
    (selmer/render template
                   (-&gt; album-info
                       (update :tracks
                               (partial map #(update % :mp3-filename
                                                     fs/file-name)))
                       (assoc :date (now))))))
</code></pre><p>Whilst there&apos;s no obvious way to repurpose it, we can follow the same basic pattern:</p><ol start="1"><li>Load the template</li><li>Massage the &quot;info&quot; about the <s>album</s> podcast as needed</li><li>Render the template with our &quot;info&quot;</li></ol><p>Let&apos;s sketch out a <code>podcast-feed</code> function:</p><pre><code class="language-clojure">(defn podcast-feed [opts podcast-info]  ;; ❓ podcast-info how?
  (let [template :???]  ;; ❓ where do we get this?
    (-&gt;&gt; podcast-info
         ;; ❓ maybe some massaging here?
         (selmer/render template))))
</code></pre><p>The first question is where we get the <code>podcast-info</code>. We got <code>album-info</code> from Discogs, but since Discogs presumably knows nothing about our podcast (and why would it?), let&apos;s create a static ~/code/orgtech/podcast.edn file instead, fill it with whatever data our podcast feed will need (I guess it&apos;s time to rhyme), and read in the EDN before calling this function.</p><p>Having made that decision, we must now ask ourselves where we will get our podcast feed template from. In the case of albums, we provided a template as a resource directly from Soundcljoud, so why don&apos;t we do that again?</p><pre><code class="language-clojure">(defn podcast-feed [opts podcast-info]
  (let [template (-&gt; (io/resource &quot;podcast-feed.rss&quot;) slurp)]
    (-&gt;&gt; podcast-info
         ;; ❓ maybe some massaging here?
         (selmer/render template))))
</code></pre><p>In order to know what if any massaging <code>podcast-info</code> will need, we&apos;ll need to create the template and the <code>podcast.edn</code> file and see where the gaps are. Let&apos;s consult Apple&apos;s handy <a href="https://help.apple.com/itc/podcasts_connect/#/itcb54353390">A Podcaster’s Guide to
RSS</a> and start writing <code>resources/podcast-feed.rss</code>. First, we need the standard feed skeleton:</p><pre><code class="language-xml">&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;
&lt;rss version=&quot;2.0&quot;
     xmlns:itunes=&quot;http://www.itunes.com/dtds/podcast-1.0.dtd&quot;
     xmlns:atom=&quot;http://www.w3.org/2005/Atom&quot;&gt;
  &lt;channel&gt;
    &lt;!-- TBD: some stuff here --&gt;
  &lt;/channel&gt;
&lt;/rss&gt;
</code></pre><p>Now to start populating the contents <code>&lt;channel&gt;</code> tag. According to Apple, we need the following:</p><table><thead><tr><th>Show tags</th><th>Usage</th><th>Parent tag</th></tr></thead><tbody><tr><td><code>&lt;title&gt;</code></td><td>The show title.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;description&gt;</code></td><td>The show description.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;itunes:image&gt;</code></td><td>The artwork for the show.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;language&gt;</code></td><td>The language spoken on the show.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;itunes:explicit&gt;</code></td><td>The podcast parental advisory information.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;itunes:category&gt;</code></td><td>The show category information.</td><td><code>&lt;channel&gt;</code></td></tr></tbody></table><p>This is straightforward enough (except for <code>&lt;itunes:category&gt;</code>, which we&apos;ll come back to):</p><pre><code class="language-xml">  &lt;channel&gt;
    &lt;title&gt;{{podcast.title}}&lt;/title&gt;
    &lt;description&gt;{{podcast.description|safe}}&lt;/description&gt;
    &lt;itunes:image href=&quot;{{base-url}}{{podcast.image}}&quot;/&gt;
    &lt;language&gt;{{podcast.language}}&lt;/language&gt;
    &lt;itunes:explicit&gt;{{podcast.explicit}}&lt;/itunes:explicit&gt;
  &lt;/channel&gt;
</code></pre><p>By the way, that <code>{{podcast.description|safe}}</code> thingy is a Selmer filter that <a href="https://github.com/yogthos/Selmer?tab=readme-ov-file#safe">exempts the variable from being
HTML-escaped</a>. Since our description text goes in the body of the <code>&lt;description&gt;</code> tag, we don&apos;t want things like &quot;rock &amp; roll&quot; getting rendered as &quot;rock &amp; roll&quot;, because that would be yucky.</p><p>Now we need to add that data to our <code>podcast.edn</code>:</p><pre><code class="language-clojure">{:base-url &quot;https://orgtech.se&quot;
 :podcast {:title &quot;Organising Tech in Sweden&quot;
           :description &quot;Organising Tech in Sweden is a limited podcast series exploring union organising in Swedish tech companies. Join us as we sit down with some of the people involved in the campaigns to win collective bargaining rights at two of Sweden&apos;s tech unicorns, Klarna and Spotify.&quot;
           :image &quot;/img/orgtech-se-cover.jpg&quot;
           :language &quot;en&quot;
           :explicit true}}
</code></pre><p>As we were writing <code>podcast.edn</code>, we realised that <code>podcast-info</code> was actually the data in the EDN file under the <code>:podcast</code> key, so we are really just providing an <code>opts</code>:</p><pre><code class="language-clojure">(defn podcast-feed [opts]
  (let [template (-&gt; (io/resource &quot;podcast-feed.rss&quot;) slurp)]
    (-&gt;&gt; opts
         ;; ❓ maybe some massaging here?
         (selmer/render template))))
</code></pre><p>Let&apos;s give this a go in our REPL:</p><pre><code class="language-clojure">(comment

  (require &apos;[clojure.edn :as edn])
  ;; =&gt; nil

  (def opts (-&gt; (slurp &quot;/home/jmglov/code/orgtech-se/podcast.edn&quot;)
                (edn/read-string)))
  ;; =&gt; #&apos;soundcljoud.rss/opts

  opts
  ;; =&gt; {:base-url &quot;https://orgtech.se&quot;,
  ;;     :podcast
  ;;     {:title &quot;Organising Tech in Sweden&quot;,
  ;;      :description
  ;;      &quot;Organising Tech in Sweden is a...&quot;,
  ;;      :image &quot;/img/orgtech-se-cover.jpg&quot;,
  ;;      :language &quot;en&quot;,
  ;;      :explicit true}}

  (podcast-feed opts)
  ;; =&gt; &quot;&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;
  ;;     &lt;rss version=\&quot;2.0\&quot;
  ;;          xmlns:itunes=\&quot;http://www.itunes.com/dtds/podcast-1.0.dtd\&quot;
  ;;          xmlns:atom=\&quot;http://www.w3.org/2005/Atom\&quot;&gt;
  ;;       &lt;channel&gt;
  ;;         &lt;title&gt;Organising Tech in Sweden&lt;/title&gt;
  ;;         &lt;description&gt;Organising Tech in Sweden is a...&lt;/description&gt;
  ;;         &lt;itunes:image href=\&quot;https://orgtech.se/img/orgtech-se-cover.jpg\&quot;/&gt;
  ;;         &lt;language&gt;en&lt;/language&gt;
  ;;         &lt;itunes:explicit&gt;true&lt;/itunes:explicit&gt;
  ;;       &lt;/channel&gt;
  ;;     &lt;/rss&gt;&quot;

  )
</code></pre><p>Let&apos;s now come back to that tricky <a href="itunes:category">itunes:category</a> tag. Referring back to the Apple docs, we see:</p><blockquote><p>For a complete list of categories and subcategories, see Apple Podcast categories.</p><p>Select the category that best reflects the content of your show. If available, you can also define a subcategory.</p><p>Single category:</p><p>&lt;itunes:category text=&quot;History&quot; /&gt;</p><p>Category with subcategory:</p><p>&lt;itunes:category text=&quot;Society &amp; Culture&quot;&gt; &lt;itunes:category text=&quot;Documentary&quot; /&gt; &lt;/itunes:category&gt;</p></blockquote><p>We can add categories to our <code>podcast-feed.rss</code> template using Selmer&apos;s <a href="https://github.com/yogthos/Selmer?tab=readme-ov-file#for">for</a> tag:</p><pre><code class="language-xml">  &lt;channel&gt;
    &lt;!-- ... --&gt;
{% for category in podcast.categories %}
    &lt;itunes:category text=&quot;{{category.text}}&quot;&gt;
{% for subcategory in category.subcategories %}
      &lt;itunes:category text=&quot;{{subcategory.text}}&quot; /&gt;
{% endfor %}
    &lt;/itunes:category&gt;
{% endfor %}
  &lt;/channel&gt;
</code></pre><p>And now we need to pick a category or two and add them to our <code>podcast.edn</code>. The <a href="https://podcasters.apple.com/support/1691-apple-podcasts-categories">Apple Podcasts
categories</a> page lists the options, of which we choose:</p><ul><li>Technology (which has no subcategories)</li><li>News, with subcategory Politics</li></ul><p>Expressing this in EDN, we get:</p><pre><code class="language-clojure">{:base-url &quot;https://orgtech.se&quot;
 :podcast { ; ...
           :categories [{:text &quot;Technology&quot;}
                        {:text &quot;News&quot;
                         :subcategories [{:text &quot;Politics&quot;}]}]}}
</code></pre><p>And our REPL shows us what we&apos;d expect to see:</p><pre><code class="language-clojure">(comment

  (def opts (-&gt; (slurp &quot;/home/jmglov/code/orgtech-se/podcast.edn&quot;)
                (edn/read-string)))
  ;; =&gt; #&apos;soundcljoud.rss/opts

  (podcast-feed opts)
  ;; =&gt; &quot;&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;
  ;;     &lt;rss version=\&quot;2.0\&quot;
  ;;          xmlns:itunes=\&quot;http://www.itunes.com/dtds/podcast-1.0.dtd\&quot;
  ;;          xmlns:atom=\&quot;http://www.w3.org/2005/Atom\&quot;&gt;
  ;;       &lt;channel&gt;
  ;;         ...
  ;;         &lt;itunes:category text=\&quot;Technology\&quot;&gt;
  ;;         &lt;/itunes:category&gt;
  ;;         &lt;itunes:category text=\&quot;News\&quot;&gt;
  ;;           &lt;itunes:category text=\&quot;Politics\&quot; /&gt;
  ;;         &lt;/itunes:category&gt;
  ;;       &lt;/channel&gt;
  ;;     &lt;/rss&gt;&quot;

  )
</code></pre><p>Having sorted our required tags, let&apos;s take a look at Apple&apos;s recommended and &quot;situational&quot; tags (which we&apos;ll just treat as &quot;recommended&quot;):</p><table><thead><tr><th>Show tags</th><th>Usage</th><th>Parent tag</th></tr></thead><tbody><tr><td><code>&lt;itunes:author&gt;</code></td><td>The group responsible for creating the show.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;link&gt;</code></td><td>The website associated with a podcast.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;itunes:title&gt;</code></td><td>The show title specific for Apple Podcasts.</td><td><code>&lt;channel&gt;</code></td></tr><tr><td><code>&lt;itunes:type&gt;</code></td><td>The type of show. Its values can be one of the following:</td><td></td></tr><tr><td></td><td>• <strong>Episodic</strong>. Episodes are intended to be consumed without any specific order.</td><td></td></tr><tr><td></td><td>• <strong>Serial</strong>. Episodes are intended to be consumed in sequential order.</td><td></td></tr><tr><td><code>&lt;copyright&gt;</code></td><td>The show copyright details.</td><td><code>&lt;channel&gt;</code></td></tr></tbody></table><p>Again, this is quite straightforward to add to our template:</p><pre><code class="language-xml">  &lt;channel&gt;
    &lt;!-- ... --&gt;
    &lt;itunes:author&gt;{{podcast.author}}&lt;/itunes:author&gt;
    &lt;link&gt;{{base-url}}&lt;/link&gt;
    &lt;itunes:title&gt;{{podcast.title}}&lt;/itunes:title&gt;
    &lt;itunes:type&gt;{{podcast.type}}&lt;/itunes:type&gt;
    &lt;copyright&gt;{{podcast.copyright}}&lt;/copyright&gt;
  &lt;/channel&gt;
</code></pre><p>and to our <code>podcast.edn</code>:</p><pre><code class="language-clojure">{:base-url &quot;https://orgtech.se&quot;
 :podcast { ; ...
           :author &quot;Organising Tech in Sweden&quot;
           :type &quot;Serial&quot;
           :copyright &quot;All rights reserved, Organising Tech in Sweden&quot;}}
</code></pre><p>Testing things out in our REPL, we see what we expect to see. 🙂</p><p>Now it&apos;s time to add some episodes! Here are the Apple Podcast required, recommended, and situational tags for episodes:</p><table><thead><tr><th>Show tags</th><th>Usage</th><th>Parent tag</th></tr></thead><tbody><tr><td><code>&lt;title&gt;</code></td><td>An episode title.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;enclosure&gt;</code></td><td>The episode content, file size, and file type information. The <code>&lt;enclosure&gt;</code> tag has three attributes:</td><td><code>&lt;item&gt;</code></td></tr><tr><td></td><td>• <strong>URL</strong>. The URL attribute points to your podcast media file.</td><td></td></tr><tr><td></td><td>• <strong>Length</strong>. The length attribute is the file size in bytes.</td><td></td></tr><tr><td></td><td>• <strong>Type</strong>. The type attribute provides the correct category for the type of file.</td><td></td></tr><tr><td><code>&lt;guid&gt;</code></td><td>The episode’s globally unique identifier (<a href="https://cyber.harvard.edu/rss/rss.html#ltguidgtSubelementOfLtitemgt">GUID</a>)</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;pubDate&gt;</code></td><td>The date and time when an episode was released. Format the date using the <a href="http://www.faqs.org/rfcs/rfc2822.html">RFC 2822</a> specifications. For example: <code>Sat, 01 Apr 2023 19:00:00 GMT</code>.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;description&gt;</code></td><td>An episode description.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;itunes:duration&gt;</code></td><td>The duration of an episode. Different duration formats are accepted however it is recommended to convert the length of the episode into seconds.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;link&gt;</code></td><td>An episode link URL.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;itunes:explicit&gt;</code></td><td>The podcast parental advisory information.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;itunes:title&gt;</code></td><td>The show title specific for Apple Podcasts.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;itunes:episode&gt;</code></td><td>An episode number.</td><td><code>&lt;item&gt;</code></td></tr><tr><td><code>&lt;itunes:episodeType&gt;</code></td><td>The episode type.</td><td><code>&lt;item&gt;</code></td></tr><tr><td></td><td>• <strong>Full</strong>. Specify full when you are submitting the complete content of your show.</td><td></td></tr><tr><td></td><td>• <strong>Trailer</strong>. Specify trailer when you are submitting a short, promotional piece of content that represents a preview of your current show.</td><td></td></tr><tr><td></td><td>• <strong>Bonus</strong>. Specify bonus when you are submitting extra content for your show (for example, behind the scenes information or interviews with the cast) or cross-promotional content for another show.</td><td></td></tr><tr><td><code>&lt;itunes:transcript&gt;</code></td><td>A link to the episode transcript in the Closed Caption format.</td><td><code>&lt;item&gt;</code></td></tr></tbody></table><p>Unfortunately, Transcribble doesn&apos;t yet support VTT or SRT transcripts, so we can&apos;t provide the transcript directly in iTunes. What we will do instead is display the OTR transcript that we previously prepared in oTranscribe on our episode page (which is yet to be written, but we&apos;ll get there in the end). In order to do this, let&apos;s add a custom <code>&lt;transcriptUrl&gt;</code> tag.</p><p>Let&apos;s start with our template as usual:</p><pre><code class="language-xml">  &lt;channel&gt;
    &lt;!-- ... --&gt;
{% for episode in episodes %}
    &lt;item&gt;
      &lt;title&gt;{{episode.title}}&lt;/title&gt;
      &lt;enclosure
          url=&quot;{{base-url}}{{episode.path}}/{{episode.audio-file}}&quot;
          length=&quot;{{episode.audio-filesize}}&quot;
          type=&quot;{{episode.mime-type}}&quot; /&gt;
      &lt;guid&gt;{{base-url}}{{episode.path}}/{{episode.audio-file}}&lt;/guid&gt;
      &lt;pubDate&gt;{{episode.date}}&lt;/pubDate&gt;
      &lt;description&gt;&lt;![CDATA[{{episode.description|safe}}]]&gt;&lt;/description&gt;
      &lt;itunes:duration&gt;{{episode.duration}}&lt;/itunes:duration&gt;
      &lt;link&gt;{{base-url}}{{episode.path}}&lt;/link&gt;
      &lt;itunes:title&gt;{{episode.title}}&lt;/itunes:title&gt;
      {% if episode.number %}&lt;itunes:episode&gt;{{episode.number}}&lt;/itunes:episode&gt;{% endif %}
      &lt;itunes:episodeType&gt;{{episode.type}}&lt;/itunes:episodeType&gt;
      &lt;transcriptUrl&gt;{{base-url}}{{episode.path}}/{{episode.transcript-file}}&lt;/transcriptUrl&gt;
    &lt;/item&gt;
{% endfor %}
  &lt;/channel&gt;
</code></pre><p>And now we know what episodes need to look like in our <code>podcast.edn</code> file:</p><pre><code class="language-clojure">{ ; ...
 :episodes
 [{:number 0
   :date &quot;Thu, 5 Sep 2024 00:00:00 +0000&quot;
   :type &quot;Trailer&quot;
   :title &quot;Trailer&quot;
   :summary &quot;Union organising seems to be in the air these days, as tech workers wake up and realise that they are, in fact, workers.&quot;
   :description &quot;
&lt;p&gt;
  Union organising seems to be in the air these days, as tech workers wake up and
  realise that they are, in fact, workers. Here in Sweden, it&apos;s no exception.
  Join us as we sit down with some of the people involved in organising two of
  Sweden&apos;s foremost tech unicorns, Klarna and Spotify. This is Organising Tech in
  Sweden.
&lt;/p&gt;
&lt;p class=\&quot;soundcljoud-hidden\&quot;&gt;
  To view full show notes, including transcripts, please visit the
  &lt;a href=\&quot;{{base-url}}{{episode.path}}/\&quot;&gt;episode page&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
  Cover art by &lt;a href=\&quot;https://anyakjordan.com/\&quot;&gt;Anya K. Jordan&lt;/a&gt;
  &lt;a href=\&quot;https://bsky.app/profile/anyakjordan.bsky.social\&quot;&gt;@anyakjordan.bsky.social&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
  Theme music by &lt;a href=\&quot;https://soundcloud.com/ptzery\&quot;&gt;Ptzery&lt;/a&gt;
&lt;/p&gt;&quot;
   :path &quot;/episodes/ep00-trailer&quot;
   :audio-file &quot;otis-ep00-trailer.mp3&quot;
   :transcript-file &quot;otis-ep00-trailer.otr&quot;
   :explicit false
   :mime-type &quot;audio/mpeg&quot;}
  {:number 1
   :date &quot;Thu, 12 Sep 2024 00:00:00 +0000&quot;
   :type &quot;Full&quot;
   :title &quot;Organising Klarna - Part 1&quot;
   :summary &quot;A conversation with three of the organisers behind the successful campaign to win a Collective Bargaining Agreement at Klarna&quot;
   :description &quot;
&lt;p&gt;
  We kick off Organising Tech in Sweden in style by recounting the story of how
  a collective bargaining agreement (CBA) was won at Klarna, a major Swedish
  fintech. In fact, Klarna was the first unicorn in Sweden to be unionised (and
  probably the first unicorn in Europe as well)!
&lt;/p&gt;
&lt;p&gt;
  To hear all about how this went down, your co-hosts Josh and Ray are joined by
  Thomas, the founder of the Klarna Unionen Club (a union \&quot;local\&quot;, to use
  terminology that might be more familiar to US listeners); Sen, the chair of
  the club who won the bargaining agreement against the odds; and Kim, a former
  Klarna employee with extensive knowledge of Swedish labour law and market
  policy.
&lt;/p&gt;
&lt;p&gt;
  This is part 1 of the conversation, which will be concluded in Episode 2.
&lt;/p&gt;
&lt;p class=\&quot;soundcljoud-hidden\&quot;&gt;
  To view full show notes, including transcripts, please visit the
  &lt;a href=\&quot;{{base-url}}{{episode.path}}/\&quot;&gt;episode page&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
  Cover art by &lt;a href=\&quot;https://anyakjordan.com/\&quot;&gt;Anya K. Jordan&lt;/a&gt;
  &lt;a href=\&quot;https://bsky.app/profile/anyakjordan.bsky.social\&quot;&gt;@anyakjordan.bsky.social&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
  Theme music by &lt;a href=\&quot;https://soundcloud.com/ptzery\&quot;&gt;Ptzery&lt;/a&gt;
&lt;/p&gt;&quot;
   :path &quot;/episodes/ep01-klarna-part1&quot;
   :audio-file &quot;otis-ep01-klarna-part1.mp3&quot;
   :transcript-file &quot;otis-ep01-klarna-part1.otr&quot;
   :explicit false
   :mime-type &quot;audio/mpeg&quot;}
  {:preview? true
   :number 2
   :date &quot;Thu, 19 Sep 2024 00:00:00 +0000&quot;
   :type &quot;Full&quot;
   :title &quot;Organising Klarna - Part 2&quot;
   :summary &quot;The conclusion of our conversation with three of the organisers behind the successful campaign to win a Collective Bargaining Agreement at Klarna&quot;
   :description &quot;
&lt;p&gt;
  We finish our conversation with Sen, Thomas, and Kim about how a collective
  bargaining agreement (CBA) was won at Klarna. In this episode, we cover the
  impact of immigrant workers on organising, the impact of organising on
  organisers, and the impact of strikes on negotiations. All of this and a happy
  ending too!
&lt;/p&gt;
&lt;p class=\&quot;soundcljoud-hidden\&quot;&gt;
  To view full show notes, including transcripts, please visit the
  &lt;a href=\&quot;{{base-url}}{{episode.path}}/\&quot;&gt;episode page&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
  Cover art by &lt;a href=\&quot;https://anyakjordan.com/\&quot;&gt;Anya K. Jordan&lt;/a&gt;
  &lt;a href=\&quot;https://bsky.app/profile/anyakjordan.bsky.social\&quot;&gt;@anyakjordan.bsky.social&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
  Theme music by &lt;a href=\&quot;https://soundcloud.com/ptzery\&quot;&gt;Ptzery&lt;/a&gt;
&lt;/p&gt;&quot;
   :path &quot;/episodes/ep02-klarna-part2&quot;
   :audio-file &quot;otis-ep02-klarna-part2.mp3&quot;
   :transcript-file &quot;otis-ep02-klarna-part2.otr&quot;
   :explicit false
   :mime-type &quot;audio/mpeg&quot;}]}
</code></pre><p>Testing this in our REPL...</p><pre><code class="language-clojure">(comment

  (def opts (-&gt; (slurp &quot;/home/jmglov/code/orgtech-se/podcast.edn&quot;)
                (edn/read-string)))
  ;; =&gt; #&apos;soundcljoud.rss/opts

  (podcast-feed opts)
  ;; =&gt; java.lang.NullPointerException soundcljoud.rss /home/jmglov/code/soundcljoud/processor/src/soundcljoud/rss.clj:34:26

  )
</code></pre><p>...we get an unpleasant surprise. 😮</p><p>This is a bit annoying to debug, but we can surmise that one of the template variables in the episode template must be missing. Doing a little visual inspection identifies the culprit:</p><pre><code class="language-xml">      &lt;enclosure
          url=&quot;{{base-url}}{{episode.path}}/{{episode.audio-file}}&quot;
          length=&quot;{{episode.audio-filesize}}&quot;
          type=&quot;{{episode.mime-type}}&quot; /&gt;
</code></pre><p>We don&apos;t have <code>audio-filesize</code> in our episode data structure. 😢</p><div class="markdown-heading"><h2 id="deep-tissue-massage">Deep tissue massage</h2><a href="#deep-tissue-massage" class="anchor" aria-label="Permalink: Deep tissue massage"><img src="assets/link.svg" /></a></div><p>All is not lost, however. Let&apos;s cast our minds back to the definition of the <code>podcast-feed</code> function:</p><pre><code class="language-clojure">(defn podcast-feed [opts]
  (let [template (-&gt; (io/resource &quot;podcast-feed.rss&quot;) slurp)]
    (-&gt;&gt; opts
         ;; ❓ maybe some massaging here?
         (selmer/render template))))
</code></pre><p>The answer to the question &quot;maybe some massaging here?&quot; now reveals itself to be &quot;Yes. Yes! A thousand times yes!&quot; We also know at least one massage technique we&apos;re going to need to use, namely setting the <code>audio-filesize</code> key for each episode. Let&apos;s start out by giving ourselves a way to update episodes:</p><pre><code class="language-clojure">(defn update-episode [opts episode]
  episode)

(defn update-episodes [opts]
  (update opts :episodes #(map (partial update-episode opts) %)))

(defn podcast-feed [opts]
  (let [template (-&gt; (io/resource &quot;podcast-feed.rss&quot;) slurp)]
    (-&gt;&gt; opts
         update-episodes
         (selmer/render template))))
</code></pre><p>Now we can figure out how to add the filesize to each episode. As usual, Babashka&apos;s got us covered! Checking out the babashka.fs API documentation, we find a function called <a href="https://github.com/babashka/fs/blob/master/API.md#babashka.fs/size">babashka.fs/size</a>:</p><blockquote><p><strong>size</strong></p><p><code>(size f)</code></p><p>Returns the size of a file (in bytes).</p></blockquote><p>Let&apos;s mess around a bit in the REPL:</p><pre><code class="language-clojure">(comment

  (def base-dir &quot;/home/jmglov/code/orgtech-se&quot;)
  ;; =&gt; #&apos;soundcljoud.rss/base-dir

  (def opts (-&gt; (slurp (fs/file base-dir &quot;podcast.edn&quot;))
                (edn/read-string)
                (assoc :base-dir base-dir)))

  (let [episode (-&gt; opts :episodes first)
        filename (format &quot;%s%s/%s&quot;
                         base-dir (:path episode) (:audio-file episode))]
    (fs/size filename))
  ;; =&gt; java.nio.file.NoSuchFileException: 
  ;; /home/jmglov/code/orgtech-se/episodes/ep00-trailer/otis-ep00-trailer.mp3 
  ;; /home/jmglov/code/soundcljoud/processor/src/soundcljoud/rss.clj:4:5

  )
</code></pre><p>Oops! Seems like we&apos;ve traded one problem for another. 😬</p><p>On disk, the files are laid out like this:</p><pre><code class="language-text">: organising-tech-in-sweden; tree
.
├── bb.edn
├── ep00-trailer
│   ├── otis-ep00-trailer.mp3
│   └── otis-ep0-trailer_transcription.txt
├── ep01-klarna-part1
│   ├── otis-ep01-klarna-part1.mp3
│   └── otis-ep01-klarna-part1_transcription.txt
├── ep02-klarna-part2
│   ├── otis-ep02-klarna-part2.mp3
│   └── otis-ep02-klarna-part2_transcription.txt
├── public
│   ├── ...
│   └── index.html
└── tasks.clj
</code></pre><p>But we are looking for the audio file in the path in which it should exist on the server, which makes sense from an RSS feed perspective, which should use paths corresponding to the published site. Our <code>publish</code> task uses <code>aws s3 sync</code> to publish everything in our <code>public/</code> directory, so if we drop the MP3s there, they will get put in the correct place on the S3 website. For now, let&apos;s cheat by using our REPL to put the files where they need to go:</p><pre><code class="language-clojure">(comment

  (def opts (-&gt; (slurp (fs/file base-dir &quot;podcast.edn&quot;))
                (edn/read-string)
                (assoc :base-dir base-dir
                       :out-dir &quot;public&quot;)))
  ;; =&gt; #&apos;soundcljoud.rss/opts

  (doseq [episode (:episodes opts)
          :let [filename (format &quot;%s/%s%s/%s&quot;
                                 (:base-dir opts) (:out-dir opts)
                                 (:path episode) (:audio-file episode))
                src-filename (fs/file dir
                                      (fs/file-name (:path episode))
                                      (:audio-file episode))]]
    (when-not (fs/exists? filename)
      (fs/create-dirs (fs/parent filename))
      (fs/copy src-filename filename)))
  ;; =&gt; nil

  )
</code></pre><p>OK, this will do for now. Let&apos;s grab this code, clean it up a bit, and shove it into our <code>update-episode</code> function:</p><pre><code class="language-clojure">(defn update-episode [{:keys [base-dir out-dir] :as opts}
                      {:keys [audio-file path] :as episode}]
  (assoc episode :audio-filesize
         (fs/size (format &quot;%s/%s%s/%s&quot; base-dir out-dir path audio-file))))
</code></pre><p>Before testing this out in the REPL, we should add the <code>:out-dir</code> key to our <code>podcast.edn</code> so we don&apos;t rely on the caller to add it to <code>opts</code>:</p><pre><code class="language-clojure">{:base-url &quot;https://orgtech.se&quot;
 :podcast { ... }
 :episodes [ ... ]}
</code></pre><p>OK, now we&apos;re ready to give it a spin in the REPL:</p><pre><code class="language-clojure">(comment

  (podcast-feed (assoc opts :out-dir &quot;public&quot;))
  ;; =&gt; &quot;&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;\n
  ;;     &lt;rss version=\&quot;2.0\&quot;\n
  ;;          xmlns:itunes=\&quot;http://www.itunes.com/dtds/podcast-1.0.dtd\&quot;\n
  ;;          xmlns:atom=\&quot;http://www.w3.org/2005/Atom\&quot;&gt;\n
  ;;       &lt;channel&gt;\n
  ;;         &lt;title&gt;Organising Tech in Sweden&lt;/title&gt;\n
  ;;         &lt;description&gt;Organising Tech in Sweden is a...&lt;/description&gt;\n
  ;;         &lt;itunes:image href=\&quot;https://orgtech.se/img/orgtech-se-cover.jpg\&quot;/&gt;\n
  ;;         &lt;language&gt;en&lt;/language&gt;\n
  ;;         &lt;itunes:explicit&gt;true&lt;/itunes:explicit&gt;\n\n
  ;;         &lt;itunes:category text=\&quot;Technology\&quot;&gt;\n\n
  ;;         &lt;/itunes:category&gt;\n\n
  ;;         &lt;itunes:category text=\&quot;News\&quot;&gt;\n\n
  ;;           &lt;itunes:category text=\&quot;Politics\&quot; /&gt;\n\n
  ;;         &lt;/itunes:category&gt;\n\n
  ;;         &lt;itunes:author&gt;Organising Tech in Sweden&lt;/itunes:author&gt;\n
  ;;         &lt;link&gt;https://orgtech.se&lt;/link&gt;\n
  ;;         &lt;itunes:title&gt;Organising Tech in Sweden&lt;/itunes:title&gt;\n
  ;;         &lt;itunes:type&gt;Serial&lt;/itunes:type&gt;\n
  ;;         &lt;copyright&gt;All rights reserved&lt;/copyright&gt;\n\n
  ;;         &lt;item&gt;\n
  ;;           &lt;title&gt;Trailer&lt;/title&gt;\n
  ;;           &lt;enclosure\n
  ;;               url=\&quot;https://orgtech.se/episodes/ep00-trailer/otis-ep00-trailer.mp3\&quot;\n
  ;;               length=\&quot;1016937\&quot;\n
  ;;               type=\&quot;audio/mpeg\&quot; /&gt;\n
  ;;           &lt;guid&gt;https://orgtech.se/episodes/ep00-trailer/otis-ep00-trailer.mp3&lt;/guid&gt;\n
  ;;           &lt;pubDate&gt;Thu, 5 Sep 2024 00:00:00 +0000&lt;/pubDate&gt;\n
  ;;           &lt;description&gt;&lt;![CDATA[\n
  ;;             &lt;p&gt;\n  Union organising seems to be in the air these days...&lt;/p&gt;\n
  ;;             &lt;p class=\&quot;soundcljoud-hidden\&quot;&gt;\n
  ;;               To view full show notes, including transcripts, please visit the\n
  ;;               &lt;a href=\&quot;{{base-url}}{{episode.path}}/\&quot;&gt;episode page&lt;/a&gt;.\n
  ;;             &lt;/p&gt;\n
  ;;             &lt;p&gt;\n
  ;;               Cover art by &lt;a href=\&quot;https://anyakjordan.com/\&quot;&gt;Anya K. Jordan&lt;/a&gt;\n
  ;;             &lt;/p&gt;\n
  ;;             &lt;p&gt;\n
  ;;               Theme music by &lt;a href=\&quot;https://soundcloud.com/ptzery\&quot;&gt;Ptzery&lt;/a&gt;\n&lt;/p&gt;
  ;;           ]]&gt;&lt;/description&gt;\n
  ;;           &lt;itunes:duration&gt;&lt;/itunes:duration&gt;\n
  ;;           &lt;link&gt;https://orgtech.se/episodes/ep00-trailer&lt;/link&gt;\n
  ;;           &lt;itunes:title&gt;Trailer&lt;/itunes:title&gt;\n
  ;;           &lt;itunes:episode&gt;0&lt;/itunes:episode&gt;\n
  ;;           &lt;itunes:episodeType&gt;Trailer&lt;/itunes:episodeType&gt;\n
  ;;           &lt;transcriptUrl&gt;
  ;;             https://orgtech.se/episodes/ep00-trailer/otis-ep00-trailer.otr
  ;;           &lt;/transcriptUrl&gt;\n
  ;;         &lt;/item&gt;\n\n
  ;;         ...
  ;;       &lt;/channel&gt;\n
  ;;     &lt;/rss&gt;\n&quot;

  )
</code></pre><p>This looks like a good start, but a few things jump out at us:</p><ol start="1"><li>Our <code>&lt;itunes:duration&gt;</code> tag is empty</li><li>We still have a few Selmer template variables in our output, for example:<pre><code class="language-html">&lt;a href=\&quot;{{base-url}}{{episode.path}}/\&quot;&gt;episode page&lt;/a&gt;
</code></pre></li></ol><p>Let&apos;s tackle the duration issue first, because we already have the tools to fix that in the soundcljoud.processor code that we wrote for Garth:</p><pre><code class="language-clojure">(ns soundcljoud.audio
  (:require [babashka.fs :as fs]
            [babashka.process :as p]
            [cheshire.core :as json]
            [clojure.string :as str]))

(defn mp3-duration [filename]
  (-&gt; (p/shell {:out :string}
               &quot;ffprobe -v quiet -print_format json -show_format -show_streams&quot;
               filename)
      :out
      (json/parse-string keyword)
      :streams
      first
      :duration
      (str/replace #&quot;[.]\d+$&quot; &quot;&quot;)))

;; ...
</code></pre><p>Let&apos;s pull soundcljoud.audio into our namespace and then grab the duration in <code>update-episode</code>:</p><pre><code class="language-clojure">(ns soundcljoud.rss
  (:require ; ...
            [soundcljoud.audio :as audio])
  (:import ...))

;; ...

(defn update-episode [{:keys [base-dir src-dir] :as opts}
                      {:keys [audio-file path] :as episode}]
  (let [filename (format &quot;%s/%s%s/%s&quot; base-dir src-dir path audio-file)]
    (assoc episode
           :audio-filesize (fs/size filename)
           :duration (audio/mp3-duration filename))))

;; ...

(comment

  (podcast-feed opts)
  ;; =&gt; &quot;&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;\n
  ;;     &lt;rss version=\&quot;2.0\&quot; ...&gt;\n
  ;;       &lt;channel&gt;\n
  ;;         &lt;title&gt;Organising Tech in Sweden&lt;/title&gt;\n
  ;;         &lt;description&gt;Organising Tech in Sweden is a...&lt;/description&gt;\n
  ;;         ...
  ;;         &lt;item&gt;\n
  ;;           &lt;title&gt;Trailer&lt;/title&gt;\n
  ;;           ...
  ;;           &lt;itunes:duration&gt;42&lt;/itunes:duration&gt;\n
  ;;           ...
  ;;         &lt;/item&gt;\n\n
  ;;         ...
  ;;       &lt;/channel&gt;\n
  ;;     &lt;/rss&gt;\n&quot;

)
</code></pre><p>This looks good, so let&apos;s turn our roving eye to the last remaining problem.</p><div class="markdown-heading"><h2 id="it&apos;s-templates-all-the-way-down,-young-man">It&apos;s templates all the way down, young man</h2><a href="#it&apos;s-templates-all-the-way-down,-young-man" class="anchor" aria-label="Permalink: It&apos;s templates all the way down, young man"><img src="assets/link.svg" /></a></div><p>After rendering our RSS feed template, we somehow still have unrendered Selmer in our output:</p><pre><code class="language-xml">&lt;description&gt;
  &lt;![CDATA[
  &lt;p&gt;
    Union organising seems to be in the air these days...
  &lt;/p&gt;
  &lt;p class=&quot;soundcljoud-hidden&quot;&gt;
    To view full show notes, including transcripts, please visit the
    &lt;a href=&quot;{{base-url}}{{episode.path}}/&quot;&gt;episode page&lt;/a&gt;.
  &lt;/p&gt;
  &lt;p&gt;
    Cover art by &lt;a href=&quot;https://anyakjordan.com/&quot;&gt;Anya K. Jordan&lt;/a&gt;
  &lt;/p&gt;
  &lt;p&gt;
    Theme music by &lt;a href=&quot;https://soundcloud.com/ptzery&quot;&gt;Ptzery&lt;/a&gt;
  &lt;/p&gt;]]&gt;
&lt;/description&gt;
</code></pre><p>Let&apos;s see what&apos;s going on in our <code>podcast-feed.rss</code> template for episodes:</p><pre><code class="language-xml">{% for episode in episodes %}
    &lt;item&gt;
      &lt;title&gt;{{episode.title}}&lt;/title&gt;
      ...
      &lt;description&gt;&lt;![CDATA[{{episode.description|safe}}]]&gt;&lt;/description&gt;
      ...
    &lt;/item&gt;
{% endfor %}
</code></pre><p>So we&apos;re plugging <code>episode.description</code> into the template. Let&apos;s see what that looks like in our <code>podcast.edn</code>:</p><pre><code class="language-clojure">{ ; ...
 :episodes
 [{:number 0
   :title &quot;Trailer&quot;
   ;; ...
   :description &quot;
&lt;p&gt;
  Union organising seems to be in the air these days, as tech workers wake up and
  realise that they are, in fact, workers. Here in Sweden, it&apos;s no exception.
  Join us as we sit down with some of the people involved in organising two of
  Sweden&apos;s foremost tech unicorns, Klarna and Spotify. This is Organising Tech in
  Sweden.
&lt;/p&gt;
&lt;p class=\&quot;soundcljoud-hidden\&quot;&gt;
  To view full show notes, including transcripts, please visit the
  &lt;a href=\&quot;{{base-url}}{{episode.path}}/\&quot;&gt;episode page&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
  Cover art by &lt;a href=\&quot;https://anyakjordan.com/\&quot;&gt;Anya K. Jordan&lt;/a&gt;
  &lt;a href=\&quot;https://bsky.app/profile/anyakjordan.bsky.social\&quot;&gt;@anyakjordan.bsky.social&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
  Theme music by &lt;a href=\&quot;https://soundcloud.com/ptzery\&quot;&gt;Ptzery&lt;/a&gt;
&lt;/p&gt;&quot;
   ;; ...
   }
  ;; ...
]}
</code></pre><p>Ah-ha! The value of <code>episode.description</code> itself contains some templating. So it looks like we need to render that as well.</p><pre><code class="language-clojure">(defn update-episode [{:keys [base-dir src-dir] :as opts}
                      {:keys [audio-file path] :as episode}]
  (let [filename (format &quot;%s/%s%s/%s&quot; base-dir src-dir path audio-file)]
    (assoc episode
           :audio-filesize (fs/size filename)
           :duration (audio/mp3-duration filename)
           :description (selmer/render (:description episode)
                                       (assoc opts :episode episode)))))

;; ...

(comment

  (podcast-feed opts)
  ;; =&gt; &quot;&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;\n
  ;;     &lt;rss version=\&quot;2.0\&quot; ...&gt;\n
  ;;       &lt;channel&gt;\n
  ;;         &lt;title&gt;Organising Tech in Sweden&lt;/title&gt;\n
  ;;         &lt;description&gt;Organising Tech in Sweden is a...&lt;/description&gt;\n
  ;;         ...
  ;;         &lt;item&gt;\n
  ;;           &lt;title&gt;Trailer&lt;/title&gt;\n
  ;;           &lt;description&gt;&lt;![CDATA[\n
  ;;             &lt;p&gt;\n  Union organising seems to be in the air these days...&lt;/p&gt;\n
  ;;             &lt;p class=\&quot;soundcljoud-hidden\&quot;&gt;\n
  ;;               To view full show notes, including transcripts, please visit the\n
  ;;               &lt;a href=\&quot;https://orgtech.se/episodes/ep00-trailer/\&quot;&gt;episode page&lt;/a&gt;.\n
  ;;             &lt;/p&gt;\n
  ;;             &lt;p&gt;\n
  ;;               Cover art by &lt;a href=\&quot;https://anyakjordan.com/\&quot;&gt;Anya K. Jordan&lt;/a&gt;\n
  ;;             &lt;/p&gt;\n
  ;;             &lt;p&gt;\n
  ;;               Theme music by &lt;a href=\&quot;https://soundcloud.com/ptzery\&quot;&gt;Ptzery&lt;/a&gt;\n&lt;/p&gt;
  ;;           ]]&gt;&lt;/description&gt;\n
  ;;           ...
  ;;         &lt;/item&gt;\n\n
  ;;         ...
  ;;       &lt;/channel&gt;\n
  ;;     &lt;/rss&gt;\n&quot;

  )
</code></pre><p>OK, this looks much better! And in fact, it looks so much better that we can declare victory and move on to figuring out how to write this beautiful feed to disk!</p><p>To do that, let&apos;s jump back to our <code>orgtech-se/bb.edn</code> and add a task for rendering the feed. We&apos;ll need to add the Soundcljoud processor to our deps, then we can pretend we have a <code>tasks/render</code> function and call it:</p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;2f8a9ed2d39a1b09d2b4d34d95494b56468f4a23&quot;}
        io.github.babashka/http-server
        {:git/sha &quot;e203166a020509d126149ff8046489857ce5c89f&quot;}
        ;; You can always depend on Soundcljoud!
        ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
        io.github.jmglov/soundcljoud
        {:local/root &quot;/home/jmglov/code/soundcljoud/processor&quot;}
        ;; 👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆
        io.github.jmglov/transcribble
        {:local/root &quot;/home/jmglov/code/transcribble/cli&quot;}}
 :paths [&quot;.&quot;]
 :tasks
 {
  ;; ...

  ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
  render {:doc &quot;Create webpages from templates&quot;
          :task (tasks/render opts)}
  ;; 👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆
   
  ;; ...
 }}
</code></pre><p>And now we pop over to <code>tasks.clj</code> to implement the task. Sadly, we need to restart our REPL since we added a new dependency and I&apos;m too lazy to learn how to use the new <code>clojure.repl.deps.add-lib</code> from Clojure 1.12 (added to Babashka in version <a href="https://github.com/babashka/babashka/releases/tag/v1.4.192">1.4.192</a>). In Emacs, we can do this with <strong>C-c C-z</strong> (<code>cider-switch-to-repl-buffer</code>) to jump to the REPL buffer, then <strong>C-c C-q</strong> (<code>cider-quit</code>) to stop the REPL, then <strong>C-c M-j</strong> (<code>cider-jack-in-clj</code>) to start a new REPL. Easy peasy!</p><p>Thus armed with a new REPL, let&apos;s pull in the namespaces required to load our <code>podcast.edn</code> and then actually load our <code>podcast.edn</code>:</p><pre><code class="language-clojure">(ns tasks
  (:require [babashka.cli :as cli]
            [babashka.process :as p]
            ;; Pull in some new namespaces
            ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇 
            [babashka.fs :as fs]
            [clojure.edn :as edn]
            ;; 👆👆👆👆👆👆👆👆👆👆👆👆👆👆
            ))

(comment

  (def default-opts {:website-bucket &quot;orgtech.se&quot;
                     :out-dir &quot;public&quot;
                     :distribution-id &quot;FDCBA42RSTUV3&quot;})  ; C-c C-v f c e
  ;; =&gt; #&apos;tasks/default-opts

  (def opts
    (let [base-dir (str (fs/cwd))]
      (merge default-opts
             (-&gt; (fs/file base-dir &quot;podcast.edn&quot;)
                 slurp
                 edn/read-string
                 (assoc :base-dir base-dir)))))
  ;; =&gt; #&apos;tasks/opts

  opts
  ;; =&gt; {:website-bucket &quot;orgtech.se/blog&quot;,
  ;;     :out-dir &quot;public&quot;,
  ;;     :distribution-id &quot;EPTUS11MTYJF7&quot;,
  ;;     :base-url &quot;https://orgtech.se&quot;,
  ;;     :src-dir &quot;public&quot;,
  ;;     :podcast { ... },
  ;;     :episodes [ ... ],
  ;;     :base-dir &quot;/home/jmglov/code/orgtech-se&quot;}

)
</code></pre><p>To set ourselves up for success with <code>soundcljoud.rss/podcast-feed</code>, we know that we need our MP3 files in the right place. And in fact, we cheated a bit in our REPL to copy those files to the right place, which means we have some code lying around that we can use! And whilst we&apos;re at it, we should also copy the transcript files, since we&apos;re referring to them in the rendered feed.</p><pre><code class="language-clojure">(comment

  (doseq [episode (:episodes opts)
          file (map episode [:audio-file :transcript-file])
          :let [filename (format &quot;%s/%s%s/%s&quot;
                                 (:base-dir opts) (:src-dir opts)
                                 (:path episode) file)
                src-filename (fs/file (:base-dir opts)
                                      (fs/file-name (:path episode))
                                      file)]]
    (when-not (fs/exists? filename)
      (fs/create-dirs (fs/parent filename))
      (fs/copy src-filename filename)))
  ;; =&gt; nil

  (-&gt;&gt; (fs/glob (fs/file (:base-dir opts) (:src-dir opts)) &quot;episodes/**&quot;)
       (map #(-&gt; (str %)
                 (str/replace (:base-dir opts) &quot;&quot;))))
  ;; =&gt; (&quot;/public/episodes/ep01-klarna-part1&quot;
  ;;     &quot;/public/episodes/ep01-klarna-part1/otis-ep01-klarna-part1.otr&quot;
  ;;     &quot;/public/episodes/ep01-klarna-part1/otis-ep01-klarna-part1.mp3&quot;
  ;;     &quot;/public/episodes/ep02-klarna-part2&quot;
  ;;     &quot;/public/episodes/ep02-klarna-part2/otis-ep02-klarna-part2.otr&quot;
  ;;     &quot;/public/episodes/ep02-klarna-part2/otis-ep02-klarna-part2.mp3&quot;
  ;;     &quot;/public/episodes/ep00-trailer&quot;
  ;;     &quot;/public/episodes/ep00-trailer/otis-ep00-trailer.otr&quot;
  ;;     &quot;/public/episodes/ep00-trailer/otis-ep00-trailer.mp3&quot;)

  )
</code></pre><p>Now that the files are, well, filed, let&apos;s see about rendering the podcast feed.</p><pre><code class="language-clojure">(ns tasks
  (:require ; ...
            [soundcljoud.rss :as rss]))

(comment

  (let [feed-file (fs/file (:src-dir opts) &quot;feed.rss&quot;)]
    (println (format &quot;Writing RSS feed %s&quot; feed-file))
    (-&gt;&gt; (rss/podcast-feed opts)
         (spit feed-file)))
  ;; =&gt; nil

  (slurp &quot;public/feed.rss&quot;)
  ;; =&gt; &quot;&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;\n
  ;;     &lt;rss version=\&quot;2.0\&quot;\n
  ;;          xmlns:itunes=\&quot;http://www.itunes.com/dtds/podcast-1.0.dtd\&quot;\n
  ;;          xmlns:atom=\&quot;http://www.w3.org/2005/Atom\&quot;&gt;\n
  ;;       &lt;channel&gt;\n
  ;;         &lt;title&gt;Organising Tech in Sweden&lt;/title&gt;\n
  ;;         &lt;description&gt;Organising Tech in Sweden is a...&lt;/description&gt;\n
  ;;         &lt;itunes:image href=\&quot;https://orgtech.se/img/orgtech-se-cover.jpg\&quot;/&gt;\n
  ;;         &lt;language&gt;en&lt;/language&gt;\n
  ;;         &lt;itunes:explicit&gt;true&lt;/itunes:explicit&gt;\n
  ;;         &lt;itunes:category text=\&quot;Technology\&quot;&gt;\n
  ;;         &lt;/itunes:category&gt;\n
  ;;         &lt;itunes:category text=\&quot;News\&quot;&gt;\n
  ;;           &lt;itunes:category text=\&quot;Politics\&quot; /&gt;\n
  ;;         &lt;/itunes:category&gt;\n
  ;;         &lt;itunes:author&gt;Organising Tech in Sweden&lt;/itunes:author&gt;\n
  ;;         &lt;link&gt;https://orgtech.se&lt;/link&gt;\n
  ;;         &lt;itunes:title&gt;Organising Tech in Sweden&lt;/itunes:title&gt;\n
  ;;         &lt;itunes:type&gt;Serial&lt;/itunes:type&gt;\n
  ;;         &lt;copyright&gt;All rights reserved, Organising Tech in Sweden&lt;/copyright&gt;\n
  ;;         &lt;item&gt;\n
  ;;           &lt;title&gt;Trailer&lt;/title&gt;\n
  ;;           &lt;enclosure\n
  ;;               url=\&quot;https://orgtech.se/episodes/ep00-trailer/otis-ep00-trailer.mp3\&quot;\n
  ;;               length=\&quot;1016937\&quot;\n
  ;;               type=\&quot;audio/mpeg\&quot; /&gt;\n
  ;;           &lt;guid&gt;https://orgtech.se/episodes/ep00-trailer/otis-ep00-trailer.mp3&lt;/guid&gt;\n
  ;;           &lt;pubDate&gt;Thu, 5 Sep 2024 00:00:00 +0000&lt;/pubDate&gt;\n
  ;;           &lt;description&gt;&lt;![CDATA[\n
  ;;             &lt;p&gt;\n
  ;;               Union organising seems to be in the air these days...
  ;;             &lt;/p&gt;]]&gt;
  ;;           &lt;/description&gt;\n
  ;;           &lt;itunes:duration&gt;42&lt;/itunes:duration&gt;\n
  ;;           &lt;link&gt;https://orgtech.se/episodes/ep00-trailer&lt;/link&gt;\n
  ;;           &lt;itunes:title&gt;Trailer&lt;/itunes:title&gt;\n
  ;;           &lt;itunes:episode&gt;0&lt;/itunes:episode&gt;\n
  ;;           &lt;itunes:episodeType&gt;Trailer&lt;/itunes:episodeType&gt;\n
  ;;           &lt;transcriptUrl&gt;https://orgtech.se/episodes/ep00-trailer/otis-ep00-trailer.otr&lt;/transcriptUrl&gt;\n
  ;;         &lt;/item&gt;\n
  ;;         ...
  ;;       &lt;/channel&gt;
  ;;     &lt;/rss&gt;

  )
</code></pre><p>OK, now we have everything we need to write our <code>render</code> function, so let&apos;s get to it:</p><pre><code class="language-clojure">(defn render [default-opts]
  (let [base-dir (str (fs/cwd))
        {:keys [episodes src-dir] :as opts}
        (merge default-opts
               (cli/parse-opts *command-line-args*)
               (-&gt; (fs/file base-dir &quot;podcast.edn&quot;)
                   slurp
                   edn/read-string
                   (assoc :base-dir base-dir)))
        feed-file (fs/file src-dir &quot;feed.rss&quot;)]
    (doseq [{:keys [path] :as episode} (:episodes opts)
            file (map episode [:audio-file :transcript-file])
            :let [filename (format &quot;%s/%s%s/%s&quot; base-dir src-dir path file)
                  src-filename (fs/file base-dir (fs/file-name path) file)]]
      (when-not (fs/exists? filename)
        (fs/create-dirs (fs/parent filename))
        (fs/copy src-filename filename)))
    (println (format &quot;Writing RSS feed %s&quot; feed-file))
    (-&gt;&gt; (rss/podcast-feed opts)
         (spit feed-file))))

(comment

  (render default-opts)
  ;; =&gt; nil

  )
</code></pre><p>We should now be able to aim our web browser at <a href="http://localhost:1341/feed.rss">http://localhost:1341/feed.rss</a> and see a lovely podcast feed.</p><p><img alt="RSS feed displayed in a web browser" src="assets/2024-09-18-podcast-soundcljoud-feed.png" title="Feed me nothing but the good stuff!" class="border" /></p><p>As lovely as this loveliness is, our eye is inexorably and tragically drawn to one thing which we do not love:</p><pre><code class="language-xml">    &lt;item&gt;
      ...
      &lt;link&gt;https://orgtech.se/episodes/ep00-trailer&lt;/link&gt;
      ...
    &lt;/item&gt;
</code></pre><p>This page, dear reader, does not exist!</p><div class="markdown-heading"><h2 id="selmer-to-the-rescue">Selmer to the rescue</h2><a href="#selmer-to-the-rescue" class="anchor" aria-label="Permalink: Selmer to the rescue"><img src="assets/link.svg" /></a></div><p>Where does this <code>&lt;link&gt;</code> thingy come from, and why do we need it anyway? Well, if we refer back to <a href="https://help.apple.com/itc/podcasts_connect/#/itcb54353390">A Podcaster&apos;s Guide to
RSS</a>, we see:</p><blockquote><p><code>&lt;link&gt;</code></p><p>An episode link URL. This is used when an episode has a corresponding webpage.</p></blockquote><p>Ah, so it&apos;s an episode page we need, eh? Well, we have a bunch of info about the episode in our <code>podcast.edn</code> file, and some code that loops over episodes and does stuff in <code>tasks/render</code>, and a deep and abiding love for Selmer, so let&apos;s whip up an episode page template, then plug some stuff in whilst we&apos;re looping over episodes. We&apos;ll start with the template, which we&apos;ll drop into a new <code>templates/episode-page.html</code> file:</p><pre><code class="language-html">&lt;!doctype html&gt;
&lt;html class=&quot;no-js&quot; lang=&quot;&quot;&gt;

&lt;head&gt;
  &lt;title&gt;
    {{podcast.title}} Episode {{episode.number}} - {{episode.title}}
  &lt;/title&gt;

  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;ie=edge&quot;&gt;

  &lt;link rel=&quot;stylesheet&quot; href=&quot;/css/main.css&quot;&gt;

  &lt;!-- Favicon from https://realfavicongenerator.net/ --&gt;
  &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;180x180&quot; href=&quot;/apple-touch-icon.png&quot;&gt;
  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;32x32&quot; href=&quot;/favicon-32x32.png&quot;&gt;
  &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;16x16&quot; href=&quot;/favicon-16x16.png&quot;&gt;
  &lt;link rel=&quot;manifest&quot; href=&quot;/site.webmanifest&quot;&gt;
  &lt;link rel=&quot;mask-icon&quot; href=&quot;/safari-pinned-tab.svg&quot; color=&quot;#5bbad5&quot;&gt;
  &lt;meta name=&quot;msapplication-TileColor&quot; content=&quot;#da532c&quot;&gt;
  &lt;meta name=&quot;theme-color&quot; content=&quot;#ffffff&quot;&gt;

  &lt;!-- Social sharing (Facebook, Twitter, LinkedIn, etc.) --&gt;
  &lt;meta name=&quot;title&quot; content=&quot;{{podcast.title}} Episode {{episode.number}} - {{episode.title}}&quot;&gt;
  &lt;meta name=&quot;twitter:title&quot; content=&quot;{{podcast.title}} Episode {{episode.number}} - {{episode.title}}&quot;&gt;
  &lt;meta property=&quot;og:title&quot; content=&quot;{{podcast.title}} Episode {{episode.number}} - {{episode.title}}&quot;&gt;
  &lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;

  &lt;meta name=&quot;description&quot; content=&quot;{{episode.summary}}&quot;&gt;
  &lt;meta name=&quot;twitter:description&quot; content=&quot;{{episode.summary}}&quot;&gt;
  &lt;meta property=&quot;og:description&quot; content=&quot;{{episode.summary}}&quot;&gt;

  &lt;meta name=&quot;twitter:url&quot; content=&quot;{{base-url}}{{episode.path}}/index.html&quot;&gt;
  &lt;meta property=&quot;og:url&quot; content=&quot;{{base-url}}{{episode.path}}/index.html&quot;&gt;

  &lt;meta name=&quot;twitter:image&quot; content=&quot;{{base-url}}{{preview-image}}&quot;&gt;
  &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot;&gt;
  &lt;meta property=&quot;og:image&quot; content=&quot;{{base-url}}{{preview-image}}&quot;&gt;
  &lt;meta property=&quot;og:image:alt&quot; content=&quot;{{podcast.image-alt}}&quot;&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;div id=&quot;wrapper&quot;&gt;
    &lt;div id=&quot;left-side&quot;&gt;
      &lt;img id=&quot;cover-image&quot; src=&quot;{{podcast.image}}&quot; alt=&quot;{{podcast.image-alt}}&quot; /&gt;
      &lt;div id=&quot;aggregators-1&quot;&gt;
        &lt;div id=&quot;apple&quot;&gt;
          &lt;a class=&quot;apple-button&quot;
            href=&quot;https://podcasts.apple.com/us/podcast/organising-tech-in-sweden/id1766442275?itsct=podcast_box_badge&amp;amp;itscg=30200&amp;amp;ls=1&quot;&gt;
            &lt;img src=&quot;https://tools.applemediaservices.com/api/badges/listen-on-apple-podcasts/badge/en-us?size=250x83&amp;amp;releaseDate=1725494400&quot;
              title=&quot;Listen on Apple Podcasts&quot; alt=&quot;Listen on Apple Podcasts&quot; class=&quot;apple-button&quot;&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div id=&quot;spotify&quot;&gt;
          &lt;a href=&quot;https://open.spotify.com/show/53psoLoX187axvmgb80l1x&quot;&gt;
            &lt;img src=&quot;/img/spotify-podcast-badge-blk-grn-330x80.svg&quot; title=&quot;Listen on Spotify&quot;
              alt=&quot;Listen on Spotify&quot;&gt;
          &lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div id=&quot;aggregators-2&quot;&gt;
        &lt;div id=&quot;podbean&quot;&gt;
          &lt;a href=&quot;https://www.podbean.com/podcast-detail/2r2tz-31b053/Organising-Tech-in-Sweden-Podcast&quot;
            rel=&quot;noopener noreferrer&quot; target=&quot;_blank&quot;&gt;
            &lt;img src=&quot;https://pbcdn1.podbean.com/fs1/site/images/badges/w600_1.png&quot;
              title=&quot;Listen on Podbean&quot; alt=&quot;Listen on Podbean&quot;&gt;
          &lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div id=&quot;main&quot;&gt;
      &lt;nav id=&quot;header&quot;&gt;
        &lt;h1 id=&quot;title&quot;&gt;{{episode.title}}&lt;/h1&gt;
        &lt;div id=&quot;socials&quot;&gt;
          {% for social in socials %}
          &lt;a href=&quot;{{social.url}}&quot;&gt;
            &lt;img src=&quot;{{social.image}}&quot; alt=&quot;{{social.image-alt}}&quot; /&gt;
          &lt;/a&gt;
          {% endfor %}
        &lt;/div&gt;
      &lt;/nav&gt;
      &lt;div id=&quot;description&quot;&gt;{{episode.description|safe}}&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div id=&quot;transcript&quot;&gt;
    &lt;h1&gt;Transcript&lt;/h1&gt;
    &lt;div id=&quot;transcript-body&quot;&gt;{{episode.transcript-html|safe}}&lt;/div&gt;
  &lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>We should also sprinkle a little extra CSS into our <code>public/css/main.css</code>:</p><pre><code class="language-css">/* ... */

#aggregators-1 {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

#aggregators-1 img {
  width: 175px;
}

#apple a {
  display: inline-block;
  overflow: hidden;
}

.apple-button {
  border-radius: 13px;
}

#aggregators-2 {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

#podbean img {
  height: 42px;
}

/* Some paragraphs in the description shouldn&apos;t be displayed on the episode page */
p.soundcljoud-hidden {
  display: none;
}

#transcript {
  background-color: #e4f1fe;
  border: solid 1px;
  padding-left: 1em;
  padding-right: 1em;
  margin-top: 1em;
}

#transcript-body &gt; br {
  display: none;
}

span.timestamp {
  margin-right: 5px;
  color: blue;
  cursor: pointer;
  &amp;:hover {
    text-decoration: underline;
  }
}

@media screen and (min-width: 600px) {

  /* ... */

  #aggregators-1 img {
    width: 155px;
  }

  #podbean img {
    height: 37px;
  }

  #podbean img {
    margin-top: 0px;
  }

}
</code></pre><p>We&apos;ll need the following template vars:</p><ul><li>base-url</li><li>episode.description</li><li>episode.number</li><li>episode.path</li><li>episode.summary</li><li>episode.title</li><li>episode.transcript-html</li><li>podcast.image</li><li>podcast.image-alt</li><li>podcast.title</li><li>preview-image</li><li>socials<ul><li>social.url</li><li>social.image</li><li>social.image-alt</li></ul></li></ul><p>Most of this we already have, but there are a couple new things. Let&apos;s take the easiest two first.</p><ul><li>podcast.image-alt</li><li>preview-image</li></ul><p>We&apos;ll add some alt text for our podcast cover image and a social preview image to <code>podcast.edn</code>. The alt text is just a description of the cover image, and it turns out that the preview image is one of the many things we hardcoded into our <code>public/index.html</code> way back when.</p><pre><code class="language-clojure">{ ; ...
 :preview-image &quot;/img/orgtech-se-preview.jpg&quot;
 ;; ...
 :podcast { ; ...
           :image-alt &quot;Organising Tech in Sweden superimposed on raised fists with a Swedish flag with a circuit board pattern in the background&quot;
           ;; ...
           }
 ;; ...
 }
</code></pre><p>Let&apos;s turn next to <code>socials</code>. This is how we refer to it in the template:</p><pre><code class="language-html">        {% for social in socials %}
        &lt;a href=&quot;{{social.url}}&quot;&gt;
          &lt;img src=&quot;{{social.image}}&quot; alt=&quot;{{social.image-alt}}&quot; /&gt;
        &lt;/a&gt;
        {% endfor %}
</code></pre><p>This means that it needs to be a list, and each list item should be a map containing three keys:</p><ul><li>social.url</li><li>social.image</li><li>social.image-alt</li></ul><p>Let&apos;s add the following to our <code>podcast.edn</code>:</p><pre><code class="language-clojure">{ ; ...
 :preview-image &quot;/img/orgtech-se-preview.jpg&quot;
 ;; ...
 :socials [{:name &quot;Twitter&quot;
            :url &quot;https://x.com/orgtech_se&quot;
            :image &quot;/img/twitter-color-svgrepo-com.svg&quot;
            :image-alt &quot;Twitter logo&quot;}
           {:name &quot;BlueSky&quot;
            :url &quot;https://bsky.app/profile/orgtech-se.bsky.social&quot;
            :image &quot;/img/bluesky-logo.svg&quot;
            :image-alt &quot;BlueSky logo&quot;}]
 ;; ...
 }
</code></pre><p>Finally, we need to conjure up one last key for each episode:</p><ul><li>episode.transcript-html</li></ul><p>Episodes already have a <code>:transcript-file</code> key, which refers to an OTR file. Let&apos;s have a quick look at one of those and see what is contained therein:</p><pre><code class="language-json">{
  &quot;text&quot;: &quot;&lt;p&gt;[Theme music begins]&lt;/p&gt;&lt;p&gt;&lt;span class=\&quot;timestamp\&quot; data-timestamp=\&quot;12.111684\&quot;&gt;00:12&lt;/span&gt;&lt;b&gt;Josh&lt;/b&gt;: ... &lt;/p&gt;&quot;,
  &quot;media&quot;: &quot;otis-ep01-klarna-part1.mp3&quot;,
  &quot;media-time&quot;: 1315.629803
}
</code></pre><p>What we have here is a JSON file with a thin veneer of metadata around a looooong HTML string. Let&apos;s deal with this back in <code>podcast.rss/update-episode</code>:</p><pre><code class="language-clojure">(defn update-episode [{:keys [base-dir src-dir] :as opts}
                      ;;                 👇👇👇👇👇👇👇
                      {:keys [audio-file transcript-file path] :as episode}]
                      ;;                 👆👆👆👆👆👆👆
  (let [filename (format &quot;%s/%s%s/%s&quot; base-dir src-dir path audio-file)
        ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
        transcript (format &quot;%s/%s%s/%s&quot; base-dir src-dir path transcript-file)]
        ;; 👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆
    (assoc episode
           :audio-filesize (fs/size filename)
           :duration (audio/mp3-duration filename)
           :description (selmer/render (:description episode)
                                       (assoc opts :episode episode))
           ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
           :transcript-html (-&gt; (slurp transcript)
                                (json/parse-string keyword)
                                :text))))
</code></pre><p>Having satisfied ourselves that we have all of the data we need for our template, let&apos;s get to rendering. In our <code>tasks/render</code> function, we&apos;re looping over episodes in order to copy the MP3 and OTR files into the right place. Sadly, we can&apos;t just pop <code>selmer/render</code> into that <code>doseq</code> and be done with it, because we need to ensure the audio file is in the right place before we can use <code>update-episode</code>. No problem, we&apos;ll just add a new bit after spitting our podcast feed:</p><pre><code class="language-clojure">(ns tasks
  (:require ; ...
            [selmer.parser :as selmer]))

(defn render [default-opts]
  (let [...]
    ;; ...
    (println (format &quot;Writing RSS feed %s&quot; feed-file))
    (-&gt;&gt; (rss/podcast-feed opts)
         (spit feed-file))
    (let [template (slurp &quot;templates/episode-page.html&quot;)
          opts (rss/update-episodes opts)]
      (doseq [{:keys [path] :as episode} (:episodes opts)
              :let [filename (format &quot;%s/%s%s/%s&quot;
                                     base-dir out-dir path &quot;index.html&quot;)]]
        (println &quot;Writing episode page&quot; filename)
        (-&gt;&gt; (selmer/render template (assoc opts :episode episode))
             (spit filename))))))
</code></pre><p>And now, the moment of truth!</p><pre><code class="language-text">: orgtech-se; bb render
Writing RSS feed public/feed.rss
Writing episode page ~/code/orgtech-se/public/episodes/ep00-trailer/index.html
Writing episode page ~/code/orgtech-se/public/episodes/ep01-klarna-part1/index.html
Writing episode page ~/code/orgtech-se/public/episodes/ep02-klarna-part2/index.html
</code></pre><p>And now if we visit (for example) <a href="http://localhost:1341/episodes/ep01-klarna-part1">http://localhost:1341/episodes/ep01-klarna-part1</a>, we should see an amazing webpage:</p><p><img alt="Episode page displayed in a web browser" src="assets/2024-09-18-podcast-soundcljoud-episode.png" title="I feel good, but also empty" class="border" /></p><div class="markdown-heading"><h2 id="podcast-half-empty,-or-podcast-half-full?">Podcast half empty, or podcast half full?</h2><a href="#podcast-half-empty,-or-podcast-half-full?" class="anchor" aria-label="Permalink: Podcast half empty, or podcast half full?"><img src="assets/link.svg" /></a></div><p>Astute observers may have noticed one issue with the episode page: there&apos;s no way to play the episode. 🤦🏼</p><p>Fear not! In the next instalment, we&apos;ll look at playing a podcast with ClojureScript, perhaps even using our own friend <a href="tags/soundcljoud.html">Soundcljoud</a>!</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-08-13-soundcljoud-rangey.html</id>
    <link href="https://jmglov.net/blog/2024-08-13-soundcljoud-rangey.html"/>
    <title>Soundcljoud gets more rangey</title>
    <updated>2024-08-13T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="A golfer with the Soundcljoud logo as their head about to hit a shot; Photo by Andrew Rice on Unsplash" src="assets/2024-08-13-soundcljoud-rangey-preview.png" title="FORE!" /></p><p><a href="2024-07-20-soundcljoud-cloudy.html">Last time</a> on &quot;Soundcljoud gets more cloudy&quot;, I found myself deeply saddened that the eternal truths I was seeking in the music of Garth Brooks remained elusive due to my attempts to seek forward in a track were rebuffed by my browser, instead abruptly returning me to the beginning of the track. 😳</p><p>Appropriately chastened, I popped the bonnet and had a look at what my user agent was doing on my behalf. When I loaded a track, I saw a request like this:</p><pre><code class="language-text">GET /Garth+Brooks/Fresh+Horses/Garth+Brooks+-+The+Old+Stuff.mp3 HTTP/1.1
Range: bytes=0-
</code></pre><p>and a response like this:</p><pre><code class="language-text">HTTP/1.1 200 OK
Content-length: 5943424
Content-Type: audio/mpeg
Server: http-kit
</code></pre><p>with a bunch of bytes in the body. In fact, a bountiful buffet of beautiful bytes, five whole million of them! And another 943,424 thrown in for dessert.</p><p>Herein lies the rub. What the browser wants back is some indication that the server knows how to return a range of bytes, because the browser doesn&apos;t want to fetch the entire damned file every time the user starts playing a track. After all, the user might be trying to remember if the track entitled &quot;The Old Stuff&quot; contains the amazing homage to a &quot;worn out tape of Chris LeDoux&quot; (spoiler: it does not), and just listening to the first few seconds to determine this, then, disappointed, moving on to another track to sample the first few seconds of that one.</p><p>And how, you might ask, does the server indicate its range savviness? Well, according to our good friends over at the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests">Mozilla Developer
Network</a>, by returning a response such as this:</p><pre><code class="language-text">HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-length: 1048576
Content-Range: bytes 0-1048575/5943424
Content-Type: audio/mpeg
</code></pre><div class="markdown-heading"><h2 id="whence-ranges?">Whence ranges?</h2><a href="#whence-ranges?" class="anchor" aria-label="Permalink: Whence ranges?"><img src="assets/link.svg" /></a></div><p>Let&apos;s refresh our memory a bit by firing up <a href="https://github.com/jmglov/soundcljoud">Soundcljoud</a>:</p><pre><code class="language-text">cd ~/code/soundcljoud/player
bb dev
</code></pre><p>Now we can pop over to <a href="http://localhost:1341/">http://localhost:1341/</a>, open up the <code>soundcljoud.cljs</code> in Emacs (or whatever inferior text editor you choose to inflict upon yourself), hit <strong>C-c l C</strong> (<code>cider-connect-cljs</code>) to start a REPL connected to localhost port 1339 (REPL type <code>nbb</code>), and finally evaluate <code>load-ui!</code> to get things going:</p><pre><code class="language-clojure">(comment

  (load-ui! &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&lt;Promise[~]&gt;

  )
</code></pre><p><img alt="The Soundcljoud UI, playing album Garth Brooks - Fresh Horses" src="assets/2024-08-13-soundcljoud-rangey-eye.png" title="The all-seeing eye of Garth is upon us" class="border" /></p><p>Opening the network tab, we see exactly what the browser asked for and exactly what the server responded:</p><p><img alt="Browser developer tools, showing the network request and response for the MP3 file" src="assets/2024-08-13-soundcljoud-rangey-range.png" title="Yeah, I didn&apos;t want *all* of the bytes..." class="border" /></p><p>First, the browser asks for some bytes, starting at the beginning of the file:</p><pre><code class="language-text">Range: bytes=0-
</code></pre><p>Since the end of the byte range isn&apos;t specified, the server is free to decide how many bytes to send back. Let&apos;s say we&apos;ll send back 1 MB (1048576 bytes). Our response should start by indicating that we&apos;re not returning the entire file, but rather just a part of it:</p><pre><code class="language-text">HTTP/1.1 206 Partial Content
</code></pre><p>Now we need to say which bytes we&apos;re returning, out of the total number of bytes in the file, as well as the length of the response, in bytes:</p><pre><code class="language-text">Content-Range: bytes 0-1048575/6062208
Content-length: 1048576
</code></pre><p>Note that the byte range is zero-indexed and <strong>inclusive</strong> on the end, meaning that the last byte we return is at index 1048575, whilst the content length is the <strong>number of bytes</strong> in the response body.</p><p>Finally, we need to let the client know what kind of range requests we support. We&apos;ll limit this to bytes:</p><pre><code class="language-text">Accept-Ranges: bytes
</code></pre><p>We must now flip Hegel on his head, as the saying goes, and move from lofty ideas to dirty, inconvenient material reality. In other words, we gotta implement range requests in our actual webserver.</p><div class="markdown-heading"><h2 id="getting-materialistic">Getting materialistic</h2><a href="#getting-materialistic" class="anchor" aria-label="Permalink: Getting materialistic"><img src="assets/link.svg" /></a></div><p>Let&apos;s cast our minds back to what happens when we type</p><pre><code class="language-text">bb dev
</code></pre><p>in our terminal. According to our <code>bb.edn</code>:</p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;2f8a9ed2d39a1b09d2b4d34d95494b56468f4a23&quot;}
        io.github.babashka/http-server
        {:git/sha &quot;b38c1f16ad2c618adae2c3b102a5520c261a7dd3&quot;}}
 :tasks
 {http-server
  {:doc &quot;Starts http server for serving static files&quot;
   :requires ([babashka.http-server :as http])
   :task (do (http/serve {:port 1341 :dir &quot;public&quot;})
             (println &quot;Serving static assets at http://localhost:1341&quot;))}

  browser-nrepl
  {:doc &quot;Start browser nREPL&quot;
   :requires ([sci.nrepl.browser-server :as bp])
   :task (bp/start! {})}

  -dev
  {:depends [http-server browser-nrepl]}

  dev
  {:task (do (run &apos;-dev {:parallel true})
           (deref (promise)))}}}
</code></pre><p>OK, so it looks like <a href="https://github.com/babashka/http-server">io.github.babashka/http-server</a> is the thing serving up our content. Let&apos;s go ahead and clone that so we can start digging through the code:</p><pre><code class="language-text">cd ~/code
git clone git@github.com:babashka/http-server.git
</code></pre><p>Tracing through <code>bb.edn</code>, we see that the webserver is started by calling <code>babashka.http-server/serve</code> with a config map containing the port and directory:</p><pre><code class="language-clojure">{ ;; ...
 :tasks
 {http-server
  {:requires ([babashka.http-server :as http])
   :task (do (http/serve {:port 1341 :dir &quot;public&quot;})
             (println &quot;Serving static assets at http://localhost:1341&quot;))}
 ;; ...
 }}
</code></pre><p>Let&apos;s see what&apos;s going on thereabouts in the http-server source code. Opening <a href="https://github.com/babashka/http-server/blob/e625b1a367023bc400d38474677d071abd8c02fb/src/babashka/http_server.clj">src/babashka/http_server.clj</a>:</p><pre><code class="language-clojure">(defn serve
  &quot;Serves static assets using web server.
Options:
  * `:dir` - directory from which to serve assets
  * `:port` - port
  * `:headers` - map of headers {key value}&quot;
  [{:keys [port]
    :or {port 8090}
    :as opts}]
  (let [dir (or (:dir opts) &quot;.&quot;)
        opts (assoc opts :dir dir :port port)
        dir (fs/path dir)]
    (assert (fs/directory? dir) (str &quot;The given dir `&quot; dir &quot;` is not a directory.&quot;))
    (binding [*out* *err*]
      (println (str &quot;Serving assets at http://localhost:&quot; (:port opts))))
    (server/run-server (file-router dir (opts :headers)) opts)))
</code></pre><p>we see a bunch of ceremony before <code>server/run-server</code> is called with a <code>file-router</code> (whatever that is) and some opts; basically the port and directory we passed in from <code>bb.edn</code>. But what, pray tell, is this mystical <code>server</code> namespace?</p><pre><code class="language-clojure">(ns babashka.http-server
  (:require [babashka.fs :as fs]
            [clojure.string :as str]
            #_[clojure.tools.cli :refer [parse-opts]]
            [hiccup2.core :as html]
            [babashka.cli :as cli]
            [org.httpkit.server :as server])
  (:import [java.net URLDecoder URLEncoder]))
</code></pre><p>Aha! &apos;Tis none other than <a href="https://github.com/http-kit/http-kit">http-kit</a>, a &quot;minimalist and efficient Ring-compatible HTTP client+server for Clojure&quot;. Looking at the <a href="https://github.com/http-kit/http-kit/wiki/3-Server#start-server">documentation for
<code>run-server</code></a>, we see that the <code>file-router</code> thingy must return a <a href="https://github.com/ring-clojure/ring/wiki/Concepts#handlers">Ring
handler</a>, which is nothing more than a function that takes a request map as its argument and returns a response map. This function will be called by http-kit upon every request.</p><p><code>start-server</code> returns a function that we can call to <a href="https://github.com/http-kit/http-kit/wiki/3-Server#stop-server">stop the
server</a>.</p><p>Using this knowledge, let&apos;s dig into the <code>file-router</code> handler function:</p><pre><code class="language-clojure">(defn file-router [dir headers]
  (fn [{:keys [uri]}]
    (let [f (fs/path dir (str/replace-first (URLDecoder/decode uri) #&quot;^/&quot; &quot;&quot;))
          index-file (fs/path f &quot;index.html&quot;)]
      (update (cond
                (and (fs/directory? f) (fs/readable? index-file))
                (body index-file)

                (fs/directory? f)
                (index dir f)

                (fs/readable? f)
                (body f)

                (and (nil? (fs/extension f)) (fs/readable? (with-ext f &quot;.html&quot;)))
                (body (with-ext f &quot;.html&quot;) headers)

                :else
                {:status 404 :body (str &quot;Not found `&quot; f &quot;` in &quot; dir)})
              :headers (fn [response-headers]
                         (merge headers response-headers))))))
</code></pre><p>OK, what&apos;s going on here? Well, we&apos;re returning a function (i.e. the Ring handler) that basically grabs the path part of the URI (which will be relative to the directory named by our <code>:dir</code> option; in other words, <code>soundcljoud/player/public</code>) and asks a series of questions in a <a href="https://clojuredocs.org/clojure.core/cond">cond</a> form:</p><ol start="1"><li>Does the path refer to a directory? If so, does there exist an <code>index.html</code> that is readable by the webserver?</li><li>Otherwise, does the path refer to a directory (without an <code>index.html</code>)?</li><li>Otherwise, does the path refer to a file that is readable by the webserver?</li><li>Otherwise, does the path refer to a thing which, if we slap a <code>.html</code> extension on the end, is a file that is readable by the webserver?</li><li>Why is this user wasting our time requesting stuff that we don&apos;t have?</li></ol><p>Let&apos;s think for a second about which case we&apos;re interested in. Our browser is requesting <code>/Garth Brooks/Fresh Horses/Garth Brooks - The Old Stuff.mp3</code>, which is going to hit condition #3 in the list:</p><pre><code class="language-clojure">                (fs/readable? f)
                (body f)
</code></pre><p>Let&apos;s see what&apos;s going on with this body. And yes, I am aware that sounds like the title of a <a href="https://en.wikipedia.org/wiki/Pitbull_(rapper)">Pitbull</a> collabo with <a href="https://en.wikipedia.org/wiki/Nicki_Minaj">Nicki Minaj</a>.</p><p><img alt="Fake cover art for a What&apos;s Going on with that Body? single" src="assets/2024-08-13-soundcljoud-rangey-body.png" title="¿Qué pasa con ese cuerpo?" /></p><pre><code class="language-clojure">(defn- body
  ([path]
   (body path {}))
  ([path headers]
   {:headers (merge {&quot;Content-Type&quot; (ext-mime-type (fs/file-name path))} headers)
    :body (fs/file path)}))
</code></pre><p>The only thing happening here is that the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME
type</a> of the file is being looked up using its extension and added as the <code>Content-Type</code> header, then the path itself is turned into a <code>java.io.File</code> with the <a href="https://github.com/babashka/fs/blob/master/API.md#babashka.fs/file">babashka.fs/file</a> function and added to the response map under the <code>:body</code> key. Presumably, http-kit will then take that <code>java.io.File</code> object and send the bytes back as the response body.</p><p>This looks very similar to what we will need to do, with the exception that instead of sending back all of the bytes in the file, we&apos;ll just want to send back those that were asked for.</p><p>Now that we know more or less where to start, let&apos;s fire up a REPL and start playing!</p><div class="markdown-heading"><h2 id="we-aim-to-serve">We aim to serve</h2><a href="#we-aim-to-serve" class="anchor" aria-label="Permalink: We aim to serve"><img src="assets/link.svg" /></a></div><p>The first thing we need to do is Ctrl-c our <code>bb dev</code> process, since we won&apos;t be able to start a webserver on port 1341 with that one in the way.</p><p>Next, let&apos;s open up <code>http-server/src/babashka/http_server.clj</code> in Emacs and start a REPL with <strong>C-c M-j</strong> (<code>cider-jack-in-clj</code>), choosing <code>babashka</code> as the command to start the REPL. Now, we load the buffer with <strong>C-c C-k</strong> (<code>cider-load-buffer</code>), and sign in relief as we&apos;re back in the REPL again.</p><p>For our first order of business, let&apos;s try starting a server from the REPL to serve up the files in the <code>soundcljoud/player/public</code> directory on port 1341, just like we had before:</p><pre><code class="language-clojure">(comment

  (def dir &quot;../soundcljoud/player/public&quot;)  ; C-c C-v f c e
  ;; =&gt; #&apos;babashka.http-server/dir
  
  (def server
    (server/run-server (file-router dir {})
                       {:dir dir, :port 1341}))
  ;; =&gt; #&apos;babashka.http-server/server

  )
</code></pre><p>OK, so we maybe have a webserver running. Let&apos;s try fetching a file to be sure:</p><pre><code class="language-text">: jmglov@alhana; curl http://localhost:1341/site.webmanifest
{
    &quot;name&quot;: &quot;Soundcljoud&quot;,
    &quot;short_name&quot;: &quot;Soundcljoud&quot;,
    &quot;icons&quot;: [
        {
            &quot;src&quot;: &quot;icons/android-chrome-192x192.png&quot;,
            &quot;sizes&quot;: &quot;192x192&quot;,
            &quot;type&quot;: &quot;image/png&quot;
        },
        {
            &quot;src&quot;: &quot;icons/android-chrome-512x512.png&quot;,
            &quot;sizes&quot;: &quot;512x512&quot;,
            &quot;type&quot;: &quot;image/png&quot;
        }
    ],
    &quot;theme_color&quot;: &quot;#ffffff&quot;,
    &quot;background_color&quot;: &quot;#ffffff&quot;,
    &quot;display&quot;: &quot;standalone&quot;
}
</code></pre><p>Looks good!</p><div class="markdown-heading"><h2 id="hacking-the-cloud">Hacking the cloud</h2><a href="#hacking-the-cloud" class="anchor" aria-label="Permalink: Hacking the cloud"><img src="assets/link.svg" /></a></div><p>The next step is making Soundcljoud use our local HTTP server instead of starting a new one. Back in <code>soundcljoud/player</code>, we open up <code>bb.edn</code>. Let&apos;s go ahead and change the deps first:</p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;2f8a9ed2d39a1b09d2b4d34d95494b56468f4a23&quot;}
        io.github.babashka/http-server
        {:git/sha &quot;b38c1f16ad2c618adae2c3b102a5520c261a7dd3&quot;}}
 ;; ...
 }
</code></pre><p>For the <code>io.github.babashka/http-server</code> dep, we can change the value from a Git reference to a local directory like this:</p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;2f8a9ed2d39a1b09d2b4d34d95494b56468f4a23&quot;}
        io.github.babashka/http-server
        {:local/root &quot;../../http-server&quot;}}
 ;; ...
 }
</code></pre><p>Next, we&apos;ll need to figure out how to start just the browser REPL. Let&apos;s take a look at the existing <code>dev</code> task that we&apos;ve been using:</p><pre><code class="language-clojure">{ ;; ...
 :tasks {http-server
         {:doc &quot;Starts http server for serving static files&quot;
          :requires ([babashka.http-server :as http])
          :task (do
                  (http/serve {:port 1341 :dir &quot;public&quot;})
                  (println &quot;Serving static assets at http://localhost:1341&quot;))}

         browser-nrepl
         {:doc &quot;Start browser nREPL&quot;
          :requires ([sci.nrepl.browser-server :as bp])
          :task (bp/start! {})}

         -dev
         {:depends [http-server browser-nrepl]}

         dev
         {:task (do (run &apos;-dev {:parallel true})
                  (deref (promise)))}}}
</code></pre><p>So <code>dev</code> just runs the <code>-dev</code> task in parallel, then derefs an empty promise to avoid exiting (calling <code>deref</code> on a promise will block the calling thread until the promise delivers, which an empty promise never will). The <code>-dev</code> task itself depends on <code>http-server</code> and <code>browser-nrepl</code>, but does nothing on its own.</p><p>Let&apos;s create a new task that follows this pattern but only starts the browser NREPL:</p><pre><code class="language-clojure">{ ;; ...
 :tasks { ;; ...

         dev
         {:task (do (run &apos;-dev {:parallel true})
                  (deref (promise)))}

         browser
         {:task (do (run &apos;browser-nrepl {:parallel true})
                    (deref (promise)))}}}
</code></pre><p>Now let&apos;s fire it up and see what happens:</p><pre><code class="language-text">: jmglov@alhana; bb browser
nREPL server started on port 1339...
Websocket server started on 1340...
</code></pre><p>Cool! If we now open <a href="http://localhost:1341/">http://localhost:1341/</a> in the browser, switch back to our open <code>soundcljoud.cljs</code> buffer and hit <strong>C-c l C</strong>, we see some very welcome log messages in our terminal:</p><pre><code class="language-text">nREPL server started on port 1339...
:msg &quot;{:versions {\&quot;scittle-nrepl\&quot; {\&quot;major\&quot; \&quot;0\&quot;, ...&quot;
</code></pre><p>With baited breath, we evaluate the <code>load-ui!</code> form and... see the good ol&apos; Eye of Garth! 🎉</p><p>This means Soundcljoud is using the http-server we&apos;re running from our REPL.</p><div class="markdown-heading"><h2 id="homing-in-on-the-range">Homing in on the range</h2><a href="#homing-in-on-the-range" class="anchor" aria-label="Permalink: Homing in on the range"><img src="assets/link.svg" /></a></div><p>Switching back to the <code>http-server/src/babashka/http_server.clj</code> buffer, let&apos;s figure out how to do some REPL-driven development to implement handling range requests.</p><p>The first order of business might be giving ourselves a way to log the requests we&apos;re getting from the client. Let&apos;s create an atom at the top of the file for this very purpose:</p><pre><code class="language-clojure">(defonce state (atom {:requests [], :log []}))
</code></pre><p>I&apos;m using <a href="https://clojuredocs.org/clojure.core/defonce">defonce</a> instead of plain &apos;ol <code>def</code> here because I tend to hit <strong>C-c C-k</strong> quite often whilst editing code, which not only causes the buffer to be re-evaluated, but also causes Emacs to ask me if I want to save my changes to the file, which is useful to keep code that&apos;s running in the system from drifting away from the code that&apos;s written in the source file. If I used <code>def</code> instead of <code>defonce</code>, my state atom would be reset every time I re-evaluate the buffer.</p><p>Now, we know that the function returned by <code>file-router</code> is a Ring handler, so let&apos;s jump there and see about how we can shove each request into our <code>state</code> atom:</p><pre><code class="language-clojure">(defn file-router [dir headers]
  (fn [{:keys [uri]}]
    ;; ...
    ))
</code></pre><p>OK, at the moment, the handler function only cares about the <code>:uri</code> key in the request. Let&apos;s bind the entire request and then add it to the atom:</p><pre><code class="language-clojure">(defn file-router [dir headers]
  (fn [{:keys [uri] :as req}]
    (swap! state update :requests conj req)
    ;; ...
    ))
</code></pre><p>In order to test this, we need to restart the server since we made a change to the anonymous function returned by <code>file-router</code>. To do this, we stop the server by calling the function that <code>server/run-server</code> returned when we evaluated it, then evaluate the <code>server/run-server</code> expression again:</p><pre><code class="language-clojure">(comment

  (server)
  ;; =&gt; nil

  (def server
    (server/run-server (file-router dir {})
                       {:dir dir, :port 1341}))
  ;; =&gt; #&apos;babashka.http-server/server

  )
</code></pre><p>Now, let&apos;s curl the manifest file again:</p><pre><code class="language-text">: jmglov@alhana; curl http://localhost:1341/site.webmanifest
{
    &quot;name&quot;: &quot;Soundcljoud&quot;,
    ...
}
</code></pre><p>If we look at our state atom now, we can see that the request was successfully logged:</p><pre><code class="language-clojure">(comment

  (:requests @state)
  ;; =&gt; [{:remote-addr &quot;0:0:0:0:0:0:0:1&quot;,
  ;;      :start-time 1004192760289113,
  ;;      :headers
  ;;      {&quot;accept&quot; &quot;*/*&quot;, &quot;host&quot; &quot;localhost:1341&quot;, &quot;user-agent&quot; &quot;curl/8.4.0&quot;},
  ;;      :async-channel
  ;;      #object[org.httpkit.server.AsyncChannel 0x44d028e7 &quot;/[0:0:0:0:0:0:0:1]:1341&lt;-&gt;/[0:0:0:0:0:0:0:1]:45890&quot;],
  ;;      :server-port 1341,
  ;;      :content-length 0,
  ;;      :websocket? false,
  ;;      :content-type nil,
  ;;      :character-encoding &quot;utf8&quot;,
  ;;      :uri &quot;/site.webmanifest&quot;,
  ;;      :server-name &quot;localhost&quot;,
  ;;      :query-string nil,
  ;;      :body nil,
  ;;      :scheme :http,
  ;;      :request-method :get}]

  )
</code></pre><p>OK, now that we&apos;ve got some basic logging in place, let&apos;s get back to thinking about range requests. A good place to start is by looking at the requests we get from Soundcljoud when it loads a file, so let&apos;s pop back over to that browser window and click on a track.</p><p>Once we&apos;ve done that, we can look at the request in our http-server REPL:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; @state
       :requests
       (map #(select-keys % [:start-time :headers :uri]))
       last)
  ;; =&gt; {:start-time 1006716878994472,
  ;;     :headers
  ;;     {&quot;range&quot; &quot;bytes=0-&quot;,
  ;;      &quot;sec-fetch-site&quot; &quot;same-origin&quot;,
  ;;      &quot;sec-ch-ua-mobile&quot; &quot;?0&quot;,
  ;;      &quot;host&quot; &quot;localhost:1341&quot;,
  ;;      &quot;user-agent&quot;
  ;;      &quot;Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&quot;,
  ;;      &quot;sec-ch-ua&quot;
  ;;      &quot;\&quot;Not_A Brand\&quot;;v=\&quot;8\&quot;, \&quot;Chromium\&quot;;v=\&quot;120\&quot;, \&quot;Brave\&quot;;v=\&quot;120\&quot;&quot;,
  ;;      &quot;sec-ch-ua-platform&quot; &quot;\&quot;Linux\&quot;&quot;,
  ;;      &quot;referer&quot; &quot;http://localhost:1341/&quot;,
  ;;      &quot;connection&quot; &quot;keep-alive&quot;,
  ;;      &quot;accept&quot; &quot;*/*&quot;,
  ;;      &quot;accept-language&quot; &quot;en-GB,en&quot;,
  ;;      &quot;sec-fetch-dest&quot; &quot;audio&quot;,
  ;;      &quot;accept-encoding&quot; &quot;identity;q=1, *;q=0&quot;,
  ;;      &quot;sec-fetch-mode&quot; &quot;no-cors&quot;,
  ;;      &quot;sec-gpc&quot; &quot;1&quot;},
  ;;     :uri
  ;;     &quot;/Garth%20Brooks/Fresh%20Horses/01%20-%20Garth%20Brooks%20-%20The%20Old%20Stuff.mp3&quot;}

  )
</code></pre><p>The interesting bit is this header right here, which is the thing that tells us that what we&apos;re dealing with here is a range request:</p><pre><code class="language-text">  ;;     :headers
  ;;     {&quot;range&quot; &quot;bytes=0-&quot;,
</code></pre><p>Remember those 5 questions we asked back in <code>file-router</code>?</p><ol start="1"><li>Does the path refer to a directory? If so, does there exist an <code>index.html</code> that is readable by the webserver?</li><li>Otherwise, does the path refer to a directory (without an <code>index.html</code>)?</li><li>Otherwise, does the path refer to a file that is readable by the webserver?</li><li>Otherwise, does the path refer to a thing which, if we slap a <code>.html</code> extension on the end, is a file that is readable by the webserver?</li><li>Why is this user wasting our time requesting stuff that we don&apos;t have?</li></ol><p>Well, let&apos;s insert a new question in there as #3, and bump the rest down:</p><ol start="1"><li>Does the path refer to a directory? If so, does there exist an <code>index.html</code> that is readable by the webserver?</li><li>Otherwise, does the path refer to a directory (without an <code>index.html</code>)?</li><li><strong>Otherwise, does the path refer to a file that is readable by the webserver and we have a <code>range</code> header in our request?</strong></li><li>Otherwise, does the path refer to a file that is readable by the webserver?</li><li>Otherwise, does the path refer to a thing which, if we slap a <code>.html</code> extension on the end, is a file that is readable by the webserver?</li><li>Why is this user wasting our time requesting stuff that we don&apos;t have?</li></ol><p>Let&apos;s write that in Clojure instead of English:</p><pre><code class="language-clojure">(defn file-router [dir headers]
  (fn [{:keys [uri] :as req}]
    (swap! state update :requests conj req)
    (let [f (fs/path dir (str/replace-first (URLDecoder/decode uri) #&quot;^/&quot; &quot;&quot;))
          index-file (fs/path f &quot;index.html&quot;)]
      (update (cond
                (and (fs/directory? f) (fs/readable? index-file))
                (body index-file)

                (fs/directory? f)
                (index dir f)

                ;; 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
                (and (fs/readable? f) (contains? (:headers req) &quot;range&quot;))
                (do
                  (swap! state update :log conj &quot;Handling range request&quot;)
                  (body f))
                ;; 👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆

                (fs/readable? f)
                (body f)

                (and (nil? (fs/extension f)) (fs/readable? (with-ext f &quot;.html&quot;)))
                (body (with-ext f &quot;.html&quot;) headers)

                :else
                {:status 404 :body (str &quot;Not found `&quot; f &quot;` in &quot; dir)})
              :headers (fn [response-headers]
                         (merge headers response-headers))))))
</code></pre><p>Now we can try this out. Unfortunately, we need to restart the server again to have it pick up the new code. The issue is that <code>file-handler</code> is returning an anonymous function, so when we edit the code and re-evaluate the buffer, we&apos;re not updating the copy of the function that http-kit is using as the request handler, we&apos;re updating <code>file-handler</code> itself, so the next time it&apos;s called, it will return a new handler function. In the writing of this blog, I did try pulling the anonymous function out and giving it a name, which I expected to fix this issue, but that didn&apos;t work, for reasons that aren&apos;t clear to me (maybe because http-kit is running the server on a different thread?). Yell at me in the Clojurians Slack thread if you know how to do this. 😅</p><p>Anyway, let&apos;s stop the server as usual:</p><pre><code class="language-clojure">(comment

  (server)
  ;; =&gt; nil

  )
</code></pre><p>And now, since we know we&apos;re going to need to do this dance every time we make changes to the code, let&apos;s write a little convenience function:</p><pre><code class="language-clojure">(comment

  (defn restart-server []
    (when (:server @state)
      ((:server @state)))
    (reset! state
            {:requests []
             :log []
             :server
             (server/run-server (file-router dir {})
                                {:dir dir, :port 1341})}))
  ;; =&gt; #&apos;babashka.http-server/restart-server

  )
</code></pre><p>Now we can just call <code>restart-server</code> whenever we need to, well, restart the server. Let&apos;s do so now:</p><pre><code class="language-clojure">(comment

  (restart-server)
  ;; =&gt; {:requests [],
  ;;     :server
  ;;     #object[clojure.lang.AFunction$1 0x3ece031a &quot;clojure.lang.AFunction$1@3ece031a&quot;]}

  )
</code></pre><p>Having done this, let&apos;s pop back over to Soundcljoud and click on another track, then inspect the log to make sure we see the message we expect:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; @state
       :log
       last)
  ;; =&gt; &quot;Handling range request&quot;

  )
</code></pre><p>Looks good! Except for the fact that we&apos;re still returning the entire file in the request body, of course. Still, the key to REPL-driven development is rapidly iterating, so let&apos;s take that next iteration now!</p><div class="markdown-heading"><h2 id="what&apos;s-in-a-range?">What&apos;s in a range?</h2><a href="#what&apos;s-in-a-range?" class="anchor" aria-label="Permalink: What&apos;s in a range?"><img src="assets/link.svg" /></a></div><p>Since we&apos;ve captured the request, let&apos;s go ahead and pull the range header out so we can play with it:</p><pre><code class="language-clojure">(comment

  (-&gt; (:requests @state) last (get-in [:headers &quot;range&quot;]))
  ;; =&gt; &quot;bytes=0-&quot;

  (def range-header *1)
  ;; =&gt; #&apos;babashka.http-server/range-header

  (let [[start end] (-&gt; range-header
                        (str/replace #&quot;^bytes=&quot; &quot;&quot;)
                        (str/split #&quot;-&quot;))]
    [start end])
  ;; =&gt; [&quot;0&quot; nil]

  )
</code></pre><p>The header parsing thing looks like a good thing to make into a function:</p><pre><code class="language-clojure">(defn- parse-range-header [range-header]
  (map #(when % (Long/parseLong %))
       (-&gt; range-header
           (str/replace #&quot;^bytes=&quot; &quot;&quot;)
           (str/split #&quot;-&quot;))))

(comment

  (parse-range-header range-header)
  ;; =&gt; (0)

)
</code></pre><p>OK, now let&apos;s shift gears and figure out how to return a specific byte range from a file. After much searching, I found a magical way to seek to an arbitrary location in a file in Java (and hence Clojure, through the magic of interop). Every <a href="https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html">FileInputStream</a> has an associated <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html">FileChannel</a>, and this FileChannel has a helpful <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#position-long-">position()</a> instance method, which sets the position in the FileChannel for subsequent read operations on the channel.</p><p>Now, how to perform a read operation on a FileInputStream? Looking at the documentation, this method looks quite useful:</p><p><a href="https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html#read-byte:A-"><strong>read</strong></a></p><pre><code class="language-java">public int read(byte[] b)
         throws IOException
</code></pre><blockquote><p>Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.</p></blockquote><p>And how do we create a <code>byte[]</code> array of an arbitrary size in Clojure? Why, by using the aptly-named <a href="https://clojuredocs.org/clojure.core/byte-array">byte-array</a> function, naturally! 😀</p><p>Let&apos;s try this out, using our helpful <code>site.webmanifest</code> file:</p><pre><code class="language-clojure">(comment

  (let [arr (byte-array 32)]
    (with-open [is (java.io.FileInputStream. manifest-file)]
      (-&gt; is .getChannel (.position 0))
      (.read is arr))
    (String. arr))
  ;; =&gt; &quot;{\n    \&quot;name\&quot;: \&quot;Soundcljoud\&quot;,\n   &quot;

  (let [arr (byte-array 16)]
    (with-open [is (java.io.FileInputStream. manifest-file)]
      (-&gt; is .getChannel (.position 14))
      (.read is arr))
    (String. arr))
  ;; =&gt; &quot;\&quot;Soundcljoud\&quot;,\n &quot;

  )
</code></pre><p>Now we&apos;re cooking with gas! 💥</p><p>Let&apos;s see if we can make a nice function out of this:</p><pre><code class="language-clojure">(defn- read-bytes [f [start end]]
  (let [arr (byte-array (- end start))]
    (with-open [is (java.io.FileInputStream. f)]
      (-&gt; is .getChannel (.position start))
      (.read is arr))
    arr))

(comment

  (-&gt; (read-bytes manifest-file [0 31])
      (String.))
  ;; =&gt; &quot;{\n    \&quot;name\&quot;: \&quot;Soundcljoud\&quot;,\n   &quot;

  (-&gt; (read-bytes manifest-file [14 29])
      (String.))
  ;; =&gt; &quot;\&quot;Soundcljoud\&quot;,\n &quot;

  )
</code></pre><p>There&apos;s one issue remaining, though. Remember the range header we got from Soundcljoud?</p><pre><code class="language-clojure">(comment

  range-header
  ;; =&gt; &quot;bytes=0-&quot;

  (parse-range-header range-header)
  ;; =&gt; (0)

)
</code></pre><p>We have a <code>start</code>, but not an <code>end</code>. 😱</p><p>Let&apos;s think about what we want to do in this case. The client is effectively saying, &quot;give me as many bytes as you feel inclined to do, starting at this offset in the file&quot;. So how many bytes are we inclined to hand out willy-nilly? I dunno, how about 1 mega of them bytes?</p><pre><code class="language-clojure">(defn- read-bytes [f [start end]]
  (let [end (or end (dec (+ start (* 1024 1024)))
        arr (byte-array (- end start))]
    (with-open [is (java.io.FileInputStream. f)]
      (-&gt; is .getChannel (.position start))
      (.read is arr))
    arr))

(comment

  (-&gt; (read-bytes manifest-file [0 31])
      (String.))  ; ⚠ OMG wait don&apos;t evaluate this for the love of Pete!

)
</code></pre><p>Yeah, so you really don&apos;t want to evaluate that last <code>read-bytes</code> expression. &quot;And why&apos;s that,&quot; you might ask? &quot;Well,&quot; I might answer, &quot;cast your mind back to the Java documentation&quot;:</p><p><a href="https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html#read-byte:A-"><strong>read</strong></a></p><pre><code class="language-java">public int read(byte[] b)
         throws IOException
</code></pre><blockquote><p>Reads up to b.length bytes of data from this input stream into an array of bytes. 👉 <strong>This method blocks until some input is available.</strong> 👈</p></blockquote><p>&quot;And how do you know this is a problem?&quot; you might query. &quot;Well,&quot; I might respond, &quot;um, just &apos;cuz? I mean... I certainly didn&apos;t evaluate this and hang my REPL process and then have to forcibly kill Emacs or anything, because that would be a rookie mistake. Haha.&quot; And then I might laugh nervously and quickly change the subject. &quot;So, how &apos;bout them Yankees?&quot; I might mutter, maybe even looking at my shoes.</p><p>So blerg, what to do, what to do?</p><p>Well, we do know (or at least <strong>can</strong> know) how many bytes are in the file, so maybe we don&apos;t read past the end of the file? Amazing insights you get in this here blog, innit?</p><pre><code class="language-clojure">(defn- read-bytes [f [start end]]
  (let [end (or end (dec (min (fs/size f)
                              (+ start (* 1024 1024)))))
        arr (byte-array (- end start))]
    (with-open [is (java.io.FileInputStream. f)]
      (-&gt; is .getChannel (.position start))
      (.read is arr))
    arr))

(comment

  (let [f manifest-file
        end nil
        end (or end (dec (min (fs/size f) (* 1024 1024))))]
    end)
  ;; =&gt; 457

  ;; Should be safe to do this... 🙈

  (-&gt; (read-bytes manifest-file [0 31])
      (String.))
  ;; =&gt; &quot;{\n    \&quot;name\&quot;: \&quot;Soundcljoud\&quot;,\n   &quot;

  (-&gt; (read-bytes manifest-file [14 29])
      (String.))
  ;; =&gt; &quot;\&quot;Soundcljoud\&quot;,\n &quot;

  ;; Never in doubt... 😌

  )
</code></pre><p>OK, we&apos;re making some progress here. In fact, it seems that we have most of the pieces we&apos;ll need to actually fulfil a range request, so let&apos;s see about sticking them together in a reasonable way.</p><div class="markdown-heading"><h2 id="how-do-you-respond?">How do you respond?</h2><a href="#how-do-you-respond?" class="anchor" aria-label="Permalink: How do you respond?"><img src="assets/link.svg" /></a></div><p>Let&apos;s review what the response to a range request is supposed to look like:</p><pre><code class="language-text">HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Length: 1048576
Content-Range: bytes 0-1048575/5943424
Content-Type: audio/mpeg
</code></pre><p>At the moment, we&apos;re just using the <code>body</code> function to respond to range requests:</p><pre><code class="language-clojure">(defn file-router [dir headers]
  ;; ...
              (cond
                ;; ...
                (and (fs/readable? f) (contains? (:headers req) &quot;range&quot;))
                (do
                  (swap! state update :log conj &quot;Handling range request&quot;)
                  (body f))
                ;; ...
              )
 ;; ...
 )
</code></pre><p>And <code>body</code> just chucks the file into a map with some headers:</p><pre><code class="language-clojure">(defn- body
  ([path]
   (body path {}))
  ([path headers]
   {:headers (merge {&quot;Content-Type&quot; (ext-mime-type (fs/file-name path))} headers)
    :body (fs/file path)}))
</code></pre><p>Let&apos;s follow suit. Since http-kit is so magical and wonderful, we&apos;ll go out on a limb and make the assumption that if we just stuff our byte array into the response body, http-kit will do The Right Thing™.</p><pre><code class="language-clojure">(defn- byte-range
  ([path request-headers]
   (byte-range path request-headers {}))
  ([path request-headers response-headers]
   (let [f (fs/file path)
         [start end
          :as requested-range] (parse-range-header (request-headers &quot;range&quot;))
         arr (read-bytes f requested-range)
         num-bytes-read (count arr)]
     {:status 206
      :headers (merge {&quot;Content-Type&quot; (ext-mime-type (fs/file-name path))
                       &quot;Accept-Ranges&quot; &quot;bytes&quot;
                       &quot;Content-Length&quot; num-bytes-read
                       &quot;Content-Range&quot; (format &quot;bytes %d-%d/%d&quot;
                                               start
                                               (+ start num-bytes-read)
                                               (fs/size f))}
                      response-headers)
      :body arr})))

(comment

  (byte-range manifest-file {&quot;range&quot; &quot;bytes=0-&quot;})
  ;; =&gt; {:status 206,
  ;;     :headers
  ;;     {&quot;Content-Type&quot; nil,
  ;;      &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;      &quot;Content-Length&quot; 458,
  ;;      &quot;Content-Range&quot; &quot;bytes 0-457/458&quot;},
  ;;     :body
  ;;     [123, 10, 32, 32, 32, 32, 34, 110, 97, 109, 101, 34, 58, 32, 34, 83, 111, 117,
  ;;      110, 100, 99, 108, 106, 111, 117, 100, 34, 44, 10, 32, 32, 32, 32, 34, 115,
  ;;      104, 111, 114, 116, 95, 110, 97, 109, 101, 34, 58, 32, 34, 83, 111, 117, 110,
  ;;      100, 99, 108, 106, 111, 117, 100, 34, 44, 10, 32, 32, 32, 32, 34, 105, 99,
  ;;      111, 110, 115, 34, 58, 32, 91, 10, 32, 32, 32, 32, 32, 32, 32, 32, 123, 10,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 114, 99, 34, 58, 32,
  ;;      34, 105, 99, 111, 110, 115, 47, 97, 110, 100, 114, 111, 105, 100, 45, 99,
  ;;      104, 114, 111, 109, 101, 45, 49, 57, 50, 120, 49, 57, 50, 46, 112, 110, 103,
  ;;      34, 44, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 105,
  ;;      122, 101, 115, 34, 58, 32, 34, 49, 57, 50, 120, 49, 57, 50, 34, 44, 10, 32,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 116, 121, 112, 101, 34, 58,
  ;;      32, 34, 105, 109, 97, 103, 101, 47, 112, 110, 103, 34, 10, 32, 32, 32, 32,
  ;;      32, 32, 32, 32, 125, 44, 10, 32, 32, 32, 32, 32, 32, 32, 32, 123, 10, 32, 32,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 114, 99, 34, 58, 32, 34,
  ;;      105, 99, 111, 110, 115, 47, 97, 110, 100, 114, 111, 105, 100, 45, 99, 104,
  ;;      114, 111, 109, 101, 45, 53, 49, 50, 120, 53, 49, 50, 46, 112, 110, 103, 34,
  ;;      44, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 105, 122,
  ;;      101, 115, 34, 58, 32, 34, 53, 49, 50, 120, 53, 49, 50, 34, 44, 10, 32, 32,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 116, 121, 112, 101, 34, 58, 32,
  ;;      34, 105, 109, 97, 103, 101, 47, 112, 110, 103, 34, 10, 32, 32, 32, 32, 32,
  ;;      32, 32, 32, 125, 10, 32, 32, 32, 32, 93, 44, 10, 32, 32, 32, 32, 34, 116,
  ;;      104, 101, 109, 101, 95, 99, 111, 108, 111, 114, 34, 58, 32, 34, 35, 102, 102,
  ;;      102, 102, 102, 102, 34, 44, 10, 32, 32, 32, 32, 34, 98, 97, 99, 107, 103,
  ;;      114, 111, 117, 110, 100, 95, 99, 111, 108, 111, 114, 34, 58, 32, 34, 35, 102,
  ;;      102, 102, 102, 102, 102, 34, 44, 10, 32, 32, 32, 32, 34, 100, 105, 115, 112,
  ;;      108, 97, 121, 34, 58, 32, 34, 115, 116, 97, 110, 100, 97, 108, 111, 110, 101,
  ;;      34, 10, 125, 10]}

  )
</code></pre><p>That looks fairly reasonable. Let&apos;s now complete the plumbing so when we turn on the tap of range requests, we get a delicious stream of ice cold, alpine spring fed responses flowing back:</p><pre><code class="language-clojure">(defn file-router [dir headers]
  ;; ...
              (cond
                ;; ...
                (and (fs/readable? f) (contains? (:headers req) &quot;range&quot;))
                (do
                  (swap! state update :log conj &quot;Handling range request&quot;)
                  (byte-range f (:headers req)))
                ;; ...
              )
 ;; ...
 )

(comment

  ((file-router dir {}) {:headers {&quot;range&quot; &quot;bytes=0-&quot;}
                         :uri &quot;/site.webmanifest&quot;})
  ;; =&gt; {:status 206,
  ;;     :headers
  ;;     {&quot;Content-Type&quot; nil,
  ;;      &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;      &quot;Content-Length&quot; 458,
  ;;      &quot;Content-Range&quot; &quot;bytes 0-457/458&quot;},
  ;;     :body
  ;;     [123, 10, 32, 32, 32, 32, 34, 110, 97, 109, 101, 34, 58, 32, 34, 83, 111, 117,
  ;;      110, 100, 99, 108, 106, 111, 117, 100, 34, 44, 10, 32, 32, 32, 32, 34, 115,
  ;;      104, 111, 114, 116, 95, 110, 97, 109, 101, 34, 58, 32, 34, 83, 111, 117, 110,
  ;;      100, 99, 108, 106, 111, 117, 100, 34, 44, 10, 32, 32, 32, 32, 34, 105, 99,
  ;;      111, 110, 115, 34, 58, 32, 91, 10, 32, 32, 32, 32, 32, 32, 32, 32, 123, 10,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 114, 99, 34, 58, 32,
  ;;      34, 105, 99, 111, 110, 115, 47, 97, 110, 100, 114, 111, 105, 100, 45, 99,
  ;;      104, 114, 111, 109, 101, 45, 49, 57, 50, 120, 49, 57, 50, 46, 112, 110, 103,
  ;;      34, 44, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 105,
  ;;      122, 101, 115, 34, 58, 32, 34, 49, 57, 50, 120, 49, 57, 50, 34, 44, 10, 32,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 116, 121, 112, 101, 34, 58,
  ;;      32, 34, 105, 109, 97, 103, 101, 47, 112, 110, 103, 34, 10, 32, 32, 32, 32,
  ;;      32, 32, 32, 32, 125, 44, 10, 32, 32, 32, 32, 32, 32, 32, 32, 123, 10, 32, 32,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 114, 99, 34, 58, 32, 34,
  ;;      105, 99, 111, 110, 115, 47, 97, 110, 100, 114, 111, 105, 100, 45, 99, 104,
  ;;      114, 111, 109, 101, 45, 53, 49, 50, 120, 53, 49, 50, 46, 112, 110, 103, 34,
  ;;      44, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 115, 105, 122,
  ;;      101, 115, 34, 58, 32, 34, 53, 49, 50, 120, 53, 49, 50, 34, 44, 10, 32, 32,
  ;;      32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 116, 121, 112, 101, 34, 58, 32,
  ;;      34, 105, 109, 97, 103, 101, 47, 112, 110, 103, 34, 10, 32, 32, 32, 32, 32,
  ;;      32, 32, 32, 125, 10, 32, 32, 32, 32, 93, 44, 10, 32, 32, 32, 32, 34, 116,
  ;;      104, 101, 109, 101, 95, 99, 111, 108, 111, 114, 34, 58, 32, 34, 35, 102, 102,
  ;;      102, 102, 102, 102, 34, 44, 10, 32, 32, 32, 32, 34, 98, 97, 99, 107, 103,
  ;;      114, 111, 117, 110, 100, 95, 99, 111, 108, 111, 114, 34, 58, 32, 34, 35, 102,
  ;;      102, 102, 102, 102, 102, 34, 44, 10, 32, 32, 32, 32, 34, 100, 105, 115, 112,
  ;;      108, 97, 121, 34, 58, 32, 34, 115, 116, 97, 110, 100, 97, 108, 111, 110, 101,
  ;;      34, 10, 125, 10]}

  )
</code></pre><p>Looks great... except for the <code>Content-Type: nil</code> bit, since our server has no clue what a <code>.webmanifest</code> extension portends, but who cares about such trivial details, since we&apos;re not gonna be getting range requests for non-media files anyway. Plus, a standard request for that file does the same thing:</p><pre><code class="language-clojure">(comment

  ((file-router dir {}) {:headers {}
                         :uri &quot;/site.webmanifest&quot;})
  ;; =&gt; {:headers {&quot;Content-Type&quot; nil},
  ;;     :body
  ;;     #object[java.io.File 0x659969c9 &quot;../soundcljoud/player/public/site.webmanifest&quot;]}

  )
</code></pre><p>🤷</p><p>Before we break out the 🍾 though, let&apos;s try this in the wild. And before we try this in the wild, it probably behoves us—at least, I feel rather behoved, and it&apos;s my blog, so I&apos;m going to follow this deep sense of behoval where it leads—to log responses as well as requests, so let&apos;s make one last minor change to good &apos;ol <code>file-router</code>:</p><pre><code class="language-clojure">(defn file-router [dir headers]
  (fn [{:keys [uri] :as req}]
    ;; 👉 Move the state swappage from here...
    (let [f (fs/path dir (str/replace-first (URLDecoder/decode uri) #&quot;^/&quot; &quot;&quot;))
          index-file (fs/path f &quot;index.html&quot;)
          res
          (update (cond
                    (and (fs/directory? f) (fs/readable? index-file))
                    (body index-file)

                    (fs/directory? f)
                    (index dir f)

                    (and (fs/readable? f) (contains? (:headers req) &quot;range&quot;))
                    (do
                      (swap! state update :log conj &quot;Handling range request&quot;)
                      (byte-range f (:headers req)))

                    (fs/readable? f)
                    (body f)

                    (and (nil? (fs/extension f)) (fs/readable? (with-ext f &quot;.html&quot;)))
                    (body (with-ext f &quot;.html&quot;) headers)

                    :else
                    {:status 404 :body (str &quot;Not found `&quot; f &quot;` in &quot; dir)})
                  :headers (fn [response-headers]
                             (merge headers response-headers)))]
      ;; ...to here 👇
      (swap! state
             update :requests
             conj {:request req, :response (dissoc res :body)})
      res)))
</code></pre><div class="markdown-heading"><h2 id="i&apos;m-the-one-that-put-the-range-in-the-rover">I&apos;m the one that put the Range in the Rover</h2><a href="#i&apos;m-the-one-that-put-the-range-in-the-rover" class="anchor" aria-label="Permalink: I&apos;m the one that put the Range in the Rover"><img src="assets/link.svg" /></a></div><p>Casting our minds back to <a href="2024-07-20-soundcljoud-cloudy.html#is_this_the_end%3F">the last post in this potentially infinite sequence
of posts</a>, we recall that Soundcljoud was unable to seek in the audio file. Let&apos;s repeat this experience by jumping over to <code>soundcljoud/player/public/soundcljoud.cljs</code>:</p><pre><code class="language-clojure">(comment

  (-&gt; (get-el &quot;audio&quot;)
      (.-seekable)
      (.-length))
  ;; =&gt; 1

  (let [s (-&gt; (get-el &quot;audio&quot;)
              (.-seekable))]
    [(.start s 0) (.end s 0)])
  ;; =&gt; [0 0]
  
  )
</code></pre><p>This is what we expected, since we haven&apos;t restarted the server to apply our changes. Let&apos;s do that now (back in our http-server REPL):</p><pre><code class="language-clojure">(comment

  (restart-server)
  ;; =&gt; {:requests [],
  ;;     :log [],
  ;;     :server
  ;;     #object[clojure.lang.AFunction$1 0x2d75d828 &quot;clojure.lang.AFunction$1@2d75d828&quot;]}

  )
</code></pre><p>Now we can click on another track in Soundcljoud and see what happens. 😬</p><p><img alt="Clicking on a track in the Soundcljoud UI" src="assets/2024-08-13-soundcljoud-rangey-hope.png" title="It&apos;s the hope that kills" class="border" /></p><p>OK, nothing blew up. Let&apos;s look at the request in the http-server logs:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (:requests @state)
       (filter #(str/ends-with? (get-in % [:request :uri]) &quot;.mp3&quot;))
       (map (fn [{:keys [request response]}]
              {:request {:uri (:uri request)
                         :headers (select-keys (:headers request)
                                               [&quot;range&quot;])}
               :response response})))
  ;; =&gt; ({:request
  ;;      {:uri
  ;;       &quot;/Garth%20Brooks/Fresh%20Horses/Garth%20Brooks%20-%20It%27s%20Midnight%20Cinderella.mp3&quot;,
  ;;       :headers {&quot;range&quot; &quot;bytes=0-&quot;}},
  ;;      :response
  ;;      {:status 206,
  ;;       :headers
  ;;       {&quot;Content-Type&quot; &quot;audio/mpeg&quot;,
  ;;        &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;        &quot;Content-Length&quot; 1048576,
  ;;        &quot;Content-Range&quot; &quot;bytes 0-1048575/3426432&quot;}}})

  )
</code></pre><p>So far, so good. But if we now seek, can we find? Let&apos;s ask in our Soundcljoud REPL:</p><pre><code class="language-clojure">(comment

  (let [seekable (-&gt; (get-el &quot;audio&quot;) (.-seekable))]
    (-&gt;&gt; (.-length seekable)
         range
         (map (fn [i]
                [(.start seekable i) (.end seekable i)]))))
  ;; =&gt; ([0 142.654694])
  
  )
</code></pre><p>And if we actually click play? OMG we hear the sweet sweet sounds of a steel guitar! And if we seek forward in the track? Garth sings! Let&apos;s just check in with http-server one last time to see what it thinks:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (:requests @state)
       (filter #(str/ends-with? (get-in % [:request :uri]) &quot;.mp3&quot;))
       (map (fn [{:keys [request response]}]
              {:request {:uri (:uri request)
                         :headers (select-keys (:headers request)
                                               [&quot;range&quot;])}
               :response response})))
  ;; =&gt; ({:request
  ;;      {:uri
  ;;       &quot;/Garth%20Brooks/Fresh%20Horses/Garth%20Brooks%20-%20It%27s%20Midnight%20Cinderella.mp3&quot;,
  ;;       :headers {&quot;range&quot; &quot;bytes=0-&quot;}},
  ;;      :response
  ;;      {:status 206,
  ;;       :headers
  ;;       {&quot;Content-Type&quot; &quot;audio/mpeg&quot;,
  ;;        &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;        &quot;Content-Length&quot; 1048575,
  ;;        &quot;Content-Range&quot; &quot;bytes 0-1048575/3426432&quot;}}}
  ;;     {:request
  ;;      {:uri
  ;;       &quot;/Garth%20Brooks/Fresh%20Horses/Garth%20Brooks%20-%20It%27s%20Midnight%20Cinderella.mp3&quot;,
  ;;       :headers {&quot;range&quot; &quot;bytes=0-&quot;}},
  ;;      :response
  ;;      {:status 206,
  ;;       :headers
  ;;       {&quot;Content-Type&quot; &quot;audio/mpeg&quot;,
  ;;        &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;        &quot;Content-Length&quot; 1048575,
  ;;        &quot;Content-Range&quot; &quot;bytes 0-1048575/3426432&quot;}}}
  ;;     {:request
  ;;      {:uri
  ;;       &quot;/Garth%20Brooks/Fresh%20Horses/Garth%20Brooks%20-%20It%27s%20Midnight%20Cinderella.mp3&quot;,
  ;;       :headers {&quot;range&quot; &quot;bytes=1048575-&quot;}},
  ;;      :response
  ;;      {:status 206,
  ;;       :headers
  ;;       {&quot;Content-Type&quot; &quot;audio/mpeg&quot;,
  ;;        &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;        &quot;Content-Length&quot; 1048575,
  ;;        &quot;Content-Range&quot; &quot;bytes 1048575-2097150/3426432&quot;}}}
  ;;     {:request
  ;;      {:uri
  ;;       &quot;/Garth%20Brooks/Fresh%20Horses/Garth%20Brooks%20-%20It%27s%20Midnight%20Cinderella.mp3&quot;,
  ;;       :headers {&quot;range&quot; &quot;bytes=2097150-&quot;}},
  ;;      :response
  ;;      {:status 206,
  ;;       :headers
  ;;       {&quot;Content-Type&quot; &quot;audio/mpeg&quot;,
  ;;        &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;        &quot;Content-Length&quot; 1048575,
  ;;        &quot;Content-Range&quot; &quot;bytes 2097150-3145725/3426432&quot;}}}
  ;;     {:request
  ;;      {:uri
  ;;       &quot;/Garth%20Brooks/Fresh%20Horses/Garth%20Brooks%20-%20It%27s%20Midnight%20Cinderella.mp3&quot;,
  ;;       :headers {&quot;range&quot; &quot;bytes=3145725-&quot;}},
  ;;      :response
  ;;      {:status 206,
  ;;       :headers
  ;;       {&quot;Content-Type&quot; &quot;audio/mpeg&quot;,
  ;;        &quot;Accept-Ranges&quot; &quot;bytes&quot;,
  ;;        &quot;Content-Length&quot; 280706,
  ;;        &quot;Content-Range&quot; &quot;bytes 3145725-3426431/3426432&quot;}}})

  )
</code></pre><p>Now that, my friends, smells like the sweet sweet smell of...</p><p><img alt="A woman on a beach at sunrise with her head thrown back, saying &quot;Victory&quot;" src="assets/2024-08-13-victory.jpg" title="Never in doubt" /></p><p>Ah... it&apos;s been a while since I&apos;ve been able to use that lovely image. 🌅</p><div class="markdown-heading"><h2 id="is-this-the-end?">Is this the end?</h2><a href="#is-this-the-end?" class="anchor" aria-label="Permalink: Is this the end?"><img src="assets/link.svg" /></a></div><p>Well... the fact that I&apos;m asking this rhetorical question points to the answer likely being &quot;no&quot;. 😅</p><p>And in fact it isn&apos;t the end, because I feel (perhaps arrogantly so) that this range support could be useful to others using babashka.http-server, so I should probably open up a pull request for the <a href="https://github.com/borkdude">borkiest of
dudes</a> to review. I&apos;ll quickly <a href="https://github.com/jmglov/http-server">fork http-server</a> on Github, then update my remotes in <a href="https://magit.vc/">magit</a> to make <code>origin</code> point to <code>git@github.com:jmglov/http-server.git</code> and <code>upstream</code> point to <code>git@github.com:babashka/http-server.git</code>, stash my changes, create a <code>range-requests</code> branch, then pop the stash.</p><p>I doubt Señor Borkdude will be terribly impressed by my <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a> and state atom, so I&apos;d better go ahead and remove that nonsense before committing. I&apos;ll open a <a href="https://github.com/babashka/http-server/issues/16">feature
request</a> on the Github project as well, since I know this is how Borkdude prefers to work.</p><p>With this, I have a fairly minimal commit that I&apos;m ready to subject to the slings and arrows of outrageous fortune that are part of any Borkdude code review:</p><pre><code class="language-diff">range-requests a87a841e02d362ae8dc346153b166d28882c3c6e
Author:     Josh Glover &lt;jmglov@jmglov.net&gt;
AuthorDate: Tue Aug 13 14:18:47 2024 +0200
Commit:     Josh Glover &lt;jmglov@jmglov.net&gt;
CommitDate: Tue Aug 13 17:08:31 2024 +0200

Support range requests

2 files changed, 42 insertions(+)
CHANGELOG.md                 |  4 ++++
src/babashka/http_server.clj | 38 ++++++++++++++++++++++++++++++++++++++

modified   CHANGELOG.md
@@ -2,6 +2,10 @@
 
 [Http-server](https://github.com/babashka/http-server): Serve static assets with [babashka](https://babashka.org/)
 
+## Unreleased
+
+- [#16](https://github.com/babashka/http-server/issues/16): support range requests
+
 ## 0.1.13
 
 - [#13](https://github.com/babashka/http-server/issues/13): add an ending slash to the dir link, and don&apos;t encode the slashes ([@KDr2](https://github.com/KDr2))
modified   src/babashka/http_server.clj
@@ -165,6 +165,41 @@
    {:headers (merge {&quot;Content-Type&quot; (ext-mime-type (fs/file-name path))} headers)
     :body (fs/file path)}))
 
+(defn- parse-range-header [range-header]
+  (map #(when % (Long/parseLong %))
+       (-&gt; range-header
+           (str/replace #&quot;^bytes=&quot; &quot;&quot;)
+           (str/split #&quot;-&quot;))))
+
+(defn- read-bytes [f [start end]]
+  (let [end (or end (dec (min (fs/size f)
+                              (+ start (* 1024 1024)))))
+        arr (byte-array (- end start))]
+    (with-open [is (java.io.FileInputStream. f)]
+      (-&gt; is .getChannel (.position start))
+      (.read is arr))
+    arr))
+
+(defn- byte-range
+  ([path request-headers]
+   (byte-range path request-headers {}))
+  ([path request-headers response-headers]
+   (let [f (fs/file path)
+         [start end
+          :as requested-range] (parse-range-header (request-headers &quot;range&quot;))
+         arr (read-bytes f requested-range)
+         num-bytes-read (count arr)]
+     {:status 206
+      :headers (merge {&quot;Content-Type&quot; (ext-mime-type (fs/file-name path))
+                       &quot;Accept-Ranges&quot; &quot;bytes&quot;
+                       &quot;Content-Length&quot; num-bytes-read
+                       &quot;Content-Range&quot; (format &quot;bytes %d-%d/%d&quot;
+                                               start
+                                               (+ start num-bytes-read)
+                                               (fs/size f))}
+                      response-headers)
+      :body arr})))
+
 (defn- with-ext [path ext]
   (fs/path (fs/parent path) (str (fs/file-name path) ext)))
 
@@ -179,6 +214,9 @@
                 (fs/directory? f)
                 (index dir f)
 
+                (and (fs/readable? f) (contains? (:headers req) &quot;range&quot;))
+                (byte-range f (:headers req))
+
                 (fs/readable? f)
                 (body f)
</code></pre><p>Wish me well, folks! If I&apos;m not heard from again, you&apos;ll know that my <a href="https://github.com/babashka/http-server/pull/17">pull
request</a> was found to be sub-par and I was sent to Java Jail to work on an enterprise workflow management system. 😭</p><div class="markdown-heading"><h1 id="ok-but-now-are-we-done?">OK but now are we done?</h1><a href="#ok-but-now-are-we-done?" class="anchor" aria-label="Permalink: OK but now are we done?"><img src="assets/link.svg" /></a></div><p>Soundcljoud has clearly now implemented the critical functionality of Soundcloud, so I could call it a day, but I&apos;m loathe to do that when I could instead extend it to be the best podcast player that ever was! Maybe I&apos;ll rebrand it OverClj... or better yet, CljerCast! VCs, get your wallets ready and stay posted for the next instalment of the exciting Soundcljoud series, right here on jmglov.net!</p><p>Previously on Soundcljoud:</p><ul><li>Part 1: <a href="2024-07-09-soundcljoud.html">Soundcljoud, or a young man&apos;s Soundcloud
clonejure</a></li><li>Part 2: <a href="2024-07-20-soundcljoud-cloudy.html">Soundcljoud gets more
cloudy</a></li></ul><div class="markdown-heading"><h2 id="photo-credits">Photo credits</h2><a href="#photo-credits" class="anchor" aria-label="Permalink: Photo credits"><img src="assets/link.svg" /></a></div><p>What&apos;s Going on with that Body cover art:</p><ul><li>Mashup by Josh Glover</li><li>Concert photo by <a href="https://unsplash.com/photos/people-watching-concert-Jb7TLs6fW_I">Andre Benz on
Unsplash</a></li><li>Photo of Pitbull by Photobra Adam Bielawski - Own work, CC BY-SA 3.0 <a href="https://commons.wikimedia.org/w/index.php?curid=14736058">https://commons.wikimedia.org/w/index.php?curid=14736058</a></li><li>Photo of Nicki Minaj by Rory from Glasgow, United Kingdom - IMG_4388, CC BY 2.0 <a href="https://commons.wikimedia.org/w/index.php?curid=115814812">https://commons.wikimedia.org/w/index.php?curid=115814812</a></li></ul></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-07-20-soundcljoud-cloudy.html</id>
    <link href="https://jmglov.net/blog/2024-07-20-soundcljoud-cloudy.html"/>
    <title>Soundcljoud gets more cloudy</title>
    <updated>2024-07-20T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="A logo of a face wearing a red hoodie with orange sunglasses featuring the Soundcloud logo" src="assets/2024-07-20-soundcljoud-bb.png" title="Above the clouds, infinite skills create miracles" /></p><p><a href="2024-07-09-soundcljoud.html">Last time</a> on &quot;Soundcljoud, or a young man&apos;s Soundcloud clonejure&quot;, I promised to clone Soundcloud, but then got bogged down in telling <a href="2024-07-09-soundcljoud.html#rambling_exposition">the story of my
life</a> and never got around to the actual cloning part. 😬</p><p>To be fair to myself, I did do <a href="2024-07-09-soundcljoud.html#omg_finally_stuff_about_clojure">a bunch of
stuff</a> to prepare for cloning, so now we can get to it with no further ado! (Skipping the ado bit is very out of character for me, I know. I&apos;ll just claim this parenthetical as my ado and thus fulfil your expectations of me as the most verbose writer in the Clojure community. You&apos;re welcome!)</p><div class="markdown-heading"><h2 id="popping-in-a-scittle">Popping in a Scittle</h2><a href="#popping-in-a-scittle" class="anchor" aria-label="Permalink: Popping in a Scittle"><img src="assets/link.svg" /></a></div><p>If you&apos;ve followed along with any of <a href="tags/clonejure.html">my other cloning
adventures</a>, you&apos;ll know where I&apos;m going with this: straight to <a href="https://github.com/babashka/scittle/">Scittle</a> Town!</p><p>I&apos;ll start by creating a <code>player</code> directory and dropping a <code>bb.edn</code> into it:</p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;2f8a9ed2d39a1b09d2b4d34d95494b56468f4a23&quot;}
        io.github.babashka/http-server
        {:git/sha &quot;b38c1f16ad2c618adae2c3b102a5520c261a7dd3&quot;}}
 :tasks {http-server {:doc &quot;Starts http server for serving static files&quot;
                      :requires ([babashka.http-server :as http])
                      :task (do (http/serve {:port 1341 :dir &quot;public&quot;})
                                (println &quot;Serving static assets at http://localhost:1341&quot;))}

         browser-nrepl {:doc &quot;Start browser nREPL&quot;
                        :requires ([sci.nrepl.browser-server :as bp])
                        :task (bp/start! {})}

         -dev {:depends [http-server browser-nrepl]}

         dev {:task (do (run &apos;-dev {:parallel true})
                        (deref (promise)))}}}
</code></pre><p>In short, what&apos;s happening here is I&apos;m setting up a Babashka project with a <code>dev</code> task that starts a webserver on port 1341 serving up the files in the <code>public/</code> directory, starts an nREPL server on port 1339 that we can connect to with Emacs (or any inferior text editor of your choosing), and a websocket server on port 1340 that is connected to the nREPL server on one end and waiting for a ClojureScript app to connect to the other end.</p><p>Speaking of the <code>public/</code> directory, I need a <code>public/index.html</code> file to serve up:</p><pre><code class="language-html">&lt;!doctype html&gt;
&lt;html class=&quot;no-js&quot; lang=&quot;&quot;&gt;

&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;title&gt;Soundcljoud&lt;/title&gt;
    &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;

    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.promesa.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script&gt;var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.nrepl.js&quot;
        type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;application/x-scittle&quot; src=&quot;soundcljoud.cljs&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;h1&gt;Soundcljoud&lt;/h1&gt;
  &lt;div id=&quot;wrapper&quot; style=&quot;display: none;&quot;&gt;
    &lt;div id=&quot;player&quot;&gt;
      &lt;div class=&quot;cover-image&quot;&gt;
        &lt;img src=&quot;&quot; alt=&quot;&quot; /&gt;
      &lt;/div&gt;
      &lt;div id=&quot;controls&quot;&gt;
        &lt;audio controls src=&quot;&quot;&gt;&lt;/audio&gt;
        &lt;div id=&quot;tracks&quot; style=&quot;&quot;&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>The <code>index.html</code> file loads three JavaScript scripts:</p><ol start="1"><li>Scittle itself, which knows how to interpret ClojureScript scripts</li><li>The Scittle <a href="https://github.com/funcool/promesa">Promesa</a> plugin, which provides some niceties for dealing with promises</li><li>The Scittle nREPL plugin, which will connect to that websocket server on port 1340 and complete the circuit that will allow us to REPL-drive our browser from Emacs (or the inferior text editor of your choosing)</li></ol><p>Once this JavaScript is in place, <code>index.html</code> loads the <code>soundcljoud.cljs</code> ClojureScript file, which we&apos;ll come to in just a second.</p><p>For a (much) more detailed explanation, refer to the <a href="2024-02-22-cljcastr.html#popping_in_a_scittle">Popping in a
Scittle</a> section of my <a href="2024-02-22-cljcastr.html">cljcastr,
or a young man&apos;s Zencastr clonejure</a> blog post.</p><p>The body of <code>index.html</code> is all about setting up a basic HTML page with this structure:</p><pre><code class="language-text">+----------------------+
| Soundcljoud          |
+-------+--------------+  &lt;---
| Album | Audio player |      }
| cover +--------------+      } &lt;div id=&quot;wrapper&quot;&gt;
| image | Tracks list  |      }
+-------+--------------+  &lt;---
</code></pre><p>Note that everything inside the wrapper div is hidden from the start:</p><pre><code class="language-html">  &lt;div id=&quot;wrapper&quot; style=&quot;display: none;&quot;&gt;
</code></pre><p>We don&apos;t know anything about the album we want to display yet, and there&apos;s no point in showing a bunch of empty divs until we do.</p><p>Let&apos;s drop a <code>public/style.css</code> in as well:</p><pre><code class="language-css">body {
  font:
    1.2em Helvetica,
    Arial,
    sans-serif;
  margin: 20px;
  padding: 0;
}

img {
  max-width: 100%;
}

#wrapper {
  max-width: 960px;
  margin: 2em auto;
}

#controls {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

#tracks {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

@media screen and (min-width: 900px) {
  #wrapper {
    display: flex;
  }

  #player {
    display: flex;
    gap: 3%;
  }

  #cover-image {
    margin-right: 5%;
    max-width: 60%;
  }

  #controls {
    width: 25%;
  }
}
</code></pre><p>All of this stuff is about using screen real estate effectively. The first chunk of CSS applies universally, but the bit inside this:</p><pre><code class="language-css">@media screen and (min-width: 900px) {
  /* ... */
}
</code></pre><p>only applies to windows at least 900px wide. So our page defaults to a layout that&apos;s appropriate for phones (or really narrow browser windows), but then adjusts to move more content &quot;above the fold&quot; so you can probably see the entire UI without scrolling if you&apos;re viewing the page on a standard computer.</p><p>Now that we have all of the HTML and CSS plumbing in place, let&apos;s add a <code>public/soundcljoud.cljs</code> file to get started with some ClojureScripting:</p><pre><code class="language-clojure">(ns soundcljoud
  (:require [promesa.core :as p]))
</code></pre><div class="markdown-heading"><h2 id="firing-up-the-repl">Firing up the REPL</h2><a href="#firing-up-the-repl" class="anchor" aria-label="Permalink: Firing up the REPL"><img src="assets/link.svg" /></a></div><p>Before we can start REPL-driving, we need to put the key in the ignition and give it a right twist! In other words, we open up a terminal in the top-level <code>player/</code> directory and invoke Babashka:</p><pre><code class="language-text">: jmglov@alhana; bb dev
Serving static assets at http://localhost:1341
nREPL server started on port 1339...
Websocket server started on 1340...
</code></pre><p>If we now connect to <a href="http://localhost:1341/">http://localhost:1341/</a>, we&apos;ll be rewarded with a simple webpage:</p><p><img alt="Screenshot of a web browser window saying Soundcljoud" src="assets/2024-07-20-soundcljoud-cloudy-boring.png" title="All that buildup for this?" class="border" /></p><p>This by itself is of course monumentally boring, so let&apos;s inject some excitement into our lives by jumping into <code>soundcljoud.cljs</code> and pressing <code>C-c l C</code> (<code>cider-connect-cljs</code>), selecting <code>localhost</code>, port 1339, and <code>nbb</code> for the REPL type (assuming you&apos;re in Emacs; if you&apos;re using some other editor, perform the incantations necessary to connect your ClojureScript REPL to localhost:1339).</p><p>If everything went according to plan, you should see something like this in your terminal window:</p><pre><code class="language-text">:msg &quot;{:versions
       {\&quot;scittle-nrepl\&quot;
        {\&quot;major\&quot; \&quot;0\&quot;, \&quot;minor\&quot; \&quot;0\&quot;, \&quot;incremental\&quot; \&quot;1\&quot;}},
       :ops
       {\&quot;complete\&quot; {}, \&quot;info\&quot; {}, \&quot;lookup\&quot; {}, \&quot;eval\&quot; {},
        \&quot;load-file\&quot; {}, \&quot;describe\&quot; {}, \&quot;close\&quot; {}, \&quot;clone\&quot; {},
        \&quot;eldoc\&quot; {}},
       :status [\&quot;done\&quot;],
       :id \&quot;3\&quot;,
       :session \&quot;3264dc1e-1b46-48a6-b11a-f606fea032b7\&quot;,
       :ns \&quot;soundcljoud\&quot;}&quot;
:msg &quot;{:value \&quot;nil\&quot;,
       :id \&quot;5\&quot;,
       :session \&quot;3264dc1e-1b46-48a6-b11a-f606fea032b7\&quot;,
       :ns \&quot;soundcljoud\&quot;}&quot;
:msg &quot;{:status [\&quot;done\&quot;],
       :id \&quot;5\&quot;,
       :session \&quot;3264dc1e-1b46-48a6-b11a-f606fea032b7\&quot;,
       :ns \&quot;soundcljoud\&quot;}&quot;
</code></pre><p>And something like this in your editor&apos;s REPL window:</p><pre><code class="language-text">;; Connected to nREPL server - nrepl://localhost:1339
;; CIDER 1.12.0 (Split)
;;
;; ClojureScript REPL type: nbb
;;
nil&gt; 
</code></pre><p>Let&apos;s prove that it works by evaluating the buffer with <code>C-c C-k</code> (<code>cider-load-buffer</code>), adding a <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a>, putting some ClojureScript in there that grabs our wrapper div, positioning our cursor at the end of the form, and evaluating that sucker with <code>C-c C-v f c e</code> (<code>cider-pprint-eval-last-sexp-to-comment</code>):</p><pre><code class="language-clojure">(ns soundcljoud
  (:require [promesa.core :as p]))

(comment

  (js/document.querySelector &quot;#wrapper&quot;)
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

)
</code></pre><p>We&apos;ve proven that we can evaluate ClojureScript code in the running browser process from our REPL buffer, which is nifty for sure, but our page still bores us, and the result of evaluating that code is pretty useless:</p><pre><code class="language-text">#object[HTMLDivElement [object HTMLDivElement]]
</code></pre><p>Let&apos;s actually do something with the div we&apos;ve pulled down, and whilst we&apos;re at it, provide a useful way of logging stuff:</p><pre><code class="language-clojure">(ns soundcljoud
  (:require [promesa.core :as p]))

(defn log
  ([msg]
   (log msg nil))
  ([msg obj]
   (if obj
     (js/console.log msg obj)
     (js/console.log msg))
   obj))

(comment

  (let [div (js/document.querySelector &quot;#wrapper&quot;)]
    (set! (.-style div) &quot;display: flex&quot;)
    (log &quot;All is revealed!&quot; div))
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

)
</code></pre><p><img alt="Screenshot of a web browser window with an audio player" src="assets/2024-07-20-soundcljoud-cloudy-revealed.png" title="Players players everywhere but not a track to play!" class="border" /></p><p>Fantastic! By using <code>js/document.log</code> (by the way, that <code>js/</code> prefix is the way you instruct ClojureScript to do some JavaScript interop; it&apos;s basically saying &quot;look for the next symbol in the top-level scope in JavaScript land&quot;), we now get the fancy inspection tools in the browser&apos;s JavaScript console so we can expand parts of the object and drill down to see stuff we&apos;re interested in.</p><p>Now that we&apos;ve established a baseline, we can get stuck in and do some real work. 💪🏻</p><div class="markdown-heading"><h2 id="reading-some-rss">Reading some RSS</h2><a href="#reading-some-rss" class="anchor" aria-label="Permalink: Reading some RSS"><img src="assets/link.svg" /></a></div><p>Do you remember the <a href="2024-07-09-soundcljoud.html#converting_from_ogg_to_mp3">MP3 files and RSS
feed</a> we prepared in the previous blog post? Let&apos;s plop those down in our <code>public/</code> directory so we can access them from the webapp we&apos;re slowly constructing:</p><pre><code class="language-text">: jmglov@alhana; mkdir -p &apos;public/Garth Brooks/Fresh Horses&apos;

: jmglov@alhana; cp /tmp/soundcljoud.12524185230907219576/*.{rss,mp3} !$

: jmglov@alhana; ls -1 !$
album.rss
&apos;Garth Brooks - Cowboys and Angels.mp3&apos;
&apos;Garth Brooks - Ireland.mp3&apos;
&quot;Garth Brooks - It&apos;s Midnight Cinderella.mp3&quot;
&quot;Garth Brooks - Rollin&apos;.mp3&quot;
&quot;Garth Brooks - She&apos;s Every Woman.mp3&quot;
&quot;Garth Brooks - That Ol&apos; Wind.mp3&quot;
&apos;Garth Brooks - The Beaches of Cheyenne.mp3&apos;
&apos;Garth Brooks - The Change.mp3&apos;
&apos;Garth Brooks - The Fever.mp3&apos;
&apos;Garth Brooks - The Old Stuff.mp3&apos;
</code></pre><p>Now that our files are in place, let&apos;s see about loading the RSS feed from ClojureScript:</p><pre><code class="language-clojure">(comment

  (def base-path &quot;/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&apos;soundcljoud/base-path

  (p/-&gt;&gt; (js/fetch (js/Request. (str base-path &quot;/album.rss&quot;)))
         (.text)
         (log &quot;Fetched XML:&quot;))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>In our console, we can see what we fetched:</p><pre><code class="language-text">Fetched XML: &lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;
&lt;rss version=&quot;2.0&quot;
     xmlns:itunes=&quot;http://www.itunes.com/dtds/podcast-1.0.dtd&quot;
     xmlns:atom=&quot;http://www.w3.org/2005/Atom&quot;&gt;
  &lt;channel&gt;
    &lt;atom:link
        href=&quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/album.rss&quot;
        rel=&quot;self&quot;
        type=&quot;application/rss+xml&quot;/&gt;
    &lt;title&gt;Garth Brooks - Fresh Horses&lt;/title&gt;
    &lt;link&gt;https://api.discogs.com/masters/212114&lt;/link&gt;
    &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
    &lt;itunes:subtitle&gt;Album: Garth Brooks - Fresh Horses&lt;/itunes:subtitle&gt;
    &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
    &lt;itunes:image href=&quot;https://i.discogs.com/0eLXmM1tK1grkH8cstgDT6eV2TlL0NvgWPZBoyScJ_8/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTY4NDcx/Ny0xNzE3NDU5MDIy/LTMxNjguanBlZw.jpeg&quot;/&gt;
    
    &lt;item&gt;
      &lt;itunes:title&gt;The Old Stuff&lt;/itunes:title&gt;
      &lt;title&gt;The Old Stuff&lt;/title&gt;
      &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
      &lt;enclosure
          url=&quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+The+Old+Stuff.mp3&quot;
          length=&quot;5943424&quot; type=&quot;audio/mpeg&quot; /&gt;
      &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
      &lt;itunes:duration&gt;252&lt;/itunes:duration&gt;
      &lt;itunes:episode&gt;1&lt;/itunes:episode&gt;
      &lt;itunes:episodeType&gt;full&lt;/itunes:episodeType&gt;
      &lt;itunes:explicit&gt;false&lt;/itunes:explicit&gt;
    &lt;/item&gt;
   ... 
    &lt;item&gt;
      &lt;itunes:title&gt;Ireland&lt;/itunes:title&gt;
      &lt;title&gt;Ireland&lt;/title&gt;
      &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
      &lt;enclosure
          url=&quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+Ireland.mp3&quot;
          length=&quot;6969472&quot; type=&quot;audio/mpeg&quot; /&gt;
      &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
      &lt;itunes:duration&gt;301&lt;/itunes:duration&gt;
      &lt;itunes:episode&gt;10&lt;/itunes:episode&gt;
      &lt;itunes:episodeType&gt;full&lt;/itunes:episodeType&gt;
      &lt;itunes:explicit&gt;false&lt;/itunes:explicit&gt;
    &lt;/item&gt;
    
  &lt;/channel&gt;
&lt;/rss&gt;
</code></pre><p>That looks quite familiar! That also looks like a bunch of text, which is not the nicest thing to extract data from. Luckily, that&apos;s a bunch of structured text, and more luckily, it&apos;s XML (XML is great, and don&apos;t let anyone tell you otherwise! And don&apos;t get me started on how we&apos;ve reinvented XML but poorly with JSON Schema and all of this other nonsense we&apos;ve built up around JSON because we realised that things like data validation are important when exchanging data between machines. 🤦🏼‍♂️), and most luckily of all, browsers know how to parse XML (which makes sense, as modern HTML is in fact XML):</p><pre><code class="language-clojure">(defn parse-xml [xml-str]
  (.parseFromString (js/window.DOMParser.) xml-str &quot;text/xml&quot;))

(comment

  (p/-&gt;&gt; (js/fetch (js/Request. (str base-path &quot;/album.rss&quot;)))
         (.text)
         parse-xml
         (log &quot;Fetched XML:&quot;))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p><img alt="Screenshot of a web browser window with an XML document in the JS console" src="assets/2024-07-20-soundcljoud-cloudy-xml.png" title="XML, anyone?" class="border" /></p><p>Let&apos;s do the right thing and make a function out of this:</p><pre><code class="language-clojure">(defn fetch-xml [path]
  (p/-&gt;&gt; (js/fetch (js/Request. path))
         (.text)
         parse-xml
         (log &quot;Fetched XML:&quot;)))
</code></pre><p>Now that we know how to fetch and parse XML, let&apos;s see how to extract useful information from it. Looking at the log output, we can see that the parsed XML is of type <code>#document</code>, just like our good friend <code>js/document</code> (the current webpage that the browser is displaying). That&apos;s right, we have a Document Object Model, which means we can use all the tasty DOM functions we&apos;re used to, such as <code>document.querySelector()</code> to grab a node using an XPATH query.</p><p>Let&apos;s start with the album title:</p><pre><code class="language-clojure">(comment

  (p/let [title (p/-&gt; (fetch-xml (str base-path &quot;/album.rss&quot;))
                      (.querySelector &quot;title&quot;)
                      (.-innerHTML))]
    (set! (.-innerHTML (js/document.querySelector &quot;h1&quot;)) title))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>Cool! We now see &quot;Garth Brooks - Fresh Horses&quot; as our page heading! Let&apos;s see about grabbing the album art next:</p><pre><code class="language-clojure">(comment

  (p/let [xml (fetch-xml (str base-path &quot;/album.rss&quot;))
          title (p/-&gt; xml
                      (.querySelector &quot;title&quot;)
                      (.-innerHTML))
          image (p/-&gt; xml
                      (.querySelector &quot;image&quot;)
                      (.getAttribute &quot;href&quot;))]
    (set! (.-innerHTML (js/document.querySelector &quot;h1&quot;)) title)
    (set! (.-src (js/document.querySelector &quot;.cover-image &gt; img&quot;)) image)
    (set! (.-style (js/document.querySelector &quot;#wrapper&quot;)) &quot;display: flex;&quot;))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p><img alt="Screenshot of a web browser window with the album art for Fresh Horses and an audio player" src="assets/2024-07-20-soundcljoud-cloudy-garth.png" title="Almost time to ride out!" class="border" /></p><p>Before we go any further, let&apos;s create some functions from this big blob of code. At the moment, we&apos;re complecting two things:</p><ol start="1"><li>Extracting data from the XML DOM</li><li>Updating the HTML DOM to display the data</li></ol><p>Let&apos;s do the functional programming thing and create a purely functional core and a mutable shell. Instead of extracting and updating, we&apos;ll create a function that transforms the XML DOM representation of an album into a ClojureScript representation:</p><pre><code class="language-clojure">(defn xml-get [el k]
  (-&gt; el
      (.querySelector k)
      (.-innerHTML)))

(defn xml-get-attr [el k attr]
  (-&gt; el
      (.querySelector k)
      (.getAttribute attr)))

(defn -&gt;album [xml]
  {:title (xml-get xml &quot;title&quot;)
   :image (xml-get-attr xml &quot;image&quot; &quot;href&quot;)})

(defn load-album [path]
  (p/-&gt; (fetch-xml path) -&gt;album))

(comment

  (p/let [{:keys [title image] :as album} (load-album (str base-path &quot;/album.rss&quot;))]
    (set! (.-innerHTML (js/document.querySelector &quot;h1&quot;)) title)
    (set! (.-src (js/document.querySelector &quot;.cover-image &gt; img&quot;)) image)
    (set! (.-style (js/document.querySelector &quot;#wrapper&quot;)) &quot;display: flex;&quot;))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>Now that we have a nice ClojureScript data structure to represent our album, let&apos;s tackle the DOM mutations we need to do to display the album:</p><pre><code class="language-clojure">(defn get-el [selector]
  (if (instance? js/HTMLElement selector)
    selector  ; already an element; just return it
    (js/document.querySelector selector)))

(defn set-styles! [el styles]
  (set! (.-style el) styles))

(defn display-album! [{:keys [title image] :as album}]
  (let [header (get-el &quot;h1&quot;)
        cover (get-el &quot;.cover-image &gt; img&quot;)
        wrapper (get-el &quot;#wrapper&quot;)]
    (set! (.-innerHTML header) title)
    (set! (.-src cover) image)
    (set-styles! wrapper &quot;display: flex;&quot;)
    album))

(comment

  (p/-&gt; (load-album (str base-path &quot;/album.rss&quot;)) display-album!)
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><div class="markdown-heading"><h2 id="tracking-down-the-tracks">Tracking down the tracks</h2><a href="#tracking-down-the-tracks" class="anchor" aria-label="Permalink: Tracking down the tracks"><img src="assets/link.svg" /></a></div><p>Displaying the album title and cover art is all well and good, but in order to complete our Soundcloud clone, we need some way of actually listening to the music on the album. If you recall, our RSS feed contains a series of <code>&lt;item&gt;</code> tags representing the tracks:</p><pre><code class="language-xml">    &lt;item&gt;
      &lt;itunes:title&gt;The Old Stuff&lt;/itunes:title&gt;
      &lt;title&gt;The Old Stuff&lt;/title&gt;
      &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
      &lt;enclosure
          url=&quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+The+Old+Stuff.mp3&quot;
          length=&quot;5943424&quot; type=&quot;audio/mpeg&quot; /&gt;
      &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
      &lt;itunes:duration&gt;252&lt;/itunes:duration&gt;
      &lt;itunes:episode&gt;1&lt;/itunes:episode&gt;
      &lt;itunes:episodeType&gt;full&lt;/itunes:episodeType&gt;
      &lt;itunes:explicit&gt;false&lt;/itunes:explicit&gt;
    &lt;/item&gt;
   ... 
    &lt;item&gt;
      &lt;itunes:title&gt;Ireland&lt;/itunes:title&gt;
      &lt;title&gt;Ireland&lt;/title&gt;
      &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
      &lt;enclosure
          url=&quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+Ireland.mp3&quot;
          length=&quot;6969472&quot; type=&quot;audio/mpeg&quot; /&gt;
      &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
      &lt;itunes:duration&gt;301&lt;/itunes:duration&gt;
      &lt;itunes:episode&gt;10&lt;/itunes:episode&gt;
      &lt;itunes:episodeType&gt;full&lt;/itunes:episodeType&gt;
      &lt;itunes:explicit&gt;false&lt;/itunes:explicit&gt;
    &lt;/item&gt;
</code></pre><p>What we need from each item in order to display and play the track is:</p><ul><li>Song title</li><li>Artist (for this album, all tracks are from Garth, but an album could be a compilation of songs by different artists, so let&apos;s grab the artist in case we later decide to display it)</li><li>Track number</li><li>URL of the source audio</li></ul><p>Let&apos;s write an aspirational function that assumes it will be called with a DOM element representing an <code>&lt;item&gt;</code> and transforms it into a ClojureScript map, just as we did for the item itself:</p><pre><code class="language-clojure">(defn -&gt;track [item-el]
  {:artist (xml-get item-el &quot;author&quot;)
   :title (xml-get item-el &quot;title&quot;)
   :number (-&gt; (xml-get item-el &quot;episode&quot;) js/parseInt)
   :src (xml-get-attr item-el &quot;enclosure&quot; &quot;url&quot;)})
</code></pre><p>For the track number, we need to convert it to an integer, since the text contents of an XML elements are, well, text, and we&apos;ll want to sort our tracks numerically.</p><p>Now that we have a function to convert an <code>&lt;item&gt;</code> into a track, let&apos;s plug that into our <code>-&gt;album</code> function to add a list of tracks to the album:</p><pre><code class="language-clojure">(defn -&gt;album [xml]
  {:title (xml-get xml &quot;title&quot;)
   :image (xml-get-attr xml &quot;image&quot; &quot;href&quot;)
   :tracks (-&gt;&gt; (.querySelectorAll xml &quot;item&quot;)
                (map -&gt;track)
                (sort-by :number))})
</code></pre><p>OK, we have data representing a list of tracks, so we need to consider how we want to display it. If we cast our mind back to our HTML, we have a div where the tracks should go:</p><pre><code class="language-html">&lt;body&gt;
  ...
  &lt;div id=&quot;wrapper&quot; style=&quot;display: none;&quot;&gt;
    &lt;div id=&quot;player&quot;&gt;
      ...
      &lt;div id=&quot;controls&quot;&gt;
        ...
        &lt;div id=&quot;tracks&quot; style=&quot;&quot;&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/body&gt;
</code></pre><p>What we can do is create a <code>&lt;span&gt;</code> for each track, something like this:</p><pre><code class="language-html">&lt;span&gt;1. The Old Stuff&lt;/span&gt;
</code></pre><p>Let&apos;s go ahead and write that function:</p><pre><code class="language-clojure">(defn track-&gt;span [{:keys [number artist title] :as track}]
  (let [span (js/document.createElement &quot;span&quot;)]
    (set! (.-innerHTML span) (str number &quot;. &quot; title))
    span))

(comment

  (p/-&gt;&gt; (load-album (str base-path &quot;/album.rss&quot;))
         :tracks
         first
         track-&gt;span
         (log &quot;The first track is:&quot;))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>In the JavaScript console, we see:</p><pre><code class="language-text">The first track is: &lt;span&gt;1. The Old Stuff&lt;/span&gt;
</code></pre><p>This is cool, because the <code>track-&gt;span</code> function is still pure—there&apos;s no mutation occurring there. We have one and only one place where that&apos;s doing mutation, and that&apos;s <code>display-album!</code>, which is where we can hook into our functional core and display the tracks. In order to do that, we&apos;ll take our list of tracks, turn them into a list of <code>&lt;span&gt;</code> elements, and then set them as the children of the <code>#tracks</code> div.</p><pre><code class="language-clojure">(defn set-children! [el children]
  (.replaceChildren el)
  (doseq [child children]
    (.appendChild el child))
  el)

(defn display-album! [{:keys [title image tracks] :as album}]
  (let [header (get-el &quot;h1&quot;)
        cover (get-el &quot;.cover-image &gt; img&quot;)
        wrapper (get-el &quot;#wrapper&quot;)]
    (set! (.-innerHTML header) title)
    (set! (.-src cover) image)
    (-&gt;&gt; tracks
         (map track-&gt;span)
         (set-children! (get-el &quot;#tracks&quot;)))
    (set-styles! wrapper &quot;display: flex;&quot;)
    album))

(comment

  (p/-&gt; (load-album (str base-path &quot;/album.rss&quot;)) display-album!)
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p><img alt="Screenshot of a web browser window with the album art for Fresh Horses, an audio player, and a list of tracks" src="assets/2024-07-20-soundcljoud-cloudy-tracks.png" title="That tracks" class="border" /></p><p>This is fantastic... if all we want to do is know what&apos;s on an album. But of course my initial problem was wanting to <strong>listen</strong> to Garth and not having a way to do that. Now I have written much Clojure and ClojureScript, and still cannot listen to Garth. 🤔</p><div class="markdown-heading"><h2 id="play-it-again,-sam">Play it again, Sam</h2><a href="#play-it-again,-sam" class="anchor" aria-label="Permalink: Play it again, Sam"><img src="assets/link.svg" /></a></div><p>Of course what I do have is an HTML <code>&lt;audio&gt;</code> element and an MP3 file with a source URL, and I bet if I can just put these two things together, my ears will soon be filled with the sweet sweet sounds of 90s country music.</p><p>Let&apos;s start out with the simplest thing we can do, which is to activate the first track on the album once it&apos;s loaded. Since <code>display-album!</code> returns the album, we can just add some code to the end of the pipeline:</p><pre><code class="language-clojure">(comment

  (def base-path &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&apos;soundcljoud/base-path

  (p/-&gt;&gt; (load-album (str base-path &quot;/album.rss&quot;))
         display-album!
         :tracks
         first
         :src
         (set! (.-src (get-el &quot;audio&quot;))))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>As soon as we evaluate this code, the <code>&lt;audio&gt;</code> element comes to life, displaying a duration and activating the play button. Pressing the play button, we do in fact hear some Garth! 🎉</p><p>However, our UX is quite poor, since there&apos;s no visual representation of which track is playing. We can fix this by emboldening the active track:</p><pre><code class="language-clojure">(comment

  (p/let [{:keys [number src] :as track}
          (p/-&gt;&gt; (load-album (str base-path &quot;/album.rss&quot;))
                 display-album!
                 :tracks
                 first)]
    (-&gt; (get-el &quot;#tracks&quot;)
        (.-children)
        seq
        (nth (dec number))
        (set-styles! &quot;font-weight: bold;&quot;))
    (set! (.-src (get-el &quot;audio&quot;)) src))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p><img alt="Screenshot of our UI with the first track highlighted and loaded in the audio element" src="assets/2024-07-20-soundcljoud-cloudy-play.png" title="That&apos;s a bold move!" class="border" /></p><p>Speaking of UX, though, one would imagine that they&apos;d be able to change to a track by clicking on it. At the moment, clicking does nothing, but that&apos;s easy enough to fix by adding an event handler to our span for each track that activates the track. Let&apos;s create a function and shovel our track activating code in there:</p><pre><code class="language-clojure">(defn activate-track! [{:keys [number src] :as track}]
  (log &quot;Activating track:&quot; (clj-&gt;js track))
  (let [track-spans (seq (.-children (get-el &quot;#tracks&quot;)))]
    (-&gt; track-spans
        (nth (dec number))
        (set-styles! &quot;font-weight: bold;&quot;)))
  (set! (.-src (get-el &quot;audio&quot;)) src)
  track)
</code></pre><p>By the way, that <code>clj-&gt;js</code> function takes a ClojureScript data structure (in this case, our track map) and recursively transforms it into a JavaScript object so it can be printed nicely in the JS console.</p><p>OK, now that we have <code>activate-track!</code> as a function, we can use it in a click handler:</p><pre><code class="language-clojure">(defn track-&gt;span [{:keys [number title] :as track}]
  (let [span (js/document.createElement &quot;span&quot;)]
    (set! (.-innerHTML span) (str number &quot;. &quot; title))
    (.addEventListener span &quot;click&quot; (partial activate-track! track))
    span))

(comment

  (p/-&gt; (load-album (str base-path &quot;/album.rss&quot;))
        display-album!
        :tracks
        first
        activate-track!)
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>Evaluating this code activates the first track on the album as before, and then clicking another track highlights it in bold and loads it into the <code>&lt;audio&gt;</code> element. That&apos;s good, but what isn&apos;t so good is that the first track stays bold. 😬</p><p>Luckily, there&apos;s an easy fix for this. All we need to do is reset the weight of all the track spans before bolding the active one in <code>activate-track!</code>:</p><pre><code class="language-clojure">(defn activate-track! [{:keys [number src] :as track}]
  (log &quot;Activating track:&quot; (clj-&gt;js track))
  (let [track-spans (seq (.-children (get-el &quot;#tracks&quot;)))]
    (doseq [span track-spans]
      (set-styles! span &quot;font-weight: normal;&quot;))
    (-&gt; track-spans
        (nth (dec number))
        (set-styles! &quot;font-weight: bold;&quot;)))
  (set! (.-src (get-el &quot;audio&quot;)) src)
  track)
</code></pre><p>Amazing!</p><p>Whilst we&apos;re ticking off UX issues, let&apos;s think about what should happen when our user clicks on a different track. At the moment, we load the track into the player and then the user has to click the play button to start listening to it. That is perfectly reasonable when first loading the album, but if I&apos;m listening to a track and then select another one, I would kinda expect the new track to start playing automatically instead of me having to click play manually.</p><p>Let&apos;s see how we can do this. According to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">HTMLMediaElement</a> documentation, our <code>&lt;audio&gt;</code> element should have <code>paused</code> attribute telling us whether playback is happening. Let&apos;s try it out:</p><pre><code class="language-clojure">(comment

  (p/-&gt; (load-album (str base-path &quot;/album.rss&quot;))
        display-album!
        :tracks
        first
        activate-track!)
  ;; =&gt; #&lt;Promise[~]&gt;

  (-&gt; (get-el &quot;audio&quot;)
      (.-paused))
  ;; =&gt; true

)
</code></pre><p>Now if we click the play button and check the value of the <code>paused</code> attribute again:</p><pre><code class="language-clojure">(comment

  (-&gt; (get-el &quot;audio&quot;)
      (.-paused))
  ;; =&gt; false

)
</code></pre><p>Excellent! Now let&apos;s see how we programatically start playing a newly loaded track. Referring back to the documentation, we discover a <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play">HTMLMediaElement.play()</a> method. Let&apos;s try that out:</p><pre><code class="language-clojure">(comment

  (p/-&gt; (load-album (str base-path &quot;/album.rss&quot;))
        display-album!
        :tracks
        second
        activate-track!)
  ;; =&gt; #&lt;Promise[~]&gt;

  (-&gt; (get-el &quot;audio&quot;)
      (.play))
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>Evaluating this code results in &quot;Cowboys and Angels&quot; starting to play!</p><p>Now we can use what we&apos;ve learned to teach <code>activate-track!</code> to start playing the track when appropriate:</p><pre><code class="language-clojure">(defn activate-track! [{:keys [number src] :as track}]
  (log &quot;Activating track:&quot; (clj-&gt;js track))
  (let [track-spans (seq (.-children (get-el &quot;#tracks&quot;)))
        audio-el (get-el &quot;audio&quot;)
        paused? (.-paused audio-el)]
    (doseq [span track-spans]
      (set-styles! span &quot;font-weight: normal;&quot;))
    (-&gt; track-spans
        (nth (dec number))
        (set-styles! &quot;font-weight: bold;&quot;))
    (set! (.-src audio-el) src)
    (when-not paused?
      (.play audio-el)))
  track)

(comment

  (p/-&gt; (load-album (str base-path &quot;/album.rss&quot;))
        display-album!
        :tracks
        first
        activate-track!)
  ;; =&gt; #&lt;Promise[~]&gt;

)
</code></pre><p>When the album loads, the first track is activated but doesn&apos;t start playing. Clicking on another track activates it but doesn&apos;t start playing it. However, if we click the play button and start listening to the active track, then click on another track, the new track is activated and immediately starts playing.</p><p>This, my friends, is some seriously good UX! Of course, we can improve it further.</p><div class="markdown-heading"><h2 id="keep-playing-it,-sam">Keep playing it, Sam</h2><a href="#keep-playing-it,-sam" class="anchor" aria-label="Permalink: Keep playing it, Sam"><img src="assets/link.svg" /></a></div><p>The next UX nit that we should pick is the fact that when a track ends, our poor user has to manually click on the next track and then manually click the play button just to keep listening to the album. This seems a bit mean of us, so let&apos;s see what we can do in order to be the nice people that we know we are, deep down inside.</p><p>Our good friend HTMLMediaElement has <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#events">a bunch of
events</a> that tell us useful things about what&apos;s happening with the media, and one of these events is <code>ended</code>:</p><blockquote><p>Fired when playback stops when end of the media (<audio> or <video>) is reached or because no further data is available.</p></blockquote><p>This seems like it will fit the bill quite nicely. Hopping back in our hammock for a minute, we think about what should happen when the end of a track is reached:</p><ul><li>The next track is activated and starts playing, unless</li><li>It&apos;s the last track on the album, in which case nothing should happen.</li></ul><p>We can of course add a <code>ended</code> event listener to the <code>&lt;audio&gt;</code> element every time a new track is activated, but this is problematic because we would then want to remove the previous event listener, and it turns out that <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#matching_event_listeners_for_removal">removing event
listeners is a bit
complicated</a>. What if we instead had an event listener that knew what track was currently playing, where that track comes in the album, and what track (if any) is next? Then we&apos;d only have to attach a listener once, right after we load the album. Let&apos;s think through how we could do that.</p><p>So far, we&apos;ve been relying on the state of the DOM to tell us things like if the track is paused. A much more functional approach would be to control the state ourselves using immutable data structures and so on. A nice side effect of this (sorry, Haskell folks, Clojurists are just fine with uncontrolled side effects) is that it actually makes REPL-driven development easier as well! 🤯</p><p>Let&apos;s start by extracting a function to handle the tedium of loading the album, displaying it, and then activating the first track:</p><pre><code class="language-clojure">(defn load-ui! [dir]
  (p/-&gt;&gt; (load-album (str dir &quot;/album.rss&quot;))
         display-album!
         :tracks
         first
         activate-track!))
</code></pre><p>Now that we have this, we&apos;ll define a top-level <a href="https://clojure.org/reference/atoms">atom</a> to hold the state, then update our <code>load-ui!</code> function to stuff the album into the atom once it&apos;s loaded:</p><pre><code class="language-clojure">(def state (atom nil))

(defn load-ui! [dir]
  (p/-&gt;&gt; (load-album (str dir &quot;/album.rss&quot;))
         display-album!
         (assoc {} :album)
         (reset! state)
         :album
         :tracks
         first
         activate-track!))
</code></pre><p>What we&apos;re doing here is creating a map to hold the state, then assoc-ing the loaded album into the map under the <code>:album</code> key, then putting that map into the <code>state</code> atom with <a href="https://clojuredocs.org/clojure.core/reset%21">reset!</a>, which returns the new value saved in the atom, which is the one we just put in there, which will look like this:</p><pre><code class="language-clojure">{:title &quot;Garth Brooks - Fresh Horses&quot;,
 :image &quot;https://i.discogs.com/.../LTMxNjguanBlZw.jpeg&quot;,
 :tracks
 ({:artist &quot;Garth Brooks&quot;,
   :title &quot;The Old Stuff&quot;,
   :number 1,
   :src &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+The+Old+Stuff.mp3&quot;}
  ...
  {:artist &quot;Garth Brooks&quot;,
   :title &quot;Ireland&quot;,
   :number 10,
   :src &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+Ireland.mp3&quot;}), :paused? true}
</code></pre><p>We&apos;ll then grab the album back out of the map and proceed as before to activate the first track. This is a little gross, but we&apos;ll clean it up as we go.</p><p>Oh yeah, and remember when I promised this would make debugging easier? Check this out:</p><pre><code class="language-clojure">(comment

  (load-ui! &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&lt;Promise[~]&gt;

  @state
  ;; =&gt; {:album {:title &quot;Garth Brooks - Fresh Horses&quot;,
  ;;             :image &quot;https://i.discogs.com/.../LTMxNjguanBlZw.jpeg&quot;,
  ;;             :tracks
  ;;             ({:artist &quot;Garth Brooks&quot;,
  ;;               :title &quot;The Old Stuff&quot;,
  ;;               :number 1,
  ;;               :src &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+The+Old+Stuff.mp3&quot;}
  ;;               ...
  ;;               {:artist &quot;Garth Brooks&quot;,
  ;;                :title &quot;Ireland&quot;,
  ;;                :number 10,
  ;;                :src &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+Ireland.mp3&quot;})}}

)
</code></pre><p>That&apos;s right, we no longer have to rely on logging stuff to the JS console in our promise chains!</p><p>OK, but we haven&apos;t really changed anything other than making the <code>load-ui!</code> function more complicated. Let&apos;s add a little more to our state atom so we can actually tackle the problem of auto-advancing tracks. First, we&apos;ll add a <code>:paused?</code> key:</p><pre><code class="language-clojure">(defn load-ui! [dir]
  (p/-&gt;&gt; (load-album (str dir &quot;/album.rss&quot;))
         display-album!
         (assoc {:paused? true} :album)
         (reset! state)
         :album
         :tracks
         first
         activate-track!))

(comment

  (load-ui! &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&lt;Promise[~]&gt;

  @state
  ;; =&gt; {:paused? true, :album {...}}

)
</code></pre><p>Now let&apos;s add an event listener to the <code>&lt;audio&gt;</code> element that updates the state when the play button is pressed, doing a little cleanup of the <code>load-ui!</code> function whilst we&apos;re at it:</p><pre><code class="language-clojure">(defn load-ui! [dir]
  (p/let [album (load-album (str dir &quot;/album.rss&quot;))]
    (display-album! album)
    (reset! state {:paused? true, :album album})
    (-&gt;&gt; album
         :tracks
         first
         activate-track!)
    (.addEventListener (get-el &quot;audio&quot;) &quot;play&quot;
                       #(swap! state assoc :paused? false))))

(comment

  (load-ui! &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&lt;Promise[~]&gt;

  (:paused? @state)
  ;; =&gt; true

  ;; Click the play button and...
  (:paused? @state)
  ;; =&gt; false

)
</code></pre><p>If you&apos;re not familiar with <a href="https://clojuredocs.org/clojure.core/swap%21">swap!</a>, it takes an atom and a function which will be called with the current value of the atom, then sets the next value of the atom to whatever the function returns, just like <a href="https://clojuredocs.org/clojure.core/update">update</a> does for plain old maps. And also just like <code>update</code>, it has a shorthand form so that instead of writing this:</p><pre><code class="language-clojure">(swap! state #(assoc % :paused? false))
</code></pre><p>you can write this:</p><pre><code class="language-clojure">(swap! state assoc :paused? false)
</code></pre><p>in which case <code>swap!</code> will treat the arg after the atom as a function which will be called with the current value first, then the rest of the args to <code>swap!</code>. You can imagine that <code>swap!</code> is written something like this:</p><pre><code class="language-clojure">(defn swap!
  ([atom f]
   (reset! atom (f @atom)))
  ([atom f &amp; args]
   (reset! atom (apply f @atom args))))
</code></pre><p>It&apos;s obviously not written like that, even though that would technically probably maybe work. It&apos;s actually written like <a href="https://github.com/clojure/clojure/blob/clojure-1.11.1/src/clj/clojure/core.clj#L2362">this</a>:</p><pre><code class="language-clojure">(defn swap!
  &quot;Atomically swaps the value of atom to be:
  (apply f current-value-of-atom args). Note that f may be called
  multiple times, and thus should be free of side effects.  Returns
  the value that was swapped in.&quot;
  {:added &quot;1.0&quot;
   :static true}
  ([^clojure.lang.IAtom atom f] (.swap atom f))
  ([^clojure.lang.IAtom atom f x] (.swap atom f x))
  ([^clojure.lang.IAtom atom f x y] (.swap atom f x y))
  ([^clojure.lang.IAtom atom f x y &amp; args] (.swap atom f x y args)))
</code></pre><p>But you get the point.</p><p>Aaaaaanyway, I seem to have digressed—which is firmly on brand for this blog, so I apologise for nothing!</p><p>But yeah, at this point, we&apos;re back to the functionality that we had before. If we click on a track whilst the player is paused, the new track is selected but doesn&apos;t start playing, and if we click on a new track whilst the player is playing, the player plays on by playing the new track. Got it?</p><p>However, <code>activate-track!</code> is still relying on the DOM to keep track of whether the player is paused. Let&apos;s fix this by checking the <code>state</code> atom instead:</p><pre><code class="language-clojure">(defn activate-track! [{:keys [number src] :as track}]
  (log &quot;Activating track:&quot; (clj-&gt;js track))
  (let [track-spans (seq (.-children (get-el &quot;#tracks&quot;)))
        audio-el (get-el &quot;audio&quot;)
        ;; Instead of this 👇
        ;; paused? (.-paused audio-el)
        ;; Do this! 👇
        {:keys [paused?]} @state]
      ;; ...
    )
  track)
</code></pre><p>Next, let&apos;s write a function to advance to the next track:</p><pre><code class="language-clojure">(defn advance-track! []
  (let [{:keys [active-track album]} @state
        {:keys [tracks]} album
        last-track? (= active-track (count tracks))]
    (when-not last-track?
      (activate-track! (nth tracks active-track)))))
</code></pre><p>Oops, this is relying on <code>:active-track</code> being present in the <code>state</code> atom. Let&apos;s put it there in <code>activate-track!</code></p><pre><code class="language-clojure">(defn activate-track! [{:keys [number src] :as track}]
  (log &quot;Activating track:&quot; (clj-&gt;js track))
  (let [track-spans (seq (.-children (get-el &quot;#tracks&quot;)))
        audio-el (get-el &quot;audio&quot;)
        {:keys [paused?]} @state]
    ;; ...
    )
  ;; Swappity swap swap! 👇
  (swap! state assoc :active-track number)
  track)

(comment

  (load-ui! &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&lt;Promise[~]&gt;

  @state
  ;; =&gt; {:paused? true,
  ;;     :active-track 1,
  ;;     :album {...}}

)
</code></pre><p>Now we should be able to actually call <code>advance-track!</code> to, well, advance the track:</p><pre><code class="language-clojure">(comment

  (load-ui! &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&lt;Promise[~]&gt;

  (:active-track @state)
  ;; =&gt; 1

  (advance-track!)
  ;; =&gt; {:artist &quot;Garth Brooks&quot;, :title &quot;Cowboys And Angels&quot;, :number 2, :src &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+Cowboys+and+Angels.mp3&quot;}

  (:active-track @state)
  ;; =&gt; 2

)
</code></pre><p>We will have also seen the highlighted track change when we evaluated the <code>(advance-track!)</code> form! 🎉</p><div class="markdown-heading"><h2 id="is-this-the-end?">Is this the end?</h2><a href="#is-this-the-end?" class="anchor" aria-label="Permalink: Is this the end?"><img src="assets/link.svg" /></a></div><p>What we&apos;re building up to is of course the ability to play our album continuously. When one track ends, the next should begin. And our good friend <code>&lt;audio&gt;</code> has just what we need, in the form of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended_event">ended</a> event. If we add one line of code to register <code>advance-track!</code> as the listener for the <code>ended</code> event:</p><pre><code class="language-clojure">(defn load-ui! [dir]
  (p/let [album (load-album (str dir &quot;/album.rss&quot;))]
    (display-album! album)
    (reset! state {:paused? true, :album album})
    (-&gt;&gt; album
         :tracks
         first
         activate-track!)
    (.addEventListener (get-el &quot;audio&quot;) &quot;play&quot;
                       #(swap! state assoc :paused? false))
    (.addEventListener (get-el &quot;audio&quot;) &quot;ended&quot;
                       advance-track!)))

(comment

  (load-ui! &quot;http://localhost:1341/Garth+Brooks/Fresh+Horses&quot;)
  ;; =&gt; #&lt;Promise[~]&gt;

  ;; Click ▶️ and witness the glory!
)
</code></pre><p>We win!</p><p><img alt="Screenshot of our UI with the last track highlighted and the console showing activating track for all previous tracks" src="assets/2024-07-20-soundcljoud-cloudy-autoplay.png" title="Autoplays assemble!" class="border" /></p><p>Winners who have won before and know how to win will of course know that the best thing to do after winning is to stride triumphantly to the podium, receive your 🥇, wave to your adoring public, soak up the applause like warm sunshine on a July day (unless you&apos;re in the southern hemisphere, in which case the warm sunshine is best appreciated in December, unless you&apos;re close enough to the equator to appreciate warm sunshine whenever you damn well please, unless you&apos;re too close to the equator and that sunshine is too warm to appreciate because you&apos;re sweating like wild), and then head home, find a comfy chair and open a bottle of champagne or fizzy water or tasty whiskey or whatever.</p><p>I, of course, am no such winner, so instead of retiring to my comfy chair with a glass of <a href="https://thewateroflife.org/2023/02/26/lagavulin-offerman-edition/">Lagavulin</a>, I want to jump ahead in a track, so I confidently reach for the audio control and click ahead in the timeline, and... nothing happens WTF?</p><p>Reading more documentation, I discover that I can see the current time in seconds in the track by reading its <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentTime">currentTime</a> property, and I can seek to an arbitrary time by setting <code>currentTime</code>, so let&apos;s give that a try, shall we? (Spoiler: we shall.)</p><pre><code class="language-clojure">(comment

  (.-currentTime (get-el &quot;audio&quot;))
  ;; =&gt; 37.010544

  (set! (.-currentTime (get-el &quot;audio&quot;)) 50)
  ;; =&gt; nil

  ;; Why did my track start over? 🤬
  
  (.-currentTime (get-el &quot;audio&quot;))
  ;; =&gt; 2.006649

)
</code></pre><p>To make a long story short, this all boils down to how the browser actually implements seeking. When it first loads the audio track, it issues a request like this:</p><pre><code class="language-text">GET /Garth+Brooks/Fresh+Horses/Garth+Brooks+-+The+Old+Stuff.mp3 HTTP/1.1
Range: bytes=0-
</code></pre><p>and expects a response like this:</p><pre><code class="language-text">HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-length: 5943424
Content-Range: bytes 0-1024000/5943424
Content-Type: audio/mpeg
</code></pre><p>It will then buffer the bytes it got back and make the track seekable within those bytes, as described <a href="https://developer.mozilla.org/en-US/docs/Web/Media/Audio_and_video_delivery/buffering_seeking_time_ranges">here</a>. You can peer under the hood by inspecting the <code>buffered</code> and <code>seekable</code> properties of the <code>&lt;audio&gt;</code> element:</p><pre><code class="language-javascript">audio.buffered.length; // returns 2
audio.buffered.start(0); // returns 0
audio.buffered.end(0); // returns 5
audio.buffered.start(1); // returns 15
audio.buffered.end(1); // returns 19
</code></pre><p>But if we do this in our player, we experience a deep feeling of melancholy:</p><pre><code class="language-clojure">(comment

  (let [b (-&gt; (get-el &quot;audio&quot;)
              (.-buffered))]
    [(.start b 0) (.end b 0)])
  ;; =&gt; [0 144.758]

  (-&gt; (get-el &quot;audio&quot;)
      (.-seekable)
      (.-length))
  ;; =&gt; 1

  (let [s (-&gt; (get-el &quot;audio&quot;)
              (.-seekable))]
    [(.start s 0) (.end s 0)])
  ;; =&gt; [0 0]

)
</code></pre><p>The buffering looks fine, but it seems that we can only seek between 0 seconds and 0 seconds in the track, which kinda explains why attempting to set <code>currentTime</code> to any number that isn&apos;t 0 results in seeking back to 0. 😭</p><p>Seeking apparently only works if we get that blessed <code>206 Partial Content</code> response from the webserver, so the browser knows how to make subsequent range requests to buffer more data, and unfortunately, the built-in <a href="https://github.com/babashka/http-server">babashka.http-server</a> that we&apos;re using to serve up files in <code>public/</code> responds like this:</p><pre><code class="language-text">HTTP/1.1 200 OK
Content-length: 5943424
Content-Type: audio/mpeg
Server: http-kit
</code></pre><p>No partial content?</p><p><img alt="Screenshot of a chef saying no seek for you, come back 1 year" src="assets/2024-07-20-soundcljoud-cloudy-noseek.jpg" title="Call Antifa, quick!" /></p><p>We may attempt to fix this next time on &quot;Soundcljoud, or a young man&apos;s Soundcloud clonejure&quot;, that is if there is a next time.</p><p>Part 1: <a href="2024-07-09-soundcljoud.html">Soundcljoud, or a young man&apos;s Soundcloud clonejure</a></p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-07-09-soundcljoud.html</id>
    <link href="https://jmglov.net/blog/2024-07-09-soundcljoud.html"/>
    <title>Soundcljoud, or a young man's Soundcloud clonejure</title>
    <updated>2024-07-09T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="A stack of CDs. Photo by Brett Jordan on Unsplash." src="assets/2024-07-09-soundcljoud-preview.jpg" title="I should be allowed to glue my poster" /></p><p>😱 <strong>Warning!</strong></p><p>This blog post is ostensibly about Clojure (of the <a href="https://babashka.org/">Babashka</a> variety), but not long after starting to write it, I found myself some 3100 words into some rambling exposition about the history of audio technology and how it intersected with my life, and had not typed the word &quot;ClojureScript&quot; even once (though it may appear that I&apos;ve now typed it twice, I actually wrote this bit <em>post scriptum</em>, but decided to attach it before the post, which I suppose makes it a prelude and not a postscript, but I digress).</p><p>Whilst this won&apos;t surprise returning readers, I thought it worth warning first-timers, and offering all readers the chance to <a href="#omg_finally_stuff_about_clojure">skip
over</a> all the stage-setting and other self-indulgent nonsense, simply by clicking the link that says &quot;skip over&quot;.</p><p>If you&apos;d like to delay your gratification, you are in luck! Read on, my friend!</p><div class="markdown-heading"><h2 id="rambling-exposition">Rambling exposition</h2><a href="#rambling-exposition" class="anchor" aria-label="Permalink: Rambling exposition"><img src="assets/link.svg" /></a></div><p>Once upon a time there were vinyl platters into which the strategic etching of grooves could encode sound waves. If one placed said platter on a table and turned it say, 78 times a minute, and attached a needle to an arm and dropped it onto the rotating platter, one could use the vibrations in the arm caused by the needle moving left and right in the grooves to decode the sound waves, which you then turn into a fluctuating electric current and cause it to flow through a coil which vibrates some fabric and reproduces the sound waves. And this was good, for we could listen to music.</p><p>The only problem with these &quot;records&quot;, as they were called, is that they were kinda big and you couldn&apos;t fit them in your backpack. So <a href="https://en.wikipedia.org/wiki/Compact_Disc_Digital_Audio#History">some Dutch people and
some Japanese people teamed
up</a> and compacted the records, and renamed them discs because a record is required by law (in Japan) to be a certain diameter or you can&apos;t call it a record. They decided to make them out of plastic instead of vinyl, and then realised that they couldn&apos;t cut grooves into plastic because they kept breaking the discs—perhaps the choice of hammer and chisel to cut the grooves wasn&apos;t ideal, but who am I to judge? &quot;だってさ、&quot; said one of the Japanese engineers, &quot;<a href="https://translate.google.com/?sl=ja&amp;tl=en&amp;text=%E9%87%9D%E3%81%A7%E3%83%87%E3%82%A3%E3%82%B9%E3%82%AF%E3%81%AB%E3%81%A1%E3%81%A3%E3%81%A1%E3%82%83%E3%81%84%E7%A9%B4%E3%82%84%E3%81%A3%E3%81%9F%E3%82%89%E3%80%81%E3%81%A9%E3%81%86%E3%81%AA%E3%82%8B%E3%81%8B%E3%81%AA&amp;op=translate">針でディスクにちっちゃい穴やったら、どうなるかな</a>？&quot; No one knew, so they just tried it, and lo! the disc didn&apos;t break! But also lo! poking at the disc with a needle made little bumps on the other side of the disc, because of the law of conservation of mass or something... I don&apos;t know, I had to drop out of physics in uni because it apparently takes me 20 hours to solve one simple orbital mechanics problem; I mean, come on, how hard is it to calculate the orbit of a planet around three stars? Jeez.</p><p>But anyway, they made some bumps, which was annoying at first but then turned out to be a very good thing indeed when someone had the realisation that if squinted at the disc with a binary way of thinking, you could consider a bump to be a 1, and a flat place on the disc to be a 0, and then if you were to build a digital analyser that sampled the position of a sound wave, say, 44,100 times a second and wrote down the results in binary, you could encode the resulting string of 1s and 0s onto the disc with a series of bumps.</p><p>But how to decode the bumps when trying to play the thing back? The solution was super obvious this time: a frickin&apos; laser beam! (Frickin&apos; laser beams were on everyone&apos;s mind back in the early 80s because of Star Wars—the movies; the <a href="https://en.wikipedia.org/wiki/Strategic_Defense_Initiative">missile defence
system</a> wouldn&apos;t show up until a few years later). If they just fired a frickin&apos; laser beam continuously whilst rotating the disc and added a photodiode next to the laser, the light bouncing back off a bump would knock the wavelength of the light 1/2 out of phase, which would partially cancel the reflected light, lowering the intensity, which the photodiode would pick up and interpret as a 1. Obviously.</p><p>Except for one thing. Try as they might, the engineers couldn&apos;t make the frickin&apos; laser beam bounce off the frickin&apos; surface of the frickin&apos; polycarbonate. If the plastic was too dark, it just absorbed the light, and if it was too light, it certainly reflected it, but not with high enough intensity for the photodiode to tell the difference between a 1 and a 0. 😢</p><p>This was a real head-scratcher, and they were well and truly stuck until one day one of the Dutch engineers was enjoying a beer from a frosty glass at a table at an outdoor cafe on Museumplein on a hot day and the condensation on the glass made the coaster stick to the bottom of the glass in the annoying way it does when one doesn&apos;t put a little table salt on the coaster first—amateur!—and the coaster fell into a nearby ashtray (people used to put these paper tubes stuffed with tobacco in their mouths, light them on fire, and suck the smoke deep into their lungs; ask your parents, kids) and got all coated in ash. The engineer wrinkled their nose in disgust before having an amazing insight. &quot;What if,&quot; they thought to themselves, &quot;we coated one side of the polycarbonate with something shiny that would reflect the frickin&apos; laser?&quot; Their train of thought then continued thusly: &quot;And what is both reflective and cheap? Why, this selfsame aluminium of which this here ashtray is constructed!&quot;</p><p>And thus the last engineering challenge was overcome, and there was much rejoicing!</p><p>The first test of the technology was a recording of <a href="https://en.wikipedia.org/wiki/Compact_disc#Initial_launch_and_adoption">Richard Strauss&apos;s &quot;An
Alpine
Symphony&quot;</a> made in the beginning of December 1981, which was then presented to the world the following spring. It took a whole year before the first commercial compact disc was released, and by 1983, the technology had really taken off, thus introducing digital music to the world and ironically sowing the seeds of the format&apos;s demise. But I&apos;m getting ahead of myself again.</p><p>Sometime around 1992, give or take, my parents got me a portable CD player (by this time, people, being <s>lazy</s> efficient by nature, had stopped saying &quot;compact disc&quot; and started abbreviating it to &quot;CD&quot;) and one disc: Aerosmith&apos;s tour de force <a href="https://www.discogs.com/release/370731-Aerosmith-Get-A-Grip">&quot;Get a
Grip&quot;</a>. Thus began a period of intense musical accumulation by yours truly.</p><p>But remember when I said the CD format contained within it the seeds of its own demise? Quoth <a href="https://en.wikipedia.org/wiki/MP3#Background">Wikipedia</a>, and verily thus:</p><blockquote><p>In 1894, the American physicist Alfred M. Mayer reported that a tone could be rendered inaudible by another tone of lower frequency. In 1959, Richard Ehmer described a complete set of auditory curves regarding this phenomenon. Between 1967 and 1974, Eberhard Zwicker did work in the areas of tuning and masking of critical frequency-bands, which in turn built on the fundamental research in the area from Harvey Fletcher and his collaborators at Bell Labs</p></blockquote><p>You see where this is going, right? Good, because I wouldn&apos;t want to condescend to you by mentioning things like space-efficient compression with transforming Fouriers into <a href="https://en.wikipedia.org/wiki/Fast_Fourier_transform">Fast
Fouriers</a> modifying discrete cosines and other trivia that would bore any 3rd grade physics student.</p><p>So anyway, <a href="https://en.wikipedia.org/wiki/Fraunhofer_Society">some Germans</a> scribbled down an algorithm and convinced the <a href="https://en.wikipedia.org/wiki/Moving_Picture_Experts_Group">Motion Picture Experts
Group</a> to standardise it as the MPEG-1 Audio Layer III format, and those Germans somehow patented this &quot;innovation&quot; that no one had even bothered to write down because it was so completely obvious to anyone who bothered to think about it for more than the time a CD takes to revolve once or twice. This patent enraged such people as <a href="https://en.wikipedia.org/wiki/Richard_Stallman">Richard Stallman</a> (who, to be fair, is easily enraged by such minor things as people objecting to his mysogyny and <a href="https://en.wikipedia.org/wiki/Richard_Stallman#Comments_about_Jeffrey_Epstein_scandal">opinions on the acceptability of romantic relationships with
minors</a>), leading some people to develop a technically superior <strong>and</strong> <a href="https://en.wiktionary.org/wiki/free_as_in_beer">free as in
beer</a> audio coding format that they named after a <a href="https://en.wikipedia.org/wiki/List_of_Discworld_characters#Vorbis">Terry Pratchett
character</a> and a <a href="https://en.wikipedia.org/wiki/Netrek">clone</a> of a [clone](<a href="https://en.wikipedia.org/wiki/Empire_(PLATO)">https://en.wikipedia.org/wiki/Empire_(PLATO)</a>) of <a href="https://en.wikipedia.org/wiki/Spacewar!">Spacewar!</a>. The name, if you haven&apos;t guessed it by now from the copious amount of clues I&apos;ve dropped here (just call me <a href="https://en.wikipedia.org/wiki/List_of_Cluedo_characters#Colonel_Mustard">Colonel
Mustard</a>) was <a href="https://en.wikipedia.org/wiki/Vorbis">Ogg Vorbis</a>.</p><p>By early summer 2005, I had accumulated a large quantity of CDs, which weighed roughly a metric shit-tonne. In addition to the strain they placed on my poor second- or third-hand bookshelves, I was due to move to Japan in the fall, and suspected that the sheer mass of my collection would interfere with the ability of whatever plane I would be taking to Tokyo to become airborne, which would be a real bummer. However, a solution presented itself, courtesy of one of the technical shortcomings of the compact disc technology itself.</p><p>Remember how CDs have this metallic layer that reflects the laser back at the sensor? Turns out that this layer is quite vulnerable, and a scratch that removes even a tiny bit of the metal results in the laser not being reflected as the disc rotates past the missing metal, which causes that block of data to be discarded by the player as faulty. To recover from this, the player would <a href="https://en.wikipedia.org/wiki/Skip_(audio_playback)#Basic_players">do one
of the
following</a>:</p><ol start="1"><li>Repeat the previous block of audio</li><li>Skip the faulty block</li><li>Try and retry to read it, causing a stopping and starting of the music</li></ol><p>For the listener, this is a sub-optimal auditory experience, and most listeners don&apos;t like any sub mixed in with their optimal.</p><p>Luckily, consumer-grade CD recorders started appearing in the mid-90s, when [HP
released the first sub-<span class="formula">1000 model](https://en.wikipedia.org/wiki/CD-R). As a
teenager in the 90s, I certainly couldn&apos;t afford </span>1000, but in 1997, I started working as a PC repair technician, and we had a CD &quot;burner&quot; (as they were known back then, not to be confused with a &quot;burner&quot; phone, which didn&apos;t exist back then, at least not in the cultural zeitgeist of the time) for such uses as device drivers which were too big to fit on a 3.5 inch &quot;floppy&quot; disk (those disks weren&apos;t actually floppy, but their 5.25 inch predecessors certainly were). I sensed an opportunity to protect my investment in digital music by &quot;ripping&quot; my discs (transferring the data on a CD onto the computer) and then burning them back to recordable CDs, at which point I could leave the original CD in its protective case and only expose my copy to the harsh elements.</p><p>Of course, one could also leave the ripped audio on one&apos;s computer and listen to it at any time of one&apos;s choosing, which was really convenient since you didn&apos;t have to change CDs when the disc ended or you were just in the mood to listen to something different. The problem is that the raw audio from the CDs (encoded in the WAV format that even modern people are probably familiar with) was fairly large, with a single CD taking up as much as 700MB of space. That may not seem like much until you know that most personal computers in the late 90s had somewhere between 3 and 16 GB of storage, which was enough to store between 20 and 220 CDs, assuming you had nothing else on the drive, which was unlikely since you needed to have software for playing back the files which meant you needed an operating system such as Windows...</p><p>To move somewhat more rapidly to the point, one solution to the issue of space was rooted in an even older technology than the compact disc (though younger than the venerable phonograph record): the cassette tape! A cassette tape was... OK, given that I&apos;ve written nigh upon 2000 words at this point without mentioning Soundcloud or ClojureScript, perhaps I&apos;ll just link you to <a href="https://en.wikipedia.org/wiki/Cassette_tape">the
Wikipedia article on the cassette
tape</a> instead of attempting to explain how it works in an amusing (to me) fashion. Interesting (to me) sidenote, though: the cassette tape was also invented by our intrepid Dutch friends over at Philips! 🤯</p><p>And my point was... oh yeah, mixtapes! Cassette tapes were one of the first media that gave your average consumer access to a recorder at an affordable price (the earliest such media that I know of was the <a href="https://en.wikipedia.org/wiki/Reel-to-reel_audio_tape_recording">reel-to-reel
tape</a>, which was like a giant cassette tape without the plastic bit that protects the tape), and in addition to <a href="https://genius.com/Mop-follow-instructions-lyrics">stuffing tissue in the top of a tape just to record Marley
Marl</a> that we borrowed from our friend down the street, we also made &quot;mixtapes&quot;, an alchemical process whereby we boiled down our tape collection and extracted only the bangers (or tear-jerkers, or hopelessly optimistic love songs, or whatever mood we were trying to capture) and recorded those onto a tape, giving us 60 minutes of magic to blare in our cars or hand to that cutie in chemistry class to try and win their affection.</p><p>With the invention of the CD and the burner, we were back in the mixtape business, and this time we had up to 80 minutes to express ourselves. By the time I entered university back in 19*cough*, I had saved up enough from my job as a PC technician to buy my own burner, and at university, I gained somewhat of a reputation as a mixtape maestro. People would bring me a stack of CDs and ask me to produce a mixtape to light up the dancefloor or get heads nodding along to the dope-ass DJs of the time (I&apos;m looking at you, <a href="https://en.wikipedia.org/wiki/DJ_Premier">Premo</a>!), and also pick a cheeky title to scrawl onto the recordable CD in Sharpie. The one that sticks in my memory was called &quot;The Wu Tang Clan ain&apos;t Nothin&apos; to Fuck With&quot;...</p><p>OK, but anyway, what if 80 minutes wasn&apos;t enough? Remember several minutes of rambling ago when I mentioned the MPEG-1 Audio Layer III format, and you may (or may not) have been like, &quot;WTF is that?&quot; What if I told you that MPEG-1 Audio Layer III is usually referred to by its initials (kinda): MP3? Now you see where I&apos;m going, right? By taking raw CD audio and compressing it with the MP3 encoding algorithm, one could now fit something like 140 songs onto a recordable CD (assuming 5MB per song and 700MB of capacity on the CD), or roughly 10 albums.</p><p>So back to the summer of 2005, when I&apos;m getting ready to move to Japan and I realise I can&apos;t realistically take all of my CDs with me. What do I do? I rip them onto my computer, encode them as not as MP3s but as Ogg Vorbis files because, y&apos;know, freedom and stuff, burn them onto a recordable CD along with ~9 of their compatriots, and pack them in a box, write their names on a <a href="https://en.wikipedia.org/wiki/Bill_of_lading">bill of
lading</a> which I tape to the box once it gets full, and then store the box in my parents&apos; basement. The freshly recorded backup CD goes into once of those big CD case thingies that we used to have:</p><p><img alt="A black Case Logic 200 CD capacity case" src="assets/2024-07-09-soundcljoud-cd-case.jpg" title="That&apos;s not a case, mate. This is a case!" /></p><p>My CD ripping frenzy was concluded in time for my move to Japan, but did not end there, because I ended up getting a job at <a href="https://amazon.co.jp">this bookstore that also sold CDs and
other stuff</a>, and publishers would send books and CDs to the buyers that worked at said bookstore, who would then decided if and how many copies of said books and CDs to buy for stock, and then usually put the books and CDs on a shelf in a printer room, where random bookstore employees such as myself were welcome to take them. So I got some cool books, and loads and loads of CDs, many of them from Japanese artists, which were promptly ripped, Ogg Vorbisified, and written to a 500GB USB hard drive that I had bought from the bookstore with my employee discount. Hurrah!</p><p>And thus when 2008 rolled around and I left Tokyo for Dublin, I did so with the vast majority of my music safely encoded into Ogg Vorbis format and written to spinning platters. Sadly, my sojourn on the shamrock shores of the Emerald Isle didn&apos;t last long, but happily, my next stop in Stockholm has been of the more permanent variety. By the time I moved here in 2010, Apple and Amazon&apos;s MP3 stores were starting to become passé, with streaming services replacing them as the Cool New Thing™, led a brash young Swedish startup called Spotify. And lo! did my collection of Ogg Vorbis files seem unnecessary, since I could now play every song ever recorded whenever I wanted to without having to lug around a hard drive full of files.</p><p>Except, at some point, some artists decided that they didn&apos;t want their music on Spotify, <a href="https://www.billboard.com/business/streaming/neil-young-spotify-joe-rogan-vaccines-letter-remove-music-1235022525/">some for admirable
reasons</a> and others for, um, other rea<span class="formula">on</span>, and now I couldn&apos;t listen to every song ever recorded whenever I wanted to without having to lug around a hard drive full of files. Plus Spotify never had a lot of the Japanese music that I had on file. This was suboptimal to be sure, but my laziness overwhelmed my desire to listen to all of my music, until one fateful day that I was sad about something and decided that I absolutely had to listen to some really sad country music, and the first song that came to mind was Garth Brook&apos;s &quot;<a href="https://www.youtube.com/watch?v=nIHWhUVxJh8">Much too Young to Feel this
Damn Old</a>&quot;. Much to my dismay, Garth was one of those artists who had withheld their catalogue from Spotify, meaning I had to resort to a cover of the song instead.</p><p>My sadness was replaced by rage, and I turned to Clojure to exact my revenge on Spotify for not having reached terms to licence music from one of the greatest Country &amp; Western recording artists of all time!</p><div class="markdown-heading"><h2 id="omg-finally-stuff-about-clojure">OMG finally stuff about Clojure</h2><a href="#omg-finally-stuff-about-clojure" class="anchor" aria-label="Permalink: OMG finally stuff about Clojure"><img src="assets/link.svg" /></a></div><p>If you wisely clicked the link at the beginning to skip my <a href="#Rambling_exposition">rambling
exposition</a>, welcome to a discussion of how I solved a serious problem caused by a certain <a href="https://en.wikipedia.org/wiki/Garth_Brooks">Country &amp; Western super-duper
star</a> (much like VA Beach legend <a href="https://en.wikipedia.org/wiki/Timbaland_&amp;_Magoo">Magoo</a>—RIP—<a href="https://genius.com/Timbaland-and-magoo-cop-that-shit-lyrics">on every CD, he
spits 48 bars</a>) wisely flicking the V at the odious <a href="https://en.wikipedia.org/wiki/Daniel_Ek">Daniel
Ek</a> and the terrible <a href="https://en.wikipedia.org/wiki/Tim_Cook">Tim
Cook</a> but <a href="https://uproxx.com/indie/garth-brooks-spotify-amazon-streaming-apple-music/">somehow being
A-OK</a> with <a href="https://en.wikipedia.org/wiki/Jeff_Bezos">an even more repulsive
billionaire</a>&apos;s streaming service.</p><p>To briefly recap, I really wanted to listen to some tear jerkin&apos; country, and Spotify doesn&apos;t carry Garth, but I had purchased <a href="https://en.wikipedia.org/wiki/Garth_Brooks_discography">all of his
albums</a> on CD back in the day (all the ones recorded before 1998, anyway) and ripped them into Ogg Vorbis format. Which is great, because I can listen to Garth anytime I want, as long as that desire occurs whilst I happen to be sitting within reach of the laptop onto which I copied all of those files. However, I like to do such things as not sit within reach of my laptop all the time, so now I&apos;m back to square almost one.</p><p>One day, as I was bemoaning my fate, I had a flash of inspiration! What if I put those files somewhere a web browser could reach them, and then I could listen to them anytime I happened to be sitting within reach of a web browser, which is basically always, since I have a web browser that fits in my pocket (I think it can also make &quot;phone calls&quot;, whatever those are). For example, I could upload them to <a href="https://soundcloud.com/">Soundcloud</a>. The only problem with that is that Soundcloud would claim that I was infringing on Garth&apos;s copyright, and they&apos;d kinda have a point, since not only could I listen to &quot;<a href="https://en.wikipedia.org/wiki/The_Beaches_of_Cheyenne">The Beaches of
Cheyenne</a>&quot; anytime I wanted to, having obtained a licence to do so by virtue of forking over $15 back in 1996 for a piece of plastic dipped in metal, but so could any random person with an internet connection.</p><p>This left me with only one option: clone Soundcloud! With Clojure! And call it Soundcljoud because I just can&apos;t help myself! And write a long and frankly absurdly self-indulgent blog post about it!</p><div class="markdown-heading"><h2 id="ok-really-clojure-now-i-promise">OK really Clojure now I promise</h2><a href="#ok-really-clojure-now-i-promise" class="anchor" aria-label="Permalink: OK really Clojure now I promise"><img src="assets/link.svg" /></a></div><p>As I mentioned, I have a bunch of Ogg Vorbis files on my laptop:</p><pre><code class="language-text">: jmglov@alhana; ls -1 ~/Music/g/Garth\ Brooks/
&apos;Beyond the Season&apos;
&apos;Double Live (Disc 1)&apos;
&apos;Double Live (Disc 2)&apos;
&apos;Fresh Horses&apos;
&apos;Garth Brooks&apos;
&apos;In Pieces&apos;
&apos;No Fences&apos;
&quot;Ropin&apos; the Wind&quot;
Sevens
&apos;The Chase&apos;
&apos;The Hits&apos;
</code></pre><p>I also have <a href="https://babashka.org/">Babashka</a>:</p><p><img alt="A logo of a face wearing a red hoodie with orange sunglasses featuring the Soundcloud logo" src="assets/2024-07-09-soundcljoud-bb.png" title="Above the clouds, infinite skills create miracles" /></p><p>So let&apos;s get to cloning!</p><p>The basic idea is to turn these Ogg Vorbis files into MP3 files, which the standard <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio">&lt;audio&gt; HTML
element</a> knows how to play, and then wrap a little ClojureScript around that element to stuff my sweet sweet country music into the <code>&lt;audio&gt;</code> element and then call it a day.</p><p>We&apos;ll accomplish the first part with Babashka and some command-line tools. I&apos;ll start by creating a new directory and dropping a <code>bb.edn</code> into it:</p><pre><code class="language-clojure">{:paths [&quot;src&quot; &quot;resources&quot;]}
</code></pre><p>Now I can create a <code>src/soundcljoud/main.clj</code> like this:</p><pre><code class="language-clojure">(ns soundcljoud.main
  (:require [babashka.fs :as fs]
            [babashka.process :as p]
            [clojure.string :as str]))
</code></pre><p>Firing up a REPL in my trusty Emacs with <code>C-c M-j</code> and then evaluating the buffer with <code>C-c C-k</code>, let me introduce Babashka to good ol&apos; Garth:</p><pre><code class="language-clojure">(comment

  (def dir (fs/file (fs/home) &quot;Music/g/Garth Brooks/Fresh Horses&quot;)) ; C-c C-v f c e
  ;; =&gt; #&apos;soundcljoud.main/dir

)
</code></pre><p>If you&apos;re a returning reader, you&apos;ll of course have translated <code>C-c C-k</code> to Control + c <pause> Control + k in your head and <code>C-c C-v f c e</code> to Control + c <pause> Control + v <pause> f <pause> c <pause> e and understood that they mean <code>cider-load-buffer</code> and <code>cider-pprint-eval-last-sexp-to-comment</code>, respectively. If you&apos;re a first-timer, what&apos;s happening here is that I&apos;m using a so-called <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a> (which protects the code within the <code>(comment)</code> form from evaluation when the buffer is evaluated) to evaluate forms one at a time as I REPL-drive my way towards a working program, for this is The Lisp Way.</p><p>Let&apos;s take a look at the Ogg Vorbis files in this directory:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
       (map str))
  ;; =&gt; (&quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - Ireland.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Fever.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - She&apos;s Every Woman.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Old Stuff.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - Rollin&apos;.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Beaches of Cheyenne.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - That Ol&apos; Wind.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - It&apos;s Midnight Cinderella.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Change.ogg&quot;
  ;;     &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - Cowboys and Angels.ogg&quot;)

)
</code></pre><p>Knowing my fastidious nature, I bet I wrote some useful tags into those Ogg files. Let&apos;s use <code>vorbiscomment</code> to check:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
       (map str)
       first
       (p/shell {:out :string} &quot;vorbiscomment&quot;)
       :out
       str/split-lines)
  ;; =&gt; [&quot;title=Ireland&quot; &quot;artist=Garth Brooks&quot; &quot;album=Fresh Horses&quot;]

)
</code></pre><p>Most excellent! With a tiny bit more work, we can turn these strings into a map:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
       (map str)
       first
       (p/shell {:out :string} &quot;vorbiscomment&quot;)
       :out
       str/split-lines
       (map #(let [[k v] (str/split % #&quot;=&quot;)] [(keyword k) v]))
       (into {}))
  ;; =&gt; {:title &quot;Ireland&quot;, :artist &quot;Garth Brooks&quot;, :album &quot;Fresh Horses&quot;}

)
</code></pre><p>And now I think we&apos;re ready to write a function that takes a filename and returns this info:</p><pre><code class="language-clojure">(defn track-info [filename]
  (-&gt;&gt; (p/shell {:out :string} &quot;vorbiscomment&quot; filename)
       :out
       str/split-lines
       (map #(let [[k v] (str/split % #&quot;=&quot;)] [(keyword k) v]))
       (into {})
       (merge {:filename filename})))
</code></pre><p>Now that we&apos;ve established that we have some Ogg Vorbis files with appropriate metadata, let&apos;s jump in the hammock for a second and think about how we want to proceed. What we&apos;re actually trying to accomplish is to make these tracks playable on the web. What if we create a podcast RSS feed per album, then we can use any podcast app to play the album?</p><div class="markdown-heading"><h2 id="faking-a-podcast-with-selmer">Faking a podcast with Selmer</h2><a href="#faking-a-podcast-with-selmer" class="anchor" aria-label="Permalink: Faking a podcast with Selmer"><img src="assets/link.svg" /></a></div><p>Let&apos;s go this route, since it seems like very little work! We&apos;ll start by creating a <a href="https://github.com/yogthos/Selmer">Selmer</a> template in <code>resources/album-feed.rss</code>:</p><pre><code class="language-xml">&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;
&lt;rss version=&quot;2.0&quot;
     xmlns:itunes=&quot;http://www.itunes.com/dtds/podcast-1.0.dtd&quot;
     xmlns:atom=&quot;http://www.w3.org/2005/Atom&quot;&gt;
  &lt;channel&gt;
    &lt;atom:link
        href=&quot;{{base-url}}/{{album|urlescape}}/album.rss&quot;
        rel=&quot;self&quot;
        type=&quot;application/rss+xml&quot;/&gt;
    &lt;title&gt;{{artist}} - {{album}}&lt;/title&gt;
    &lt;link&gt;{{link}}&lt;/link&gt;
    &lt;pubDate&gt;{{date}}&lt;/pubDate&gt;
    &lt;lastBuildDate&gt;{{date}}&lt;/lastBuildDate&gt;
    &lt;ttl&gt;60&lt;/ttl&gt;
    &lt;language&gt;en&lt;/language&gt;
    &lt;copyright&gt;All rights reserved&lt;/copyright&gt;
    &lt;webMaster&gt;{{owner-email}}&lt;/webMaster&gt;
    &lt;description&gt;Album: {{artist}} - {{album}}&lt;/description&gt;
    &lt;itunes:subtitle&gt;Album: {{artist}} - {{album}}&lt;/itunes:subtitle&gt;
    &lt;itunes:owner&gt;
      &lt;itunes:name&gt;{{owner-name}}&lt;/itunes:name&gt;
      &lt;itunes:email&gt;{{owner-email}}&lt;/itunes:email&gt;
    &lt;/itunes:owner&gt;
    &lt;itunes:author&gt;{{artist}}&lt;/itunes:author&gt;
    &lt;itunes:explicit&gt;no&lt;/itunes:explicit&gt;
    &lt;itunes:image href=&quot;{{image}}&quot;/&gt;
    &lt;image&gt;
      &lt;url&gt;{{image}}&lt;/url&gt;
      &lt;title&gt;{{artist}} - {{album}}&lt;/title&gt;
      &lt;link&gt;{{link}}&lt;/link&gt;
    &lt;/image&gt;
    {% for track in tracks %}
    &lt;item&gt;
      &lt;itunes:title&gt;{{track.title}}&lt;/itunes:title&gt;
      &lt;title&gt;{{track.title}}&lt;/title&gt;
      &lt;itunes:author&gt;{{artist}}&lt;/itunes:author&gt;
      &lt;enclosure
          url=&quot;{{base-url}}/{{artist|urlescape}}/{{album|urlescape}}/{{track.mp3-filename|urlescape}}&quot;
          length=&quot;{{track.mp3-size}}&quot; type=&quot;audio/mpeg&quot; /&gt;
      &lt;pubDate&gt;{{date}}&lt;/pubDate&gt;
      &lt;itunes:duration&gt;{{track.duration}}&lt;/itunes:duration&gt;
      &lt;itunes:episode&gt;{{track.number}}&lt;/itunes:episode&gt;
      &lt;itunes:episodeType&gt;full&lt;/itunes:episodeType&gt;
      &lt;itunes:explicit&gt;false&lt;/itunes:explicit&gt;
    &lt;/item&gt;
    {% endfor %}
  &lt;/channel&gt;
&lt;/rss&gt;
</code></pre><p>If you&apos;re not familiar with Selmer, the basic idea is that anything inside <code>{{}}</code> tags is a variable, and you also have some looping constructs like <code>{% for %}</code> and so on. So let&apos;s look at the variables that we slapped in that template:</p><p>General info:</p><ul><li>base-url</li><li>owner-name</li><li>owner-email</li></ul><p>Album-specific stuff:</p><ul><li>album</li><li>artist</li><li>link</li><li>date</li><li>image</li></ul><p>Track-specific stuff:</p><ul><li>track.title</li><li>track.mp3-filename</li><li>track.mp3-size</li><li>track.duration</li><li>track.number</li></ul><p>OK, so where are we going to get all this? The general info is easy; we can just decide what we want it to be and slap it in a variable:</p><pre><code class="language-clojure">(comment

  (def opts {:base-url &quot;http://localhost:1341&quot;
             :owner-name &quot;Josh Glover&quot;
             :owner-email &quot;jmglov@jmglov.net&quot;})
  ;; =&gt; #&apos;soundcljoud.main/opts

)
</code></pre><p>The album-specific stuff is a little more challenging. <code>album</code> and <code>artist</code> we can get from our <code>track-info</code> function, and <code>link</code> can be something like <code>base-url</code> + <code>artist</code> + <code>album</code>, but what about <code>date</code> (the date the album was released) and <code>image</code> (the cover image of the album)? Well, for this we can use a music database that offers API access, such as <a href="https://www.discogs.com/">Discogs</a>. Let&apos;s start by creating an account and then visiting the <a href="https://www.discogs.com/settings/developers">Developers settings
page</a> to generate a personal access token, which we&apos;ll save in <code>resources/discogs-token.txt</code>. With this in hand, let&apos;s try searching for an album. We&apos;ll need to add an HTTP client (luckily, <a href="https://github.com/babashka/http-client">Babashka ships with one</a>), a JSON parser (luckily, <a href="https://github.com/dakrone/cheshire">Babashka ships with one</a>) and a way to load the <code>resources/discogs-token.txt</code> to our namespace, then we can use the API.</p><pre><code class="language-clojure">(ns soundcljoud.main
  (:require [babashka.fs :as fs]
            [babashka.process :as p]
            [clojure.string :as str]
            ;; ⬇⬇⬇ New stuff ⬇⬇⬇
            [babashka.http-client :as http]
            [cheshire.core :as json]
            [clojure.java.io :as io]))

(comment

  (def discogs-token (-&gt; (io/resource &quot;discogs-token.txt&quot;)
                         slurp
                         str/trim-newline))
  ;; =&gt; #&apos;soundcljoud.main/discogs-token

  (def album-info (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
                       (map str)
                       first
                       track-info))
  ;; =&gt; #&apos;soundcljoud.main/album-info

  (-&gt; (http/get &quot;https://api.discogs.com/database/search&quot;
                {:query-params {:artist (:artist album-info)
                                :release_title (:album album-info)
                                :token discogs-token}
                 :headers {:User-Agent &quot;SoundCljoud/0.1 +https://jmglov.net&quot;}})
      :body
      (json/parse-string keyword)
      :results
      first)
  ;;  {:format [&quot;CD&quot; &quot;Album&quot;],
  ;;   :master_url &quot;https://api.discogs.com/masters/212114&quot;,
  ;;   :cover_image
  ;;   &quot;https://i.discogs.com/0eLXmM1tK1grkH8cstgDT6eV2TlL0NvgWPZBoyScJ_8/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTY4NDcx/Ny0xNzE3NDU5MDIy/LTMxNjguanBlZw.jpeg&quot;,
  ;;   :title &quot;Garth Brooks - Fresh Horses&quot;,
  ;;   :style [&quot;Country Rock&quot; &quot;Pop Rock&quot;],
  ;;   :year &quot;1995&quot;,
  ;;   :id 212114,
  ;;   ...
  ;;  }

)
</code></pre><p>This looks very promising indeed! We now have the release year, which we can put in our RSS feed as <code>date</code>, and the cover image, which we can put in <code>image</code>. Now let&apos;s grab info for the tracks:</p><pre><code class="language-clojure">(comment

  (def master-url (:master_url *1))
  ;; =&gt; #&apos;soundcljoud.main/master-url

)
</code></pre><p>That <code>(:master_url *1)</code> thing might be new to you, so let me explain before we continue. The REPL keeps track of the result of the last three evaluations, and binds them to <code>*1</code>, <code>*2</code>, and <code>*3</code>. So <code>(:master_url *1)</code> says &quot;give me the <code>:master_url</code> key of the result of the last evaluation, which I assume is a map or I&apos;m <a href="https://www.urbandictionary.com/define.php?term=shit%20out%20of%20luck">SOL</a>&quot;.</p><p>OK, back to the fetching track info:</p><pre><code class="language-clojure">(comment

  (def master-url (:master_url *1))
  ;; =&gt; #&apos;soundcljoud.main/master-url

  (-&gt; (http/get master-url
                {:query-params {:token discogs-token}
                 :headers {:User-Agent &quot;SoundCljoud/0.1 +https://jmglov.net&quot;}})
      :body
      (json/parse-string keyword)
      :tracklist)
  ;; =&gt; [{:position &quot;1&quot;,
  ;;      :title &quot;The Old Stuff&quot;,
  ;;      :duration &quot;4:12&quot;}
  ;;     {:position &quot;2&quot;,
  ;;      :title &quot;Cowboys And Angels&quot;,
  ;;      :duration &quot;3:16&quot;}
  ;;     ...
  ;;    ]

)
</code></pre><p>We now have all the pieces, so let&apos;s clean this up by turning it into a series of functions:</p><pre><code class="language-clojure">(def discogs-base-url &quot;https://api.discogs.com&quot;)
(def user-agent &quot;SoundCljoud/0.1 +https://jmglov.net&quot;)

(defn load-token []
  (-&gt; (io/resource &quot;discogs-token.txt&quot;)
      slurp
      str/trim-newline))

(defn api-get
  ([token path]
   (api-get token path {}))
  ([token path opts]
   (let [url (if (str/starts-with? path discogs-base-url)
               path
               (str discogs-base-url path))]
     (-&gt; (http/get url
                   (merge {:headers {:User-Agent user-agent}}
                          opts))
         :body
         (json/parse-string keyword)))))

(defn search-album [token {:keys [artist album]}]
  (api-get token &quot;/database/search&quot;
           {:query-params {:artist artist
                           :release_title album
                           :token token}}))

(defn album-info [token {:keys [artist album] :as metadata}]
  (let [{:keys [cover_image master_url year]}
        (-&gt;&gt; (search-album token metadata)
             :results
             first)
        {:keys [tracklist]} (api-get token master_url)]
    (merge metadata {:link master_url
                     :image cover_image
                     :year year
                     :tracks (map (fn [{:keys [title position]}]
                                    {:title title
                                     :artist artist
                                     :album album
                                     :number position
                                     :year year})
                                  tracklist)})))
</code></pre><p>Putting it all together, let&apos;s load all the album info in a format that&apos;s amenable to stuffing into our RSS template:</p><pre><code class="language-clojure">(comment

  (let [tracks (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
                    (map (comp track-info fs/file)))]
    (album-info (load-token) (first tracks))))
  ;; =&gt; {:title &quot;Ireland&quot;,
  ;;     :artist &quot;Garth Brooks&quot;,
  ;;     :album &quot;Fresh Horses&quot;,
  ;;     :link &quot;https://api.discogs.com/masters/212114&quot;,
  ;;     :image &quot;https://i.discogs.com/0eLXmM1tK1grkH8cstgDT6eV2TlL0NvgWPZBoyScJ_8/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTY4NDcx/Ny0xNzE3NDU5MDIy/LTMxNjguanBlZw.jpeg&quot;,
  ;;     :year &quot;1995&quot;,
  ;;     :tracks
  ;;     ({:title &quot;The Old Stuff&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :number 1}
  ;;      {:title &quot;Cowboys and Angels&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :number 2}
  ;;      ...
  ;;      {:title &quot;Ireland&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :number 10})}

)
</code></pre><p>Now that we have a big ol&apos; map containing all the metadata an RSS feed could possibly desire, let&apos;s use Selmer to turn our template into some actual RSS! We&apos;ll need to add Selmer itself to our namespace, and also grab some <code>java.time</code> stuff in order to produce the <a href="http://www.faqs.org/rfcs/rfc2822.html">RFC 2822</a> datetime <a href="https://podcasters.apple.com/support/823-podcast-requirements">required by the podcast RSS
format</a>, then we can get onto the templating itself.</p><pre><code class="language-clojure">(ns soundcljoud.main
  (:require ...
            [selmer.parser :as selmer])
  (:import (java.time ZonedDateTime)
           (java.time.format DateTimeFormatter)))

(def dt-formatter
  (DateTimeFormatter/ofPattern &quot;EEE, dd MMM yyyy HH:mm:ss xxxx&quot;))

(defn -&gt;rfc-2822-date [date]
  (-&gt; (Integer/parseInt date)
      (ZonedDateTime/of 1 1 0 0 0 0 java.time.ZoneOffset/UTC)
      (.format dt-formatter)))

(defn album-feed [opts album-info]
  (let [template (-&gt; (io/resource &quot;album-feed.rss&quot;) slurp)]
    (-&gt;&gt; (update album-info :tracks
                 (partial map #(update % :mp3-filename fs/file-name)))
         (merge opts {:date (-&gt;rfc-2822-date (:year album-info))})
         (selmer/render template))))

(comment

  (let [tracks (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
                    (map (comp track-info fs/file)))]
    (-&gt;&gt; (album-info (load-token) (first tracks))
         (album-feed opts)))
  ;; =&gt; java.lang.NullPointerException soundcljoud.main
  ;; {:type :sci/error, :line 3, :column 53, ...}
  ;;  at sci.impl.utils$rethrow_with_location_of_node.invokeStatic (utils.cljc:135)
  ;;  ...
  ;; Caused by: java.lang.NullPointerException: null
  ;;  at babashka.fs$file_name.invokeStatic (fs.cljc:182)
  ;;  ...

)
</code></pre><p>Oops! It appears that <code>fs/file-name</code> is angry at us. Searching for it, we identify the culprit:</p><pre><code class="language-clojure">(partial map #(update % :mp3-filename fs/file-name))
</code></pre><p>Nowhere in our <code>album-info</code> map have we mentioned <code>:mp3-filename</code>, which actually makes sense given that we only have an Ogg Vorbis file and not an MP3. Let&apos;s see what we can do about that, shall we? (Spoiler: we shall.)</p><div class="markdown-heading"><h2 id="converting-from-ogg-to-mp3">Converting from Ogg to MP3</h2><a href="#converting-from-ogg-to-mp3" class="anchor" aria-label="Permalink: Converting from Ogg to MP3"><img src="assets/link.svg" /></a></div><p>We&apos;ll honour Rich Hickey by decomplecting this problem into two problems:</p><ol start="1"><li>Converting an Ogg Vorbis file into a WAV</li><li>Converting a WAV into an MP3</li></ol><p>Let&apos;s start with problem #1 by taking a look at what we get back from <code>album-info</code>:</p><pre><code class="language-clojure">(comment

  (let [tracks (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
                    (map (comp track-info fs/file)))]
    (album-info (load-token) (first tracks))))
  ;; =&gt; {:title &quot;Ireland&quot;,
  ;;     :artist &quot;Garth Brooks&quot;,
  ;;     :album &quot;Fresh Horses&quot;,
  ;;     :link &quot;https://api.discogs.com/masters/212114&quot;,
  ;;     :image &quot;https://i.discogs.com/0eLXmM1tK1grkH8cstgDT6eV2TlL0NvgWPZBoyScJ_8/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTY4NDcx/Ny0xNzE3NDU5MDIy/LTMxNjguanBlZw.jpeg&quot;,
  ;;     :year &quot;1995&quot;,
  ;;     :tracks
  ;;     ({:title &quot;The Old Stuff&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :number 1}
  ;;      {:title &quot;Cowboys and Angels&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :number 2}
  ;;      ...
  ;;      {:title &quot;Ireland&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :number 10})}

)
</code></pre><p>The problem here is that we&apos;ve lost the filename that came from <code>fs/glob</code>, so we have no idea which files we need to convert. Let&apos;s fix this by tweaking <code>album-info</code> to take the token and directory, rather than just the track info of the first file in the directory:</p><pre><code class="language-clojure">(defn normalise-title [title]
  (-&gt; title
      str/lower-case
      (str/replace #&quot;[^a-z]&quot; &quot;&quot;)))

(defn album-info [token tracks]
  (let [{:keys [artist album] :as track} (first tracks)
        track-filename (-&gt;&gt; tracks
                            (map (fn [{:keys [filename title]}]
                                   [(normalise-title title) filename]))
                            (into {}))
        {:keys [cover_image master_url year]}
        (-&gt;&gt; (search-album token track)
             :results
             first)
        {:keys [tracklist]} (api-get token master_url)]
    (merge track {:link master_url
                  :image cover_image
                  :year year
                  :tracks (map (fn [{:keys [title position]}]
                                 {:title title
                                  :artist artist
                                  :album album
                                  :number position
                                  :year year
                                  :filename (track-filename (normalise-title title))})
                               tracklist)})))

(comment

  (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
       (map (comp track-info fs/file))
       (album-info (load-token)))
  ;; =&gt; {:artist &quot;Garth Brooks&quot;,
  ;;     :album &quot;Fresh Horses&quot;,
  ;;     :link &quot;https://api.discogs.com/masters/212114&quot;,
  ;;     :image
  ;;     &quot;https://i.discogs.com/0eLXmM1tK1grkH8cstgDT6eV2TlL0NvgWPZBoyScJ_8/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTY4NDcx/Ny0xNzE3NDU5MDIy/LTMxNjguanBlZw.jpeg&quot;,
  ;;     :year &quot;1995&quot;,
  ;;     :tracks
  ;;     ({:title &quot;The Old Stuff&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :number &quot;1&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :filename
  ;;       #object[java.io.File 0x96d79f0 &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Old Stuff.ogg&quot;]}
  ;; ...
  ;;      {:title &quot;Ireland&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :number &quot;10&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :filename
  ;;       #object[java.io.File 0x13968577 &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - Ireland.ogg&quot;]})}

)
</code></pre><p>Much better! Given this, let&apos;s convert this file into a WAV:</p><pre><code class="language-clojure">(comment

  (def info (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
                 (map (comp track-info fs/file))
                 (album-info (load-token))))
  ;; =&gt; #&apos;soundcljoud.main/info

  (def tmpdir (fs/create-dirs &quot;/tmp/soundcljoud&quot;))
  ;; =&gt; #&apos;soundcljoud.main/tmpdir

  (let [{:keys [filename] :as track} (-&gt;&gt; info :tracks first)
        out-filename (fs/file tmpdir (str/replace (fs/file-name filename)
                                                  &quot;.ogg&quot; &quot;.wav&quot;))]
    (p/shell &quot;oggdec&quot; &quot;-o&quot; out-filename filename)
    (assoc track :wav-filename out-filename))
  ;; =&gt; {:title &quot;The Old Stuff&quot;,
  ;;     :artist &quot;Garth Brooks&quot;,
  ;;     :album &quot;Fresh Horses&quot;,
  ;;     :number &quot;1&quot;,
  ;;     :year &quot;1995&quot;,
  ;;     :filename
  ;;     #object[java.io.File 0x96d79f0 &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Old Stuff.ogg&quot;],
  ;;     :wav-filename
  ;;     #object[java.io.File 0x4221dcb2 &quot;/tmp/soundcljoud/Garth Brooks - The Old Stuff.wav&quot;]}

)
</code></pre><p>Lovely! Let&apos;s make a nice function out of this:</p><pre><code class="language-clojure">(defn ogg-&gt;wav [{:keys [filename] :as track} tmpdir]
  (let [out-filename (fs/file tmpdir (str/replace (fs/file-name filename)
                                                  &quot;.ogg&quot; &quot;.wav&quot;))]
    (println (format &quot;Converting %s -&gt; %s&quot; filename out-filename))
    (p/shell &quot;oggdec&quot; &quot;-o&quot; out-filename filename)
    (assoc track :wav-filename out-filename)))
</code></pre><p>Now let&apos;s see if problem #2 is equally tractable.</p><pre><code class="language-clojure">(comment

  (let [{:keys [filename artist album title year number] :as track}
        (-&gt;&gt; info :tracks first)
        wav-file (fs/file tmpdir
                          (-&gt; (fs/file-name filename)
                              (str/replace #&quot;[.][^.]+$&quot; &quot;.wav&quot;)))
        mp3-file (str/replace wav-file &quot;.wav&quot; &quot;.mp3&quot;)
        ffmpeg-args [&quot;ffmpeg&quot; &quot;-i&quot; wav-file
                     &quot;-vn&quot;  ; no video
                     &quot;-q:a&quot; &quot;2&quot;  ; dynamic bitrate averaging 192 KB/s
                     &quot;-y&quot;  ; overwrite existing files without prompting
                     mp3-file]]
    (p/shell &quot;ffmpeg&quot; &quot;-i&quot; wav-file
             &quot;-vn&quot;       ; no video
             &quot;-q:a&quot; &quot;2&quot;  ; dynamic bitrate averaging 192 KB/s
             &quot;-y&quot;        ; overwrite existing files without prompting
             mp3-file))
  ;; =&gt; {:exit 0,
  ;;     ...
  ;;     }

  (fs/size &quot;/tmp/soundcljoud/Garth Brooks - The Old Stuff.mp3&quot;)
  ;; =&gt; 5941943

)
</code></pre><p>Nice! There&apos;s one annoying thing about this, though. My Ogg Vorbis file had metadata tags telling me stuff and also things about the contents of the file, whereas my MP3 is inscrutable, save for the filename. Let&apos;s ameliorate this with our good friend <a href="https://id3v2.sourceforge.net/">id3v2</a>:</p><pre><code class="language-clojure">(comment

  (let [{:keys [filename artist album title year number] :as track}
        (-&gt;&gt; info :tracks first)
        wav-file (fs/file tmpdir
                          (-&gt; (fs/file-name filename)
                              (str/replace #&quot;[.][^.]+$&quot; &quot;.wav&quot;)))
        mp3-file (str/replace wav-file &quot;.wav&quot; &quot;.mp3&quot;)
        ffmpeg-args [&quot;ffmpeg&quot; &quot;-i&quot; wav-file
                     &quot;-vn&quot;  ; no video
                     &quot;-q:a&quot; &quot;2&quot;  ; dynamic bitrate averaging 192 KB/s
                     &quot;-y&quot;  ; overwrite existing files without prompting
                     mp3-file]]
    (p/shell &quot;id3v2&quot;
             &quot;-a&quot; artist &quot;-A&quot; album &quot;-t&quot; title &quot;-y&quot; year &quot;-T&quot; number
             mp3-file))
  ;; =&gt; {:exit 0,
  ;;     ...
  ;;     }

  (-&gt;&gt; (p/shell {:out :string}
                &quot;id3v2&quot; &quot;--list&quot;
                &quot;/tmp/soundcljoud/Garth Brooks - The Old Stuff.mp3&quot;)
       :out
       str/split-lines)
  ;; =&gt; [&quot;id3v1 tag info for /tmp/soundcljoud/Garth Brooks - The Old Stuff.mp3:&quot;
  ;;     &quot;Title  : The Old Stuff                   Artist: Garth Brooks&quot;
  ;;     &quot;Album  : Fresh Horses                    Year: 1995, Genre: Unknown (255)&quot;
  ;;     &quot;Comment:                                 Track: 1&quot;
  ;;     &quot;id3v2 tag info for /tmp/soundcljoud/Garth Brooks - The Old Stuff.mp3:&quot;
  ;;     &quot;TPE1 (Lead performer(s)/Soloist(s)): Garth Brooks&quot;
  ;;     &quot;TALB (Album/Movie/Show title): Fresh Horses&quot;
  ;;     &quot;TIT2 (Title/songname/content description): The Old Stuff&quot;
  ;;     &quot;TRCK (Track number/Position in set): 1&quot;]

)
</code></pre><p>There&apos;s an awful lot of copy and paste code here, so let&apos;s consolidate MP3 conversion and tag writing into a single function. We should also make sure that function returns a track info map that contains all the good stuff that our RSS template needs. Casting our mind back to the track-specific stuff, we need:</p><ul><li>track.title</li><li>track.number</li><li>track.mp3-filename</li><li>track.mp3-size</li><li>track.duration</li></ul><p><code>mp3-filename</code> we have, and <code>m3-size</code> we can get with the same <code>fs/size</code> call that we previously used to check if the MP3 file existed. <code>duration</code> is a little more interesting. What the RSS feed standard is looking for is a duration in one of the following formats:</p><ul><li>hours:minutes:seconds</li><li>minutes:seconds</li><li>seconds</li></ul><p>We can use the <a href="https://ffmpeg.org/ffprobe.html">ffprobe</a> tool that ships with <a href="https://ffmpeg.org/">FFmpeg</a> to get some info about the MP3:</p><pre><code class="language-clojure">(comment

  (-&gt; (p/shell {:out :string}
               &quot;ffprobe -v quiet -print_format json -show_format -show_streams&quot;
               &quot;/tmp/soundcljoud/01 - Garth Brooks - The Old Stuff.mp3&quot;)
      :out
      (json/parse-string keyword)
      :streams
      first)
  ;; =&gt; {:tags {:encoder &quot;Lavc60.3.&quot;},
  ;;     :r_frame_rate &quot;0/0&quot;,
  ;;     :sample_rate &quot;44100&quot;,
  ;;     :channel_layout &quot;stereo&quot;,
  ;;     :channels 2,
  ;;     :duration &quot;252.473469&quot;,
  ;;     :codec_name &quot;mp3&quot;,
  ;;     :bit_rate &quot;188278&quot;,
  ;;     ...
  ;;     :codec_tag &quot;0x0000&quot;}

)
</code></pre><p>Cool! <code>ffprobe</code> reports duration in seconds (with some extra nanoseconds that we don&apos;t need), so let&apos;s write a function that grabs the duration and chops off everything after the decimal place, then we can consolidate the WAV -&gt; MP3 conversion and ID3 tag writing in another function:</p><pre><code class="language-clojure">(defn mp3-duration [filename]
  (-&gt; (p/shell {:out :string}
               &quot;ffprobe -v quiet -print_format json -show_format -show_streams&quot;
               filename)
      :out
      (json/parse-string keyword)
      :streams
      first
      :duration
      (str/replace #&quot;[.]\d+$&quot; &quot;&quot;)))

(defn wav-&gt;mp3 [{:keys [filename artist album title year number] :as track} tmpdir]
  (let [wav-file (fs/file tmpdir
                          (-&gt; (fs/file-name filename)
                              (str/replace #&quot;[.][^.]+$&quot; &quot;.wav&quot;)))
        mp3-file (str/replace wav-file &quot;.wav&quot; &quot;.mp3&quot;)
        ffmpeg-args [&quot;ffmpeg&quot; &quot;-i&quot; wav-file
                     &quot;-vn&quot;  ; no video
                     &quot;-q:a&quot; &quot;2&quot;  ; dynamic bitrate averaging 192 KB/s
                     &quot;-y&quot;  ; overwrite existing files without prompting
                     mp3-file]
        id3v2-args [&quot;id3v2&quot;
                    &quot;-a&quot; artist &quot;-A&quot; album &quot;-t&quot; title &quot;-y&quot; year &quot;-T&quot; number
                    mp3-file]]
    (println (format &quot;Converting %s -&gt; %s&quot; wav-file mp3-file))
    (apply println (map str ffmpeg-args))
    (apply p/shell ffmpeg-args)
    (println &quot;Writing ID3 tag&quot;)
    (apply println id3v2-args)
    (apply p/shell (map str id3v2-args))
    (assoc track
           :mp3-filename mp3-file
           :mp3-size (fs/size mp3-file)
           :duration (mp3-duration mp3-file))))

(comment

  (-&gt; info :tracks first (wav-&gt;mp3 tmpdir))
  ;; =&gt; {:number &quot;1&quot;,
  ;;     :duration &quot;252&quot;,
  ;;     :artist &quot;Garth Brooks&quot;,
  ;;     :title &quot;The Old Stuff&quot;,
  ;;     :year &quot;1995&quot;,
  ;;     :filename
  ;;     #object[java.io.File 0x96d79f0 &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Old Stuff.ogg&quot;],
  ;;     :mp3-filename &quot;/tmp/soundcljoud/Garth Brooks - The Old Stuff.mp3&quot;,
  ;;     :album &quot;Fresh Horses&quot;,
  ;;     :mp3-size 5943424}

)
</code></pre><p>Looking good! Now we should have everything we need for the RSS feed, so let&apos;s try to put it all together:</p><pre><code class="language-clojure">(defn process-track [track tmpdir]
  (-&gt; track
      (ogg-&gt;wav tmpdir)
      (wav-&gt;mp3 tmpdir)))

(defn process-album [opts dir]
  (let [info (-&gt;&gt; (fs/glob dir &quot;*.ogg&quot;)
                  (map (comp track-info fs/file))
                  (album-info (load-token)))
        tmpdir (fs/create-temp-dir {:prefix &quot;soundcljoud.&quot;})]
    (spit (fs/file tmpdir &quot;album.rss&quot;) (rss/album-feed opts info))
    (assoc info :out-dir tmpdir)))

(comment

  (process-album opts dir)
  ;; =&gt; {:out-dir &quot;/tmp/soundcljoud.12524185230907219576&quot;
  ;;     :artist &quot;Garth Brooks&quot;,
  ;;     :album &quot;Fresh Horses&quot;,
  ;;     :link &quot;https://api.discogs.com/masters/212114&quot;,
  ;;     :image
  ;;     &quot;https://i.discogs.com/0eLXmM1tK1grkH8cstgDT6eV2TlL0NvgWPZBoyScJ_8/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTY4NDcx/Ny0xNzE3NDU5MDIy/LTMxNjguanBlZw.jpeg&quot;,
  ;;     :year &quot;1995&quot;,
  ;;     :tracks
  ;;     ({:number &quot;1&quot;,
  ;;       :duration &quot;252&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :title &quot;The Old Stuff&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :filename
  ;;       #object[java.io.File 0x344bc92b &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - The Old Stuff.ogg&quot;],
  ;;       :mp3-filename
  ;;       &quot;/tmp/soundcljoud.12524185230907219576/Garth Brooks - The Old Stuff.mp3&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :wav-filename
  ;;       #object[java.io.File 0x105830d2 &quot;/tmp/soundcljoud.12524185230907219576/Garth Brooks - The Old Stuff.wav&quot;],
  ;;       :mp3-size 5943424}
  ;;      ...
  ;;      {:number &quot;10&quot;,
  ;;       :duration &quot;301&quot;,
  ;;       :artist &quot;Garth Brooks&quot;,
  ;;       :title &quot;Ireland&quot;,
  ;;       :year &quot;1995&quot;,
  ;;       :filename
  ;;       #object[java.io.File 0x59ba6e31 &quot;~/Music/g/Garth Brooks/Fresh Horses/Garth Brooks - Ireland.ogg&quot;],
  ;;       :mp3-filename
  ;;       &quot;/tmp/soundcljoud.12524185230907219576/Garth Brooks - Ireland.mp3&quot;,
  ;;       :album &quot;Fresh Horses&quot;,
  ;;       :wav-filename
  ;;       #object[java.io.File 0x4de1472 &quot;/tmp/soundcljoud.12524185230907219576/Garth Brooks - Ireland.wav&quot;],
  ;;       :mp3-size 6969472})}
)
</code></pre><p>We also have a <code>/tmp/soundcljoud.12524185230907219576/album.rss</code> file containing:</p><pre><code class="language-xml">&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;
&lt;rss version=&quot;2.0&quot;
     xmlns:itunes=&quot;http://www.itunes.com/dtds/podcast-1.0.dtd&quot;
     xmlns:atom=&quot;http://www.w3.org/2005/Atom&quot;&gt;
  &lt;channel&gt;
    &lt;title&gt;Garth Brooks - Fresh Horses&lt;/title&gt;
    &lt;link&gt;https://api.discogs.com/masters/212114&lt;/link&gt;
    &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
    &lt;itunes:subtitle&gt;Album: Garth Brooks - Fresh Horses&lt;/itunes:subtitle&gt;
    &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
    &lt;itunes:image href=&quot;https://i.discogs.com/0eLXmM1tK1grkH8cstgDT6eV2TlL0NvgWPZBoyScJ_8/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTY4NDcx/Ny0xNzE3NDU5MDIy/LTMxNjguanBlZw.jpeg&quot;/&gt;
    
    &lt;item&gt;
      &lt;itunes:title&gt;The Old Stuff&lt;/itunes:title&gt;
      &lt;title&gt;The Old Stuff&lt;/title&gt;
      &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
      &lt;enclosure
          url=&quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/01+-+Garth+Brooks+-+The+Old+Stuff.mp3&quot;
          length=&quot;5943424&quot; type=&quot;audio/mpeg&quot; /&gt;
      &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
      &lt;itunes:duration&gt;252&lt;/itunes:duration&gt;
      &lt;itunes:episode&gt;1&lt;/itunes:episode&gt;
      &lt;itunes:episodeType&gt;full&lt;/itunes:episodeType&gt;
      &lt;itunes:explicit&gt;false&lt;/itunes:explicit&gt;
    &lt;/item&gt;

    ...
    
    &lt;item&gt;
      &lt;itunes:title&gt;Ireland&lt;/itunes:title&gt;
      &lt;title&gt;Ireland&lt;/title&gt;
      &lt;itunes:author&gt;Garth Brooks&lt;/itunes:author&gt;
      &lt;enclosure
          url=&quot;http://localhost:1341/Garth+Brooks/Fresh+Horses/Garth+Brooks+-+Ireland.mp3&quot;
          length=&quot;6969472&quot; type=&quot;audio/mpeg&quot; /&gt;
      &lt;pubDate&gt;Sun, 01 Jan 1995 00:00:00 +0000&lt;/pubDate&gt;
      &lt;itunes:duration&gt;301&lt;/itunes:duration&gt;
      &lt;itunes:episode&gt;10&lt;/itunes:episode&gt;
      &lt;itunes:episodeType&gt;full&lt;/itunes:episodeType&gt;
      &lt;itunes:explicit&gt;false&lt;/itunes:explicit&gt;
    &lt;/item&gt;
    
  &lt;/channel&gt;
&lt;/rss&gt;
</code></pre><p>In theory, if we put this RSS file and our MP3 somewhere a podcast player can find them, we should be able to listen to some Garth Brooks! However, <a href="http://localhost:1341/">http://localhost:1341/</a> is not likely to be reachable by a podcast player, so perhaps we should put a webserver there and whilst we&apos;re at it, just write our own little Soundcloud clone webapp. Seems reasonable, right?</p><p>We&apos;ll get into that in the next instalment of &quot;Soundcljoud, or a young man&apos;s Soundcloud clonejure.&quot;</p><p>Part 2: <a href="2024-07-20-soundcljoud-cloudy.html">Soundcljoud gets more cloudy</a></p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-02-22-cljcastr.html</id>
    <link href="https://jmglov.net/blog/2024-02-22-cljcastr.html"/>
    <title>cljcastr, or a young man's Zencastr clonejure</title>
    <updated>2024-02-22T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="A man with the Babashka logo for a face sits in front of a laptop and a mic" src="assets/2024-02-22-cljcastr-preview.png" title="Photo by Jeremy Enns on Unsplash" /></p><p>Who amongst us hasn&apos;t wanted to make a podcast? And of those who, who amongst them hasn&apos;t drooled over <a href="https://zencastr.com/">Zencastr</a>, which is a web-based podcast recording studio thingy?</p><p>I don&apos;t even know how to answer that question, as convoluted as it got, but what I&apos;m trying to say is that I got to see Zencastr&apos;s cool interface, and have been meaning to play around with the browser&apos;s audio / video API anyway, so why not see if I can whip up a quick Zencastr clone in Clojure? I mean, how hard can it be?</p><div class="markdown-heading"><h2 id="popping-in-a-scittle">Popping in a Scittle</h2><a href="#popping-in-a-scittle" class="anchor" aria-label="Permalink: Popping in a Scittle"><img src="assets/link.svg" /></a></div><p>You may recall from my <a href="2024-01-22-clickr-goes-fe.html">adventures cloning
Flickr</a> that I love ClojureScript but feel sad at my own lack of knowledge when trying to use <a href="https://github.com/thheller/shadow-cljs">shadow-cljs</a>. You may also recall that the sweet sweet antidote to this was <a href="https://github.com/babashka/scittle/">Scittle</a>, which allows you to &quot;execute Clojure(Script) directly from browser script tags via SCI&quot;. Since I&apos;m now an expert Scittler, I figured that&apos;s the obvious place to start a Zencastr clone. So let&apos;s start a project!</p><pre><code class="language-text">$ mkdir cljcastr &amp;&amp; cd cljcastr
</code></pre><p>Then we need a <code>bb.edn</code>, which we can just steal from Scittle&apos;s <a href="https://github.com/babashka/scittle/blob/cfaf6b0b33e6a2fd1fb82ef99871be38ce0e5c53/doc/nrepl/bb.edn">nrepl
demo</a> and modify ever so slightly to serve resources out of the <code>public/</code> directory:</p><pre><code class="language-clojure">{:deps {io.github.babashka/sci.nrepl
        {:git/sha &quot;2f8a9ed2d39a1b09d2b4d34d95494b56468f4a23&quot;}
        io.github.babashka/http-server
        {:git/sha &quot;b38c1f16ad2c618adae2c3b102a5520c261a7dd3&quot;}}
 :tasks {http-server {:doc &quot;Starts http server for serving static files&quot;
                      :requires ([babashka.http-server :as http])
                      :task (do (http/serve {:port 1341 :dir &quot;public&quot;})
                                (println &quot;Serving static assets at http://localhost:1341&quot;))}

         browser-nrepl {:doc &quot;Start browser nREPL&quot;
                        :requires ([sci.nrepl.browser-server :as bp])
                        :task (bp/start! {})}

         -dev {:depends [http-server browser-nrepl]}

         dev {:task (do (run &apos;-dev {:parallel true})
                        (deref (promise)))}}}
</code></pre><p>Given this, let&apos;s create a <code>public/index.html</code> to bootstrap our ClojureScript:</p><pre><code class="language-html">&lt;!doctype html&gt;
&lt;html class=&quot;no-js&quot; lang=&quot;&quot;&gt;

&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;title&gt;cljcastr&lt;/title&gt;
    &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;

    &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;/apple-touch-icon.png&quot;&gt;
    &lt;!-- Place favicon.ico in the root directory --&gt;

    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script&gt;var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.nrepl.js&quot;
        type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;application/x-scittle&quot; src=&quot;cljcastr.cljs&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;!--[if lt IE 8]&gt;
      &lt;p class=&quot;browserupgrade&quot;&gt;
      You are using an &lt;strong&gt;outdated&lt;/strong&gt; browser. Please
      &lt;a href=&quot;http://browsehappy.com/&quot;&gt;upgrade your browser&lt;/a&gt; to improve
      your experience.
      &lt;/p&gt;
    &lt;![endif]--&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>And of course we need to get stylish with a <code>public/style.css</code>:</p><pre><code class="language-css">body {
  font-family: Proxima Nova,helvetica neue,helvetica,arial,sans-serif;
}
</code></pre><p>And finally, we need <code>public/cljcastr.clj</code> to script some Clojure:</p><pre><code class="language-clojure">;; To start a REPL:
;;
;; bb dev
;;
;; Then connect to it in Emacs:
;;
;; C-c l C (cider-connect-cljs), host: localhost; port: 1339; REPL type: nbb

(ns cljcastr)
</code></pre><p>I always forget how to start the REPL and connect to it, so I left myself some nice explicit instructions, which we shall now follow. In the terminal:</p><pre><code class="language-text">$ bb dev
Serving static assets at http://localhost:1341
nREPL server started on port 1339...
Websocket server started on 1340...
</code></pre><p>We&apos;ll then visit <a href="http://localhost:1341">http://localhost:1341</a> in the browser and open up the JavaScript console, which should say:</p><pre><code class="language-text">   :ws #object[WebSocket [object WebSocket]]
&gt; 
</code></pre><p>Finally, back in Emacs, hitting <strong>C-c l C</strong> (cider-connect-cljs), selecting localhost for the host, 1339 for the port, and nbb for the REPL type, then <strong>C-c C-k</strong> (cider-load-buffer) shows us this in the terminal:</p><pre><code class="language-text">:msg &quot;{:versions {\&quot;scittle-nrepl\&quot; {\&quot;major\&quot; \&quot;0\&quot;, \&quot;minor\&quot; \&quot;0\&quot;, \&quot;incremental\&quot; \&quot;1\&quot;}}, :ops {\&quot;complete\&quot; {}, \&quot;info\&quot; {}, \&quot;lookup\&quot; {}, \&quot;eval\&quot; {}, \&quot;load-file\&quot; {}, \&quot;describe\&quot; {}, \&quot;close\&quot; {}, \&quot;clone\&quot; {}, \&quot;eldoc\&quot; {}}, :status [\&quot;done\&quot;], :id \&quot;3\&quot;, :session \&quot;5e3f1fb0-1f13-4db0-a25a-b63a9e7d7d72\&quot;, :ns \&quot;cljcastr\&quot;}&quot;
:msg &quot;{:value \&quot;nil\&quot;, :id \&quot;5\&quot;, :session \&quot;5e3f1fb0-1f13-4db0-a25a-b63a9e7d7d72\&quot;, :ns \&quot;cljcastr\&quot;}&quot;
:msg &quot;{:status [\&quot;done\&quot;], :id \&quot;5\&quot;, :session \&quot;5e3f1fb0-1f13-4db0-a25a-b63a9e7d7d72\&quot;, :ns \&quot;cljcastr\&quot;}&quot;
</code></pre><p>Exciting! Let&apos;s prove we&apos;re connected with a <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a>:</p><pre><code class="language-clojure">(comment

  (println &quot;Now we&apos;re cooking with Scittle!&quot;)  ; &lt;- C-c C-v f c e (cider-pprint-eval-last-sexp-to-comment)
  ;; =&gt; nil

  )
</code></pre><p>If all went well, we should see glorious things in the JavaScript console:</p><p><img alt="Screenshot of a browser window with the JavaScript console displaying: Now we&apos;re cooking with Scittle!" src="assets/2024-02-22-cljcastr-cooking.png" title="Sauté on medium-high heat for 15 minutes" /></p><div class="markdown-heading"><h2 id="left-to-our-own-devices">Left to our own devices</h2><a href="#left-to-our-own-devices" class="anchor" aria-label="Permalink: Left to our own devices"><img src="assets/link.svg" /></a></div><p>Now that we have a solid platform to stand on (namely: the REPL), let&apos;s get on with the cljcasting! We&apos;ll start by asking ourselves what audio and video devices we have at our disposal.</p><p>Modern browsers implement the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Media_Capture_and_Streams_API">Media Capture and Streams
API</a>, which provides support for streaming audio and video data. You can read a bit about the backstory of the API in a nice little article by Eric Bidelman and Sam Dutton: <a href="https://web.dev/articles/getusermedia-intro">Capture audio and video in
HTML5</a>. This article points to <a href="https://simpl.info/getusermedia/sources/">a
great demo of A/V capture</a> that Sam Dutton did.</p><p>I am relating all this because Sam Dutton&apos;s demo comes with <a href="https://github.com/samdutton/simpl/tree/gh-pages/getusermedia/sources">source
code</a> that shows not tells how to use this API, and like any great artist, I stole that code and used it for my own nefarious purposes. Well, &quot;nefarious&quot; might be a bit of a stretch, but c&apos;mon, I&apos;ve got a reputation to uphold over here. 😅</p><p>Our entrypoint into the wonderful world of browser-based A/V is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices">MediaDevices</a> interface, which is exposed as <code>navigator.mediaDevices</code>. MediaDevices has an instance method <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices">enumerateDevices()</a>, which we can use to, well, enumerate the audio and video devices availabile to our browser:</p><pre><code class="language-clojure">(comment

  (.enumerateDevices js/navigator.mediaDevices)
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>Blergh, looks like it returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a> instead of an actual value (OK, OK, a promise is a value, but you know what I mean). That means that we need to feed a function to the promise that actually does the thing. We do this by using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">Promise.then()</a>, which calls a function when the promise is fulfilled and returns a promise which wraps the return value of the function, allowing us to chain calls in a very similar way to Clojure&apos;s threading operators, <code>-&gt;</code> and <code>-&gt;&gt;</code>.</p><p>Now, before we do this, I discovered during the writing of this post that my browser hides all devices from me until I give it permission to use my audio and video devices. We can trigger that permission request with this incantation:</p><pre><code class="language-clojure">(comment

  (.getUserMedia js/navigator.mediaDevices #js {:video true, :audio true})
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>What should happen is that we&apos;re presented with a dialog asking for permission to use our video camera and microphone. Assuming we trust ourselves this far, we can accept and get back to seeing what <code>mediaDevices.enumerateDevices()</code> returns:</p><pre><code class="language-clojure">(comment

  (-&gt; (.enumerateDevices js/navigator.mediaDevices)
      (.then println))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>This results in some awesome stuff being printed to the JS console:</p><pre><code class="language-text">#js [#object[InputDeviceInfo [object InputDeviceInfo]]
     #object[InputDeviceInfo [object InputDeviceInfo]]
     #object[InputDeviceInfo [object InputDeviceInfo]]
     #object[InputDeviceInfo [object InputDeviceInfo]]
     #object[InputDeviceInfo [object InputDeviceInfo]]
     #object[InputDeviceInfo [object InputDeviceInfo]]
     #object[MediaDeviceInfo [object MediaDeviceInfo]]
     #object[MediaDeviceInfo [object MediaDeviceInfo]]
     #object[MediaDeviceInfo [object MediaDeviceInfo]]
     #object[MediaDeviceInfo [object MediaDeviceInfo]]
     #object[MediaDeviceInfo [object MediaDeviceInfo]]
     #object[MediaDeviceInfo [object MediaDeviceInfo]]]
</code></pre><p>OK, so we have an array of <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo">MediaDeviceInfo</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/InputDeviceInfo">InputDeviceInfo</a> objects, which have convenient <code>.label</code> and <code>.kind</code> properties that we can avail ourselves of:</p><pre><code class="language-clojure">(comment

  (-&gt; (.enumerateDevices js/navigator.mediaDevices)
      (.then (fn [devices]
               (-&gt;&gt; devices
                    (group-by #(.-kind %))
                    (sort-by key)
                    (map (fn [[kind ds]]
                           (str kind &quot;:\n  &quot;
                                (str/join &quot;\n  &quot; (map #(.-label %) ds)))))
                    (str/join &quot;\n&quot;)
                    println))))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>This gives us something much more reasonable in the console:</p><pre><code class="language-text">audioinput:
  Default
  Tiger Lake-LP Smart Sound Technology Audio Controller Digital Microphone
  HD Webcam B910 Analog Stereo
  Yeti X Analog Stereo
audiooutput:
  Default
  Tiger Lake-LP Smart Sound Technology Audio Controller HDMI / DisplayPort 3 Output
  Tiger Lake-LP Smart Sound Technology Audio Controller HDMI / DisplayPort 2 Output
  Tiger Lake-LP Smart Sound Technology Audio Controller HDMI / DisplayPort 1 Output
  Tiger Lake-LP Smart Sound Technology Audio Controller Speaker + Headphones
  Yeti X Analog Stereo
videoinput:
  Integrated Camera (04f2:b6ea)
  UVC Camera (046d:0823) (046d:0823)
</code></pre><p>This looks like useful information indeed! Let&apos;s extract some functions out of the mess we made in our REPL:</p><pre><code class="language-clojure">(ns cljcastr
  (:require [clojure.string :as str]))

(defn log-devices [devices]
  (-&gt;&gt; devices
       (group-by #(.-kind %))
       (sort-by key)
       (map (fn [[kind ds]]
              (str kind &quot;:\n  &quot;
                   (str/join &quot;\n  &quot; (map #(.-label %) ds)))))
       (str/join &quot;\n&quot;)
       println)
  devices)

(defn get-devices []
  (.enumerateDevices js/navigator.mediaDevices))
</code></pre><p>Now, taking inspiration from Sam Dutton&apos;s demo, let&apos;s make a UI that lets you choose your video source and stream from it into a window:</p><p><img alt="Screenshot of a browser window showing Sam Dutton&apos;s mediaDevices demo" src="assets/2024-02-22-cljcastr-demo.png" title="A portrait of the young man as an artist" /></p><p>We&apos;ll start by opening up our <code>public/index.html</code> and sprinkling in some UI elements:</p><pre><code class="language-html">&lt;body&gt;
    &lt;!--[if lt IE 8]&gt;
      ...
    &lt;![endif]--&gt;

  &lt;div id=&quot;container&quot;&gt;
    &lt;h1&gt;cljcastr&lt;/h1&gt;
    &lt;div class=&quot;select&quot;&gt;
      &lt;label for=&quot;videoSource&quot;&gt;Video source:&lt;/label&gt;
      &lt;select id=&quot;videoSource&quot;&gt;&lt;/select&gt;
    &lt;/div&gt;
    &lt;video autoplay muted playsinline&gt;&lt;/video&gt;
  &lt;/div&gt;
&lt;/body&gt;
</code></pre><p>Since the labels of my devices were quite lengthy, let&apos;s make the select quite widthy by dropping the following in <code>public/style.css</code>:</p><pre><code class="language-css">select {
  width: 300px;
}
</code></pre><p>After doing this, we&apos;ll sadly have to refresh the browser to get it to pick up the changes to <code>index.html</code> and <code>style.css</code>. We could of course add in some awesome watching and live reloading like <a href="https://github.com/borkdude/quickblog">quickblog</a> does, but that smacks of effort and we don&apos;t have any useful state in the REPL to mourn anyway, so we&apos;ll bite our tongue and hope we don&apos;t have too many HTML or CSS changes left to make.</p><p>Now that we have the bones of a UI, let&apos;s actually populate the select element with the video devices that we&apos;ve detected. We can try grabbing all of the video input devices:</p><pre><code class="language-clojure">(comment

  (-&gt; (get-devices)
      (.then (fn [devices]
               (-&gt;&gt; devices
                    (filter #(= &quot;videoinput&quot; (.-kind %)))
                    log-devices))))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>The JS console now reads:</p><pre><code class="language-text">videoinput:
  Integrated Camera (04f2:b6ea)
  UVC Camera (046d:0823) (046d:0823)
</code></pre><p>Stuffing these in the select should be fairly straightforward:</p><pre><code class="language-clojure">(def video-select (.querySelector js/document &quot;select#videoSource&quot;))

(comment

  (-&gt; (get-devices)
      (.then (fn [devices]
               (doseq [device
                       (-&gt;&gt; devices
                            (filter #(= &quot;videoinput&quot; (.-kind %)))
                            log-devices)]
                 (let [option (.createElement js/document &quot;option&quot;)]
                   (set! (.-value option) (.-deviceId device))
                   (set! (.-text option)
                         (or (.-label device)
                             (str &quot;Camera &quot; (inc (.-length video-select)))))
                   (.appendChild video-select option))))))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>Et voilà! The browser now shows our cameras:</p><p><img alt="Screenshot of a browser window showing a selection box containing two video input sources" src="assets/2024-02-22-cljcastr-videoselect.png" title="Ah, the choices!" /></p><p>Having proven this works, let&apos;s make a function out of it:</p><pre><code class="language-clojure">(defn populate-device-selects! [devices]
  (doseq [device
          (-&gt;&gt; devices
               (filter #(= &quot;videoinput&quot; (.-kind %)))
               log-devices)]
    (let [option (.createElement js/document &quot;option&quot;)]
      (set! (.-value option) (.-deviceID device))
      (set! (.-text option)
            (or (.-label device)
                (str &quot;Camera &quot; (inc (.-length video-select)))))
      (.appendChild video-select option))))
</code></pre><p>In case you haven&apos;t come across this convention before, adding a <code>!</code> to the end of a function name indicates that the function is mutating something, in this case, adding options to the select element.</p><div class="markdown-heading"><h2 id="&lt;video&gt;-killed-the-adobe-flash-star">&lt;video&gt; killed the Adobe Flash star</h2><a href="#&lt;video&gt;-killed-the-adobe-flash-star" class="anchor" aria-label="Permalink: &lt;video&gt; killed the Adobe Flash star"><img src="assets/link.svg" /></a></div><p>Having given ourselves a way to select a video input device, we just need to actually display the video being input into said device. For this, we&apos;ll need to avail ourselves of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">MediaDevices.getUserMedia()</a> method. Given a device ID, it will &quot;prompt the user for permission to use a media input which produces a <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaStream">MediaStream</a>&quot;.</p><p>Let&apos;s check which video input device is selected:</p><pre><code class="language-clojure">(comment

  (.-value video-select)
  ;; =&gt; &quot;d9862f4684c6b3f21bf95436a09b58dfa1b7a442e79aff225314e5e9bab45217&quot;

  )
</code></pre><p>If we feed this ID to <code>getUserMedia()</code>, we should get a stream back:</p><pre><code class="language-clojure">(comment

  (-&gt; js/navigator.mediaDevices
      (.getUserMedia (clj-&gt;js {:video {:deviceId {:exact (.-value video-select)}}}))
      (.then #(println (.getVideoTracks %))))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>This <code>clj-&gt;js</code> business is taking a ClojureScript hashmap and turning it into a JavaScript object with nested objects. You have to remember to use it whenever you&apos;re calling JavaScript functions that take &quot;maps&quot; as arguments, lest those functions basically ignore your arguments. Don&apos;t ask me how I know! 😅</p><p>As an interesting aside, ClojureScript also has a <code>#js</code> reader tag, which says &quot;turn the following ClojureScript literal into the JavaScript equivalent&quot;. As an interesting aside to the aside, this is not recursive. Don&apos;t ask me how I know! 😅</p><pre><code class="language-clojure">(comment

  #js {:video &quot;killed the radio star&quot;}
  ;; =&gt; #js {:video &quot;killed the radio star&quot;}

  #js {:video {:deviceId {:exact (.-value video-select)}}}
  ;; =&gt; #js {:video
  ;;         {:deviceId
  ;;          {:exact
  ;;           &quot;24705d21befb46ac4b2596716eee02c2fecb819447ef3edb91562aad41d2db50&quot;}}}

  (clj-&gt;js {:video {:deviceId {:exact (.-value video-select)}}})
  ;; =&gt; #js {:video
  ;;         #js {:deviceId
  ;;              #js {:exact
  ;;                   &quot;24705d21befb46ac4b2596716eee02c2fecb819447ef3edb91562aad41d2db50&quot;}}}

  )
</code></pre><p>OK, getting back to our code:</p><pre><code class="language-clojure">(comment

  (-&gt; js/navigator.mediaDevices
      (.getUserMedia (clj-&gt;js {:video {:deviceId {:exact (.-value video-select)}}}))
      (.then #(println (.getVideoTracks %))))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>When we evaluated this, two interesting things should have happened. First, the JS console should say something like this:</p><pre><code class="language-text">#js [#object[MediaStreamTrack [object MediaStreamTrack]]]
</code></pre><p>And second, the recording light on your webcam should light up. OMG we&apos;re getting somewhere! 🎉</p><p>Of course, our goal isn&apos;t simply to turn on the webcam, but rather to turn it on and then start streaming video to our webpage. This is actually pretty straightforward, compared to what we&apos;ve done to get to this point.</p><pre><code class="language-clojure">(def video-element (.querySelector js/document &quot;video&quot;))

(comment

  (-&gt; js/navigator.mediaDevices
      (.getUserMedia (clj-&gt;js {:video {:deviceId {:exact (.-value video-select)}}}))
      (.then #(set! (.-srcObject video-element) %)))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>The results are stunning...ly bad. Unless of course you&apos;re more photogenic than I am, in which case, congrats!</p><p><img alt="Screenshot of a browser window showing a video of me" src="assets/2024-02-22-cljcastr-streaming.png" title="I&apos;m getting tired of this view" /></p><p>Now that we&apos;re streaming video, it looks pretty ugly to have the video pressed right up against the bottom of the select element, so let&apos;s add some margin in our <code>style.css</code>:</p><pre><code class="language-css">select {
  width: 300px;
  margin-bottom: 10px;
}
</code></pre><p>With all of this plumbing, we can hook it up to the actual select box so it automatically starts playing video when we make a camera selection, rather than requiring us to go all 1337 h4ckZ0r in the REPL.</p><pre><code class="language-clojure">(def active-stream (atom nil))

(def video-element (.querySelector js/document &quot;video&quot;))

(defn log-error [e]
  (.error js/console e))

(defn log-devices [devices]
  ;; ...
  )

(defn get-devices []
  ;; ...
  )

(defn populate-device-selects! [devices]
  ;; ...
  )

(defn select-device! [select-element tracks]
  (let [label (-&gt; tracks first (.-label))
        index (-&gt;&gt; (.-options select-element)
                   (zipmap (range))
                   (some (fn [[i option]]
                           (and (= label (.-text option)) i))))]
    (when index
      (println &quot;Setting selected video source to index&quot; index)
      (set! (.-selectedIndex select-element) index))))

(defn start-video! [stream]
  (reset! active-stream stream)
  (select-device! video-select (.getVideoTracks stream))
  (set! (.-srcObject video-element) stream))

(defn stop-video! []
  (when @active-stream
    (println &quot;Stopping currently playing video&quot;)
    (doseq [track (.getTracks @active-stream)]
      (.stop track))))

(defn set-video-stream! []
  (stop-video!)
  (let [video-source (.-value video-select)
        constraints {:video {:deviceId (when (not-empty video-source)
                                         {:exact video-source})}}]
    (println &quot;Getting media with constraints:&quot; constraints)
    (-&gt; js/navigator.mediaDevices
        (.getUserMedia (clj-&gt;js constraints))
        (.then start-video!)
        (.catch log-error))))

(defn load-ui! []
  (set! (.-onchange video-select) set-video-stream!)
  (-&gt; (set-video-stream!)
      (.then get-devices)
      (.then log-devices)
      (.then populate-device-selects!)))

(comment

  (load-ui!)
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>Let&apos;s break these functions down to see what&apos;s going on here:</p><pre><code class="language-clojure">(defn load-ui! []
  (set! (.-onchange video-select) set-video-stream!)
  (-&gt; (set-video-stream!)
      ;; ...
      ))
</code></pre><p>First, we set the change handler for the video select element to the <code>set-video-stream!</code> function, then we call <code>set-video-stream!</code>.</p><pre><code class="language-clojure">(defn set-video-stream! []
  (stop-video!)
  ;; ...
  )
</code></pre><p><code>set-video-stream!</code> calls <code>stop-video!</code>:</p><pre><code class="language-clojure">(defn stop-video! []
  (when @active-stream
    (println &quot;Stopping currently playing video&quot;)
    (doseq [track (.getTracks @active-stream)]
      (.stop track))))
</code></pre><p><code>stop-video!</code> checks to see if we have a truthy value in our <code>active-stream</code> atom, which we won&apos;t at this point, since we initiatise the atom with a <code>nil</code> value:</p><pre><code class="language-clojure">(def active-stream (atom nil))
</code></pre><p>Back to <code>set-video-stream!</code>:</p><pre><code class="language-clojure">(defn set-video-stream! []
  ;; ...
  (let [video-source (.-value video-select)
        constraints {:video {:deviceId (when (not-empty video-source)
                                         {:exact video-source})}}]
    ;; ...
    ))
</code></pre><p>Since we haven&apos;t yet populated the video select element with video sources, <code>video-select.value</code> will be <code>&quot;&quot;</code>, which is not not empty (in other words, it&apos;s empty), so our <code>constraints</code> map will look like this:</p><pre><code class="language-clojure">(comment

  (let [video-source (.-value video-select)
        constraints {:video {:deviceId (when (not-empty video-source)
                                         {:exact video-source})}}]
    constraints)
  ;; =&gt; {:video {:deviceId nil}}

  )
</code></pre><p>Feeding this to <code>navigator.mediaDevices.getUserMedia()</code> will result in prompting the user for permission to access whichever of their cameras the browser considers the default, then turning on that camera and providing a <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaStream">MediaStream</a> containing a video track with the input, which we then feed to <code>start-video!</code>.</p><pre><code class="language-clojure">(defn set-video-stream! []
  ;; ...
  (let [ ;; ...
       ]
    (println &quot;Getting media with constraints:&quot; constraints)
    (-&gt; js/navigator.mediaDevices
        (.getUserMedia (clj-&gt;js constraints))
        (.then start-video!)
        (.catch log-error))))
</code></pre><p><code>start-video!</code> is fairly simple:</p><pre><code class="language-clojure">(defn start-video! [stream]
  (reset! active-stream stream)
  (select-device! video-select (.getVideoTracks stream))
  (set! (.-srcObject video-element) stream))
</code></pre><p>The first thing it does is reset the value of the <code>active-stream</code> atom to the stream returned by <code>getUserMedia()</code>, then calls <code>select-device!</code> with the video select DOM element and the video tracks of the stream, then finally sets the <code>srcObject</code> property of the <code>&lt;video&gt;</code> element to the stream, which results in us seeing ourselves (or whatever our default camera is aimed at).</p><p><code>select-device!</code> is responsible for setting the value of a select element to the device corresponding to the first of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack">MediaStreamTrack</a> objects we passed it:</p><pre><code class="language-clojure">(defn select-device! [select-element tracks]
  (let [label (-&gt; tracks first (.-label))
        index (-&gt;&gt; (.-options select-element)
                   (zipmap (range))
                   (some (fn [[i option]]
                           (and (= label (.-text option)) i))))]
    (when index
      (println &quot;Setting selected video source to index&quot; index)
      (set! (.-selectedIndex select-element) index))))
</code></pre><p>In this case, that will be the video select element and the video tracks from the default camera.</p><p>The tracks are labelled with the name of the device they correspond to:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (.getVideoTracks @active-stream)
       (map #(.-label %)))
  ;; =&gt; (&quot;Integrated Camera (04f2:b6ea)&quot;)

  )
</code></pre><p>Which are the same names we used to populate our video select options:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (.-options video-select)
       (map #(.-text %)))
  ;; =&gt; (&quot;Integrated Camera (04f2:b6ea)&quot;
  ;;     &quot;UVC Camera (046d:0823) (046d:0823)&quot;)

  )
</code></pre><p>To select an option, we need to set the <code>selectedIndex</code> property of the select element to the index corresponding to the option we want. We can turn the list of options into a map of index to option using <a href="https://clojuredocs.org/clojure.core/zipmap">zipmap</a>, which takes a list of keys and a list of values and returns a map with the keys mapped to the corresponding values:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (.-options video-select)
       (zipmap (range)))
  ;; =&gt; {0 #object[HTMLOptionElement [object HTMLOptionElement]]
  ;;     1 #object[HTMLOptionElement [object HTMLOptionElement]]}

  )
</code></pre><p>Finally, we need to return the index of first option where the value of the <code>text</code> property matches the label we&apos;re looking for:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (.-options video-select)
       (zipmap (range))
       (some (fn [[i option]]
               (and (= label (.-text option)) i)))))
  ;; =&gt; 0

  )
</code></pre><p>Note that the <a href="https://clojuredocs.org/clojure.core/some">some</a> function returns the first truthy value return by the predicate function, so we can use a neat little trick to return the index:</p><pre><code class="language-clojure">(and (= label (.-text option)) i)
</code></pre><p>When the text matches the label, the first clause of the <code>and</code> will be truthy (a literal <code>true</code>), and the second clause, the index, will also be truthy because only <code>false</code> and <code>nil</code> are not truthy in Clojure, and <code>and</code> returns the last truthy value, which is the index, so the return value of <code>some</code> is the index corresponding to the label. Without this trick, we&apos;d have to resort to something like this:</p><pre><code class="language-clojure">(comment

  (let [label &quot;Integrated Camera (04f2:b6ea)&quot;]
    (-&gt;&gt; (.-options video-select)
         (zipmap (range))
         (filter (fn [[i option]]
                   (= label (.-text option))))
         ffirst))
  ;; =&gt; 0

  )
</code></pre><p>I hope we can all agree that this is gross! 🤮</p><p>So that&apos;s what happens on the initial load of the page. If we have more than one camera, we can select it, which results in <code>set-video-stream!</code> being called again:</p><pre><code class="language-clojure">(defn set-video-stream! []
  (stop-video!)
  (let [video-source (.-value video-select)
        constraints {:video {:deviceId (when (not-empty video-source)
                                         {:exact video-source})}}]
    (println &quot;Getting media with constraints:&quot; constraints)
    (-&gt; js/navigator.mediaDevices
        (.getUserMedia (clj-&gt;js constraints))
        (.then start-video!)
        (.catch log-error))))
</code></pre><p>This time, the video select element will have a value:</p><pre><code class="language-clojure">(comment

  (let [video-source (.-value video-select)
        constraints {:video {:deviceId (when (not-empty video-source)
                                         {:exact video-source})}}]
    constraints)
  ;; =&gt; {:video
  ;;     {:deviceId
  ;;      {:exact
  ;;       &quot;24705d21befb46ac4b2596716eee02c2fecb819447ef3edb91562aad41d2db50&quot;}}}

  )
</code></pre><p>Hence <code>.getUserMedia()</code> will return a <code>MediaStream</code> for that specific camera, and then <code>start-video!</code> and the rest of it work as before.</p><p>OK, that was a lot! 😅</p><div class="markdown-heading"><h2 id="audioimmolation">Audioimmolation</h2><a href="#audioimmolation" class="anchor" aria-label="Permalink: Audioimmolation"><img src="assets/link.svg" /></a></div><p>Now that we have video on lockdown, let&apos;s see if we can add some sweet sweet audio. We&apos;ll start with the HTML:</p><pre><code class="language-html">&lt;!doctype html&gt;
&lt;html class=&quot;no-js&quot; lang=&quot;&quot;&gt;
&lt;!-- ... --&gt;
&lt;body&gt;
  &lt;!-- ... --&gt;
  &lt;div id=&quot;container&quot;&gt;
    &lt;h1&gt;cljcastr&lt;/h1&gt;
    &lt;div id=&quot;sources&quot;&gt;
      &lt;div class=&quot;select&quot;&gt;
        &lt;label for=&quot;videoSource&quot;&gt;Video source:&lt;/label&gt;
        &lt;select id=&quot;videoSource&quot;&gt;&lt;/select&gt;
      &lt;/div&gt;
      &lt;div class=&quot;select&quot;&gt;
        &lt;label for=&quot;audioSource&quot;&gt;Audio source:&lt;/label&gt;
        &lt;select id=&quot;audioSource&quot;&gt;&lt;/select&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;video autoplay muted playsinline&gt;&lt;/video&gt;
  &lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>Note that we&apos;re wrapping the two <code>.select</code> divs in another div. In our <code>style.css</code>, we can move the margin down to this div instead of directly on the <code>&lt;select&gt;</code> elements:</p><pre><code class="language-css">div#sources {
  margin-bottom: 10px;
}
</code></pre><p>If we refresh the page, we&apos;ll now see a select element labelled &quot;Audio source&quot; pop up.</p><p>Now back to <code>cljcastr.cljs</code>! First we add a binding for the audio select to the top of the file alongside the video select:</p><pre><code class="language-clojure">(ns cljcastr
  (:require [clojure.string :as str]))

(def video-element (.querySelector js/document &quot;video&quot;))
(def video-select (.querySelector js/document &quot;select#videoSource&quot;))
(def audio-select (.querySelector js/document &quot;select#audioSource&quot;))
</code></pre><p>Now, let&apos;s walk through the UI flow, starting with <code>load-ui!</code>, and see where to sprinkle in audio stuff:</p><pre><code class="language-clojure">(defn load-ui! []
  (set! (.-onchange video-select) set-video-stream!)
  (-&gt; (set-video-stream!)
      (.then get-devices)
      (.then log-devices)
      (.then populate-device-selects!)))
</code></pre><p>Digging into <code>set-video-stream!</code>, it looks like we can grab the audio source in exactly the same way as we do the video one, so let&apos;s add that in:</p><pre><code class="language-clojure">(defn set-video-stream! []
  (stop-video!)
  (let [audio-source (.-value audio-select)
        video-source (.-value video-select)
        constraints {:audio {:deviceId (when (not-empty audio-source)
                                         {:exact audio-source})}
                     :video {:deviceId (when (not-empty video-source)
                                         {:exact video-source})}}]
    (println &quot;Getting media with constraints:&quot; constraints)
    (-&gt; js/navigator.mediaDevices
        (.getUserMedia (clj-&gt;js constraints))
        (.then start-video!)
        (.catch log-error))))
</code></pre><p>We should also rename the function, now that it&apos;s responsible for audio as well. <code>set-media-stream!</code> seems like a pretty decent name, so let&apos;s go for that! Whilst we&apos;re at the renaming, we can rename <code>stop-video!</code> to <code>stop-media!</code> as well. The contents of the function itself look pretty good, except the log statement, so we can fix that:</p><pre><code class="language-clojure">(defn stop-media! []
  (when @active-stream
    (println &quot;Stopping currently playing media&quot;)
    (doseq [track (.getTracks @active-stream)]
      (.stop track))))
</code></pre><p>If we keep going in <code>set-media-stream!</code>, the <code>.getUserMedia()</code> call is fine, since we&apos;ve added an audio constraint. The next thing that happens is the call to <code>start-video!</code>, which we can rename to <code>start-media!</code> and then have a look at:</p><pre><code class="language-clojure">(defn start-media! [stream]
  (reset! active-stream stream)
  (select-device! video-select (.getVideoTracks stream))
  (set! (.-srcObject video-element) stream))
</code></pre><p>It looks like we can use <code>select-device!</code> to handle the audio as well, so let&apos;s try that out:</p><pre><code class="language-clojure">(defn start-media! [stream]
  (reset! active-stream stream)
  (select-device! audio-select (.getAudioTracks stream))
  (select-device! video-select (.getVideoTracks stream))
  (set! (.-srcObject video-element) stream))
</code></pre><p>OK, it looks like we&apos;re in pretty good shape in <code>set-media-stream!</code> now, so let&apos;s keep walking through <code>load-ui!</code>:</p><pre><code class="language-clojure">(defn load-ui! []
  (set! (.-onchange video-select) set-media-stream!)
  (-&gt; (set-media-stream!)
      (.then get-devices)
      (.then log-devices)
      (.then populate-device-selects!)))
</code></pre><p>Next up after the call to <code>set-media-stream!</code> is the call to <code>get-devices</code>, so let&apos;s dig in there:</p><pre><code class="language-clojure">(defn get-devices []
  (.enumerateDevices js/navigator.mediaDevices))
</code></pre><p>That looks pretty reasonable, so let&apos;s look at the final function called from <code>load-ui!</code>, which is <code>populate-device-selects!</code>.</p><pre><code class="language-clojure">(defn populate-device-selects! [devices]
  (doseq [device
          (-&gt;&gt; devices
               (filter #(= &quot;videoinput&quot; (.-kind %)))
               (log-devices &quot;Populating video inputs with devices&quot;))]
    (let [option (.createElement js/document &quot;option&quot;)]
      (set! (.-value option) (.-deviceId device))
      (set! (.-text option)
            (or (.-label device)
                (str &quot;Camera &quot; (inc (.-length video-select)))))
      (.appendChild video-select option))))
</code></pre><p>Yikes! 😱 Looks like we have a little refactoring to do here. After diving into the closest phonebooth (they still have those, right?) to replace our nerdy glasses with our LISP superhero cape, we can do a top-down design move and rewrite the function the way we wish it worked:</p><pre><code class="language-clojure">(defn populate-device-selects! [devices]
  (populate-device-select! audio-select (audio-devices devices))
  (populate-device-select! video-select (video-devices devices)))
</code></pre><p>Looks quite nice, doesn&apos;t it? Given this, let&apos;s write <code>populate-device-select!</code>:</p><pre><code class="language-clojure">(defn populate-device-select! [select-element devices]
  (let [select-label (-&gt;&gt; (.-labels select-element) first .-textContent)]
    (doseq [device (log-devices (str &quot;Populating options for &quot; select-label) devices)]
      (let [option (.createElement js/document &quot;option&quot;)]
        (set! (.-value option) (.-deviceId device))
        (set! (.-text option) (.-label device))
        (.appendChild select-element option)))))
</code></pre><p>It&apos;s nice to specify in the log output which select we&apos;re populating, and since we specified a label in our HTML:</p><pre><code class="language-html">&lt;label for=&quot;videoSource&quot;&gt;Video source:&lt;/label&gt;
&lt;select id=&quot;videoSource&quot;&gt;&lt;/select&gt;
</code></pre><p>we can access the label through the <code>labels</code> property on the select element. Since we know that we only have one label, we can take the first one and grab the value of its <code>textContent</code> property:</p><pre><code class="language-clojure">(let [select-label (-&gt;&gt; (.-labels select-element) first .-textContent)]
  ;; ...
  )
</code></pre><p>Pretty neat!</p><p>OK, now that we have <code>populate-device-select!</code>, the last two functions we need to write are <code>audio-devices</code> and <code>video-devices</code>. Well, it turns out that we&apos;ve more or less already written <code>video-devices</code> in the original <code>populate-device-selects!</code> code:</p><pre><code class="language-clojure">(-&gt;&gt; devices
     (filter #(= &quot;videoinput&quot; (.-kind %)))
     (log-devices &quot;Populating video inputs with devices&quot;))
</code></pre><p>Let&apos;s transform this into a function:</p><pre><code class="language-clojure">(defn video-devices [devices]
  (filter #(= &quot;videoinput&quot; (.-kind %)) devices))
</code></pre><p>Given this, writing <code>audio-devices</code> is just some copy / paste / <code>query-replace</code>:</p><pre><code class="language-clojure">(defn audio-devices [devices]
  (filter #(= &quot;audioinput&quot; (.-kind %)) devices))
</code></pre><p>We can test this out:</p><pre><code class="language-clojure">(comment

  (doseq [f [audio-devices video-devices]]
    (-&gt; (get-devices)
        (.then (comp log-devices f))))
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p>We should now see something like this in the JavaScript console:</p><pre><code class="language-text">audioinput:
  Default (default)
  Tiger Lake-LP Smart Sound Technology Audio Controller Digital Microphone (94edc85f1f91926d1e9f9da6995188d6263dee15e8a45a6d1add28f64f74c13b)
  HD Webcam B910 Analog Stereo (f78a32bacbfbe6ffe238b0d3b046f11bf4ed8e5ad8ce6cf25f18d431be3cd9af)
  Yeti X Analog Stereo (5af7607e641d0c8061291e648a5bec4958a588147bf0ffcc61a1ef5f2afb6cb6)
videoinput:
  Integrated Camera (04f2:b6ea) (d9862f4684c6b3f21bf95436a09b58dfa1b7a442e79aff225314e5e9bab45217)
  UVC Camera (046d:0823) (046d:0823) (24705d21befb46ac4b2596716eee02c2fecb819447ef3edb91562aad41d2db50)
</code></pre><p>Amazing!</p><p>At this point, we should be able to call <code>load-ui!</code> and see both the audio and video sources in their respective select dropdowns:</p><pre><code class="language-clojure">(comment

  (load-ui!)
  ;; =&gt; #object[Promise [object Promise]]

  )
</code></pre><p><img alt="Screenshot of a browser window showing a selection box containing four audio input sources" src="assets/2024-02-22-cljcastr-audioselect.png" title="Get in mah ear!" /></p><p>As a brief aside, I&apos;m annoyed by that 404 (Not Found) when trying to get <code>favicon.ico</code>, so let&apos;s fix that, using lessons learned in <a href="2022-07-05-hacking-blog-favicon.html">Hacking the blog:
favicon</a>!</p><div class="markdown-heading"><h2 id="an-iconic-favicon">An iconic favicon</h2><a href="#an-iconic-favicon" class="anchor" aria-label="Permalink: An iconic favicon"><img src="assets/link.svg" /></a></div><p>We&apos;ll just pop over to <a href="https://realfavicongenerator.net/">RealFaviconGenerator</a> and supply a logo such as this one:</p><p><img alt="A microphone with the Clojure logo for the top part" src="assets/2024-02-22-cljcastr-logo.png" title="Everything&apos;s better with Clojure on top!" width=260 /></p><p>Then download the favicon package and unzip it into our webserver root:</p><pre><code class="language-text">$ cd public
$ unzip ~/Downloads/cljcastr-favicon_package_v0.16.zip
Archive:  /home/jmglov/Downloads/cljcastr-favicon_package_v0.16.zip
  inflating: android-chrome-192x192.png
  inflating: mstile-150x150.png
  inflating: favicon-16x16.png
  inflating: safari-pinned-tab.svg
  inflating: favicon.ico
  inflating: site.webmanifest
  inflating: android-chrome-512x512.png
  inflating: apple-touch-icon.png
  inflating: browserconfig.xml
  inflating: favicon-32x32.png
</code></pre><p>And finally, drop this goodness into the <code>&lt;head&gt;</code> section of <code>public/index.html</code>:</p><pre><code class="language-html">&lt;head&gt;
    &lt;!-- ... --&gt;
    &lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;180x180&quot; href=&quot;/apple-touch-icon.png&quot;&gt;
    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;32x32&quot; href=&quot;/favicon-32x32.png&quot;&gt;
    &lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;16x16&quot; href=&quot;/favicon-16x16.png&quot;&gt;
    &lt;link rel=&quot;manifest&quot; href=&quot;/site.webmanifest&quot;&gt;
    &lt;link rel=&quot;mask-icon&quot; href=&quot;/safari-pinned-tab.svg&quot; color=&quot;#5bbad5&quot;&gt;
    &lt;meta name=&quot;msapplication-TileColor&quot; content=&quot;#da532c&quot;&gt;
    &lt;meta name=&quot;theme-color&quot; content=&quot;#ffffff&quot;&gt;
    &lt;!-- ... --&gt;
&lt;/head&gt;
</code></pre><p>Reloading the cljcastr page should now show a delightful little icon in the tab.</p><div class="markdown-heading"><h2 id="hey-mr.-selector">Hey Mr. Selector</h2><a href="#hey-mr.-selector" class="anchor" aria-label="Permalink: Hey Mr. Selector"><img src="assets/link.svg" /></a></div><p>The only thing lacking at this point is adding an <code>onchange</code> event handler to the audio select. We can do that in <code>load-ui!</code>, and then we might as well call <code>load-ui!</code> on page load whilst we&apos;re at it:</p><pre><code class="language-clojure">(defn load-ui! []
  (set! (.-onchange audio-select) set-media-stream!)
  (set! (.-onchange video-select) set-media-stream!)
  (-&gt; (set-media-stream!)
      (.then get-devices)
      (.then log-devices)
      (.then populate-device-selects!)))

(load-ui!)
</code></pre><p>Evaluating the buffer results in seeing ourselves, and we seem to be able to switch video and audio sources happily, but there&apos;s one annoying thing happening when switching audio source. Quoth the JS console:</p><pre><code class="language-text">Getting media with constraints:
  {:audio
   {:deviceId
    {:exact
     5af7607e641d0c8061291e648a5bec4958a588147bf0ffcc61a1ef5f2afb6cb6}},
   :video
   {:deviceId
    {:exact
     24705d21befb46ac4b2596716eee02c2fecb819447ef3edb91562aad41d2db50}}}
Setting selected video source to index 3
Setting selected video source to index 1
</code></pre><p>It looks like that first &quot;video source&quot; is actually an audio source. 😬</p><p>Looking at <code>select-device!</code>, it&apos;s obvious why this is:</p><pre><code class="language-clojure">(defn select-device! [select-element tracks]
  (let [label (-&gt; tracks first (.-label))
        index (-&gt;&gt; (.-options select-element)
                   (zipmap (range))
                   (some (fn [[i option]]
                           (and (= label (.-text option)) i))))]
    (when index
      (println &quot;Setting selected video source to index&quot; index)
      (set! (.-selectedIndex select-element) index))))
</code></pre><p>Since we have the select DOM element here, we can use the same trick as in <code>populate-device-select!</code> to get its label. Let&apos;s extract that stuff to a function of its very own, then update <code>populate-device-select!</code> and <code>select-device!</code> to use it:</p><pre><code class="language-clojure">(defn label-for [element]
  (-&gt;&gt; (.-labels element) first .-textContent))

(defn populate-device-select! [select-element devices]
  (doseq [device (log-devices (str &quot;Populating options for &quot;
                                   (label-for select-element))
                              devices)]
    ;; ...
    ))

(defn select-device! [select-element tracks]
  (let [
        ;; ...
       ]
    (when index
      (println &quot;Setting index for&quot; (label-for select-element) index)
      (set! (.-selectedIndex select-element) index))))
</code></pre><p>This looks much better now!</p><pre><code class="language-text">Getting media with constraints:
  {:audio
   {:deviceId
    {:exact
     5af7607e641d0c8061291e648a5bec4958a588147bf0ffcc61a1ef5f2afb6cb6}},
   :video
   {:deviceId
    {:exact
     24705d21befb46ac4b2596716eee02c2fecb819447ef3edb91562aad41d2db50}}}
Setting index for Audio source: 3
Setting index for Video source: 1
</code></pre><div class="markdown-heading"><h2 id="stop,-in-the-name-of-privacy,-before-you-break-my-heart">Stop, in the name of privacy, before you break my heart</h2><a href="#stop,-in-the-name-of-privacy,-before-you-break-my-heart" class="anchor" aria-label="Permalink: Stop, in the name of privacy, before you break my heart"><img src="assets/link.svg" /></a></div><p>This is all wonderful, but if you&apos;re anything like me, you probably don&apos;t like your webcam and mic surveilling you when you&apos;re not actively using them. Let&apos;s add a stop button that shuts down this whole dog and pony show. First, we can add the button in <code>index.html</code>:</p><pre><code class="language-html">  &lt;div id=&quot;container&quot;&gt;
    &lt;h1&gt;cljcastr&lt;/h1&gt;
    &lt;div id=&quot;sources&quot;&gt;
      &lt;div id=&quot;selects&quot;&gt;
        &lt;div class=&quot;select&quot;&gt; &lt;!-- ... --&gt; &lt;/div&gt;
        &lt;div class=&quot;select&quot;&gt; &lt;!-- ... --&gt; &lt;/div&gt;
      &lt;/div&gt;
      &lt;div id=&quot;stop&quot;&gt;
        &lt;input id=&quot;stop&quot; type=&quot;button&quot; value=&quot;Stop&quot; /&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;video autoplay muted playsinline&gt;&lt;/video&gt;
  &lt;/div&gt;
</code></pre><p>Yes, yes, I added another <code>&lt;div&gt;</code>. Listen, I never claimed to actually know what I was doing with this whole new-fangled HTML thing, OK? Back in my day, we had <a href="https://www.howtogeek.com/661871/the-web-before-the-web-a-look-back-at-gopher/">Gopher</a> and counted ourselves lucky! Also, we FTP&apos;d files uphill both ways in a blizzard and so on.</p><p>Speaking of not knowing what I&apos;m doing, lemme sprinkle some CSS on the top of this lovely cake:</p><pre><code class="language-css">div#sources {
  display: flex;
  margin-bottom: 10px;
}

div#stop {
  padding-left: 10px;
}
</code></pre><p>Now that we have a button, let&apos;s make it do stuff and things:</p><pre><code class="language-clojure">(ns cljcastr
  (:require [clojure.string :as str]))

(def video-element (.querySelector js/document &quot;video&quot;))
(def video-select (.querySelector js/document &quot;select#videoSource&quot;))
(def audio-select (.querySelector js/document &quot;select#audioSource&quot;))
(def stop-button (.querySelector js/document &quot;input#stop&quot;))

;; ...

(defn load-ui! []
  (set! (.-onclick stop-button) stop-media!)
  ;; ...
  )
</code></pre><p>Reload the page, click the button, and watch your face disappear!</p><p><img alt="Screenshot of a browser window showing a black video screen" src="assets/2024-02-22-cljcastr-stop.png" title="Hello darkness my old friend" /></p><p>And there you have it! A fully functional Zencastr clone!</p><p><em>*Ahem*</em></p><p>Perhaps we&apos;re missing recording and connecting to other people and transcription and so on, but those are just bonus features that people don&apos;t really need for podcasting, right? Anyway, I&apos;m quite proud of <a href="https://github.com/jmglov/cljcastr">what we
accomplished</a> in 106 lines of ClojureScript! 🏆</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-02-13-bb-playground.html</id>
    <link href="https://jmglov.net/blog/2024-02-13-bb-playground.html"/>
    <title>Playing on the Babashka playground</title>
    <updated>2024-02-13T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="A child with the Babashka logo as a face on a playground slide" src="assets/2024-02-13-bb-playground-preview.png" title="Photo by Amber Faust on Unsplash" /></p><p>As a longtime Linux user, I often find myself starting to type a complicated command. As a longtime programmer, I often find myself thinking, &quot;Maybe I should just automate this,&quot; and open up a <code>whatever.sh</code> in Emacs. As a longtime Bash scripter, I often find myself hundreds of lines into a script and looking up how to do string substition for the 60,000th time. As a recent-ish convert to <a href="https://babashka.org/">Babashka</a>, I often find myself closing the <code>whatever.sh</code> buffer quickly and opening <code>whatever.bb</code> instead. As a true believer in the power of the REPL, I often ask myself why I&apos;m writing code in <code>whatever.bb</code> and then executing it in my terminal and rolling my eyes when it doesn&apos;t work and going back to Emacs and changing something and executing it in my terminal again like a caveman instead of just <strong>C-c C-v f c e</strong>-ing like a normal person.</p><p>Surely there must be a better way!</p><p><img alt="Blackadder saying: I&apos;ve got a plan so cunning you could put a tail on it and call it a weasel" src="assets/2024-02-13-cunning-plan.png" title="I too have a cunning plan!" /></p><p>Enter the playground! And not just any playground, but a playground where joyous Babashkas (Babashki?) frolic, REPLing their little hearts out!</p><p>Here&apos;s what I did:</p><div class="markdown-heading"><h2 id="constructing-the-playground">Constructing the playground</h2><a href="#constructing-the-playground" class="anchor" aria-label="Permalink: Constructing the playground"><img src="assets/link.svg" /></a></div><p>First, I created a directory called <code>bb-playground</code> and dropped a <code>bb.edn</code> in it:</p><pre><code class="language-clojure">{:paths [&quot;dev&quot; &quot;src&quot;]}
</code></pre><p>Now if I create a <code>dev/user.clj</code>, I can start playing around in my REPL:</p><pre><code class="language-clojure">(ns user
  (:require [clojure.string :as str]))

;; 1. Start a REPL with C-c M-j
;; 2. Evaluate this buffer with C-c C-k

(comment

  ;; Do fun stuff here by putting your cursor at the end of an expression and
  ;; whacking C-c C-v f c e

  (-&gt;&gt; (System/getProperties)
       (filter (fn [[k _]] (str/starts-with? k &quot;babashka.&quot;)))
       (into {}))
  ;; =&gt; {&quot;babashka.version&quot; &quot;1.3.188&quot;,
  ;;     &quot;babashka.config&quot; &quot;/home/jmglov/Documents/code/bb-playground/bb.edn&quot;}

  )
</code></pre><p>That was quite easy, and very useful if I just want to play around with Clojure or any of the <a href="https://book.babashka.org/#libraries">libraries that ship with
Babashka</a>, but what if I want to do something like list all of the objects in a certain S3 bucket with a specific prefix?</p><div class="markdown-heading"><h2 id="making-the-playground-more-fun">Making the playground more fun</h2><a href="#making-the-playground-more-fun" class="anchor" aria-label="Permalink: Making the playground more fun"><img src="assets/link.svg" /></a></div><p>In order to do what I want, I&apos;m going to need my old favourite <a href="https://github.com/grzm/awyeah-api">awyeah-api</a>, which itself needs some friends from the the Cognitect <a href="https://github.com/cognitect-labs/aws-api">aws-api</a> library:</p><pre><code class="language-clojure">{:deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.504&quot;}
        com.cognitect.aws/s3 {:mvn/version &quot;848.2.1413.0&quot;}
        com.grzm/awyeah-api {:git/url &quot;https://github.com/grzm/awyeah-api&quot;
                             :git/sha &quot;e5513349a2fd8a980a62bbe0d45a0d55bfcea141&quot;
                             :git/tag &quot;v0.8.84&quot;}
        org.babashka/spec.alpha {:git/url &quot;https://github.com/babashka/spec.alpha&quot;
                                 :git/sha &quot;1a841c4cc1d4f6dab7505a98ed2d532dd9d56b78&quot;}}}
</code></pre><p>So I could just paste those deps into my <code>bb.edn</code>, but I want the latest and greatest from the AWS APIs, which I can grab from <a href="https://github.com/cognitect-labs/aws-api/blob/main/latest-releases.edn">aws-api/latest-releases.edn</a>, but then I have to get git hashes for awyeah-api and org.babashka/spec.alpha and paste them into my <code>bb.edn</code> and that seems like a lot of work that I&apos;m too lazy to do.</p><p>What I can do instead is use the power of <a href="https://github.com/babashka/neil">neil</a> to add my dependencies for me!</p><p>Since <a href="https://github.com/jlesquembre">someone</a> has been lovely enough to add neil to <a href="https://github.com/NixOS/nixpkgs/blob/c0b7a892fb042ede583bdaecbbdc804acb85eabe/pkgs/development/tools/neil/default.nix">nixpkgs</a>, installing it is as easy as plopping it into my <a href="https://github.com/jmglov/nixos-config/blob/59983ddf4e959f634d0d87aee9fbdd2a01f8ce95/jmglov/home.nix#L37">home.nix</a> and running:</p><pre><code class="language-text">: ~; sudo nixos-rebuild switch 
</code></pre><p>Now I can add dependencies like this:</p><pre><code class="language-text">: bb-playground; neil dep add --deps-file bb.edn com.cognitect.aws/endpoints
</code></pre><p>The only problem is that I&apos;m never in a million years going to remember all the arguments to neil. 🤔</p><div class="markdown-heading"><h2 id="working-around-my-poor-memory">Working around my poor memory</h2><a href="#working-around-my-poor-memory" class="anchor" aria-label="Permalink: Working around my poor memory"><img src="assets/link.svg" /></a></div><p>What if my <code>bb.edn</code> knew how to add dependencies to itself? Like, could I just run:</p><pre><code class="language-text">bb add-dep com.cognitect.aws/s3
</code></pre><p>and be done with it? Even I should be able to remember that! 😅</p><p>Well, Babashka has this thing called the <a href="https://book.babashka.org/#tasks">task
runner</a>, whereby you can drop stuff like this in your <code>bb.edn</code>:</p><pre><code class="language-clojure">{:tasks
 {:requires ([babashka.fs :as fs])
  clean (do (println &quot;Removing target folder.&quot;)
            (fs/delete-tree &quot;target&quot;))
  }
 }
</code></pre><p>and then run:</p><pre><code class="language-text">$ ls target
total 4
-rw-r--r-- 1 jmglov users 107 Dec 18 13:28 stuff.jar
$ bb clean
Removing target folder.
$ ls target
ls: cannot access &apos;target&apos;: No such file or directory
</code></pre><p>So with this, let&apos;s add a task to our <code>bb.edn</code>!</p><pre><code class="language-clojure">{:paths [&quot;dev&quot; &quot;src&quot;]
 :deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.626&quot;}}
 :aliases {}
 :tasks
 {add-dep (println &quot;What to do, what to do?&quot;)}}
</code></pre><p>And try it out:</p><pre><code class="language-text">: bb-playground; bb add-dep
What to do, what to do?
</code></pre><p>Cool! Now, if we think about what we want to do, it&apos;s basically: prepend &quot;neil dep add --deps-file bb.edn&quot; to the command line passed to <code>bb add-dep</code>. <a href="https://book.babashka.org/#_command_line_arguments">According to the docs</a>: &gt;</p><blockquote><p>Command line arguments are available as <em>command-line-args</em>, just like in Clojure.</p></blockquote><p>We can drop this in our <code>bb.edn</code>:</p><pre><code class="language-clojure">{ ; ...
 :tasks
 {add-dep (println &quot;ARGS:&quot; *command-line-args*)}}}
</code></pre><p>And see what the command line looks like when we play around:</p><pre><code class="language-text">: bb-playground; bb add-dep com.cognitect.aws/s3
ARGS: (com.cognitect.aws/s3)
</code></pre><p>OK, nice. So now we want to pass that along to neil. We can do this with <a href="https://github.com/babashka/process#shell">babashka.process/shell</a>:</p><pre><code class="language-clojure">{ ; ...
:tasks
 {:requires ([babashka.process :as p])
  add-dep (apply p/shell &quot;neil dep add --deps-file bb.edn&quot; *command-line-args*)}}
</code></pre><p>Now let&apos;s try this out:</p><pre><code class="language-text">: bb-playground; bb add-dep com.cognitect.aws/s3

: bb-playground; cat bb.edn 
{:paths [&quot;dev&quot; &quot;src&quot;]
 :deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.626&quot;} com.cognitect.aws/s3 {:mvn/version &quot;848.2.1413.0&quot;}}
 :aliases {}
 :tasks
 {:requires ([babashka.process :as p]
             [clojure.string :as str])
  add-dep (apply p/shell &quot;neil dep add --deps-file bb.edn&quot; *command-line-args*)}}
</code></pre><p>OMG wat!</p><p>Another cool thing we can do with the task runner is ask it what tasks we can run:</p><pre><code class="language-text">: bb-playground; bb tasks
The following tasks are available:

add-dep
</code></pre><p>We can even make this nicer by adding a description to the task:</p><pre><code class="language-clojure">{ ; ...
:tasks
 {:requires ([babashka.process :as p])
  add-dep {:doc &quot;Add a dependency to the playground&quot;
           :task (apply p/shell &quot;neil dep add --deps-file bb.edn&quot; *command-line-args*)}}}
</code></pre><p>Now we get some additional memory joggage:</p><pre><code class="language-text">: bb-playground; bb tasks
The following tasks are available:

add-dep Add a dependency to the playground
</code></pre><p>OK, but what if we don&apos;t remember what args <code>add-dep</code> takes? Let&apos;s try asking for help:</p><pre><code class="language-text">: bb-playground; bb add-dep --help
Usage: neil add dep [lib] [options]
Options:
  --lib                         Fully qualified library name.
  --version                     Optional. When not provided, picks newest version from Clojars or Maven Central.
  --sha                         When provided, assumes lib refers to Github repo.
  --latest-sha                  When provided, assumes lib refers to Github repo and then picks latest SHA from it.
  --tag                         When provided, assumes lib refers to Github repo.
  --latest-tag                  When provided, assumes lib refers to Github repo and then picks latest tag from it.
  --deps/root                   Sets deps/root to give value.
  --as                          Use as dependency name in deps.edn
  --alias      &lt;alias&gt;          Add to alias &lt;alias&gt;.
  --deps-file  &lt;file&gt;  deps.edn Add to &lt;file&gt; instead of deps.edn.
</code></pre><p>Oh neat! Of course, it&apos;s a bit confusing that the usage line says &quot;neil add dep&quot; instead of &quot;bb add-dep&quot;. Let&apos;s fix that!</p><pre><code class="language-clojure">{ ; ...
 :tasks
 {:requires ([babashka.process :as p]
             [clojure.string :as str])
  add-dep {:doc &quot;Add a dependency to the playground&quot;
           :task (let [args (or *command-line-args* [&quot;--help&quot;])
                       neil-args (concat [&quot;neil&quot; &quot;dep&quot; &quot;add&quot; &quot;--deps-file&quot; &quot;bb.edn&quot;] args)
                       {:keys [out]} (apply p/shell {:out :string} neil-args)]
                   (if (= &quot;--help&quot; (first args))
                     (-&gt;&gt; [(str/replace out &quot;Usage: neil add dep&quot; &quot;Usage: bb add-dep&quot;)
                           &quot;Examples:\n&quot;
                           &quot;bb add-dep com.cognitect.aws/endpoints&quot;
                           &quot;bb add-dep com.cognitect.aws/s3 --version 848.2.1413.0&quot;
                           &quot;bb add-dep grzm/awyeah-api --latest-sha&quot;]
                          (str/join &quot;\n&quot;)
                          println)
                     (println out)))}}}
</code></pre><p>Now if we ask for help:</p><pre><code class="language-text">Usage: bb add-dep [lib] [options]
Options:
  --lib                         Fully qualified library name.
  --version                     Optional. When not provided, picks newest version from Clojars or Maven Central.
  --sha                         When provided, assumes lib refers to Github repo.
  --latest-sha                  When provided, assumes lib refers to Github repo and then picks latest SHA from it.
  --tag                         When provided, assumes lib refers to Github repo.
  --latest-tag                  When provided, assumes lib refers to Github repo and then picks latest tag from it.
  --deps/root                   Sets deps/root to give value.
  --as                          Use as dependency name in deps.edn
  --alias      &lt;alias&gt;          Add to alias &lt;alias&gt;.
  --deps-file  &lt;file&gt;  deps.edn Add to &lt;file&gt; instead of deps.edn.

Examples:

bb add-dep com.cognitect.aws/endpoints
bb add-dep com.cognitect.aws/s3 --version 848.2.1413.0
bb add-dep grzm/awyeah-api --latest-sha
</code></pre><p>The one problem with all of this is that we&apos;ve been doing the thing that I was complaining about at the top: writing some code, saving the file, executing it in a terminal, realising it doesn&apos;t quite work, going back to the editor... etc.</p><p><img alt="Christopher Walken cowbell meme: I&apos;ve got a fever... and the only prescription is more REPL" src="assets/2024-02-13-cowbell.jpg" title="Bring me your finest CIDER!" /></p><div class="markdown-heading"><h2 id="getting-back-to-the-repl">Getting back to the REPL</h2><a href="#getting-back-to-the-repl" class="anchor" aria-label="Permalink: Getting back to the REPL"><img src="assets/link.svg" /></a></div><p>OK, so remember the REPL we had running over in <code>dev/user.clj</code>? We can use that to drive our <code>bb.edn</code> development. Let&apos;s create a <code>src/tasks.clj</code> file and copy all the <code>add-dep</code> stuff over to it:</p><pre><code class="language-clojure">(ns tasks
  (:require [babashka.process :as p]
            [clojure.string :as str]))

(defn add-dep [command-line-args]
  (let [args (or command-line-args [&quot;--help&quot;])
        neil-args (concat [&quot;neil&quot; &quot;dep&quot; &quot;add&quot; &quot;--deps-file&quot; &quot;bb.edn&quot;] args)
        {:keys [out]} (apply p/shell {:out :string} neil-args)]
    (if (= &quot;--help&quot; (first args))
      (-&gt;&gt; [(str/replace out &quot;Usage: neil add dep&quot; &quot;Usage: bb add-dep&quot;)
            &quot;Examples:\n&quot;
            &quot;bb add-dep com.cognitect.aws/endpoints&quot;
            &quot;bb add-dep com.cognitect.aws/s3 --version 848.2.1413.0&quot;
            &quot;bb add-dep grzm/awyeah-api --latest-sha&quot;]
           (str/join &quot;\n&quot;)
           println)
      (println out))))
</code></pre><p>Let&apos;s give it a <strong>C-c C-k</strong> to evaluate the buffer, just to make sure everything is in order. 😉</p><p>Now we can use this from <code>bb.edn</code></p><pre><code class="language-clojure">{:paths [&quot;dev&quot; &quot;src&quot;]
 :deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.626&quot;}
        com.cognitect.aws/s3 {:mvn/version &quot;848.2.1413.0&quot;}}
 :aliases {}
 :tasks
 {:requires ([tasks])
  add-dep {:doc &quot;Add a dependency to the playground&quot;
           :task (tasks/add-dep *command-line-args*)}}}
</code></pre><p>And just to verify that it still works:</p><pre><code class="language-text">: bb-playground; bb add-dep --help
Usage: bb add-dep [lib] [options]
Options:
  --lib                         Fully qualified library name.
  --version                     Optional. When not provided, picks newest version from Clojars or Maven Central.
  --sha                         When provided, assumes lib refers to Github repo.
  --latest-sha                  When provided, assumes lib refers to Github repo and then picks latest SHA from it.
  --tag                         When provided, assumes lib refers to Github repo.
  --latest-tag                  When provided, assumes lib refers to Github repo and then picks latest tag from it.
  --deps/root                   Sets deps/root to give value.
  --as                          Use as dependency name in deps.edn
  --alias      &lt;alias&gt;          Add to alias &lt;alias&gt;.
  --deps-file  &lt;file&gt;  deps.edn Add to &lt;file&gt; instead of deps.edn.

Examples:

bb add-dep com.cognitect.aws/endpoints
bb add-dep com.cognitect.aws/s3 --version 848.2.1413.0
bb add-dep grzm/awyeah-api --latest-sha
</code></pre><p>From now on, we won&apos;t need to leave our REPL to develop our tasks! Let&apos;s prove it by making <code>add-dep</code> print out the new dependencies after adding them:</p><pre><code class="language-clojure">(ns tasks
  (:require [babashka.process :as p]
            [clojure.edn :as edn]
            [clojure.pprint :refer [pprint]]
            [clojure.string :as str]))

(defn add-dep [command-line-args]
  (let [ ; ...
        ]
    (if (= &quot;--help&quot; (first args))
      ;; ...
      (do
        (println &quot;Dependency added. Dependencies are now:&quot;)
        (-&gt; (slurp &quot;bb.edn&quot;)
            edn/read-string
            :deps
            pprint)))))

(comment

  (add-dep [&quot;grzm/awyeah-api&quot;])
  ;; nil

  )
</code></pre><p>The REPL buffer should now say:</p><pre><code class="language-text">Dependency added. Dependencies are now:
{com.cognitect.aws/endpoints #:mvn{:version &quot;1.1.12.626&quot;},
 com.cognitect.aws/s3 #:mvn{:version &quot;848.2.1413.0&quot;},
 grzm/awyeah-api
 #:git{:url &quot;https://github.com/grzm/awyeah-api&quot;,
       :sha &quot;d98a9f6210c61d64f22e9b577d2254d6f6d2f35f&quot;}}
</code></pre><p>Hoorah! And just to prove that this also works from the terminal:</p><pre><code class="language-text">: bb-playground; bb add-dep babashka/spec.alpha
Dependency added. Dependencies are now:
{com.cognitect.aws/endpoints #:mvn{:version &quot;1.1.12.626&quot;},
 com.cognitect.aws/s3 #:mvn{:version &quot;848.2.1413.0&quot;},
 grzm/awyeah-api
 #:git{:url &quot;https://github.com/grzm/awyeah-api&quot;,
       :sha &quot;d98a9f6210c61d64f22e9b577d2254d6f6d2f35f&quot;},
 babashka/spec.alpha
 #:git{:url &quot;https://github.com/babashka/spec.alpha&quot;,
       :sha &quot;951b49b8c173244e66443b8188e3ff928a0a71e7&quot;}}
</code></pre><div class="markdown-heading"><h2 id="so-about-listing-that-bucket...">So about listing that bucket...</h2><a href="#so-about-listing-that-bucket..." class="anchor" aria-label="Permalink: So about listing that bucket..."><img src="assets/link.svg" /></a></div><p>If we pop back over to <code>user.clj</code> and give it a <strong>C-c C-k</strong> get our REPL firmly planted back in that namespace, let&apos;s start REPL-driving some S3 goodness:</p><pre><code class="language-clojure">(ns user
  (:require [clojure.string :as str]
            [com.grzm.awyeah.client.api :as aws]))

(comment

  (def s3 (aws/client {:api :s3}))

  )
</code></pre><p>Tragically, the second we try to evaluate this, everything goes a bit sideways:</p><pre><code class="language-text">clojure.lang.ExceptionInfo: Could not locate com/grzm/awyeah/client/api.bb, com/grzm/awyeah/client/api.clj or com/grzm/awyeah/client/api.cljc on classpath.
{:type :sci/error, :line 2, :column 3, :message &quot;Could not locate com/grzm/awyeah/client/api.bb, com/grzm/awyeah/client/api.clj or com/grzm/awyeah/client/api.cljc on classpath.&quot;, :sci.impl/callstack #object[clojure.lang.Volatile 0x70ac29ff {:status :ready, :val ({:line 2, :column 3, :file &quot;/home/jmglov/Documents/code/bb-playground/dev/user.clj&quot;, :ns #object[sci.lang.Namespace 0x460699aa &quot;user&quot;]})}], :file &quot;/home/jmglov/Documents/code/bb-playground/dev/user.clj&quot;}
 at sci.impl.utils$rethrow_with_location_of_node.invokeStatic (utils.cljc:135)
    [...]
Caused by: java.io.FileNotFoundException: Could not locate com/grzm/awyeah/client/api.bb, com/grzm/awyeah/client/api.clj or com/grzm/awyeah/client/api.cljc on classpath.
 at babashka.main$exec$fn__32207$load_fn__32218.invoke (main.clj:924)
    sci.impl.load$handle_require_libspec.invokeStatic (load.cljc:163)
    [...]
</code></pre><p>Oh yes, our REPL was started before we added all the dependencies. 🤦🏼</p><p>Now, if you thought for a second about restarting the REPL, this is clearly your first time on this blog. We never take the coward&apos;s way out around here! Even (or especially) when that would be super fast and easy and the alternative is many many keystrokes and the occasional muttered curse word under our breath!</p><p>So let&apos;s screw our courage to the sticking point and hotload those damned dependencies! (OK, so the cursing isn&apos;t always under our breath.)</p><pre><code class="language-clojure">(ns user
  (:require [babashka.deps :as deps]
            [clojure.edn :as edn]))

(comment

  (-&gt; (slurp &quot;bb.edn&quot;)
      edn/read-string
      deps/add-deps)
  ;; =&gt; nil

  (require &apos;[com.grzm.awyeah.client.api :as aws])
  ;; =&gt; nil

  )
</code></pre><p>Exceptional! Or rather, not exceptional, since no exceptions were thrown. Which is what we wanted. 😅</p><p>This actually looks pretty useful, so let&apos;s make it a function so we can just call it whenever we add a dependency:</p><pre><code class="language-clojure">(ns user
  (:require [babashka.deps :as deps]
            [clojure.edn :as edn]))

(defn refresh-deps []
  (-&gt; (slurp &quot;bb.edn&quot;)
      edn/read-string
      deps/add-deps))
</code></pre><p>Having done this, we can get back to listing stuff in S3.</p><pre><code class="language-clojure">(comment

  (def s3 (aws/client {:api :s3, :region &quot;eu-west-1&quot;}))
  ;; =&gt; #&apos;user/s3

  (-&gt;&gt; (aws/invoke s3 {:op :ListObjectsV2
                       :request {:Bucket &quot;misc.jmglov.net&quot;}})
       :Contents
       count)
  ;; =&gt; 1000

  )
</code></pre><p>Oh my, that&apos;s a lot of stuff! And it&apos;s somewhat suspicious that it&apos;s exactly 1000 stuffs. Especially since 1000 is the default page size for the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html">ListObjectsV2</a> API request. In fact, I seem to remember writing a couple <a href="2022-09-22-aws-paging.html">blog</a> <a href="2022-10-02-page-2.html">posts</a> about paging and S3. I&apos;ll just go ahead and liberate some code from that second post there:</p><pre><code class="language-clojure">(ns user
  (:require [babashka.deps :as deps]
            [com.grzm.awyeah.client.api :as aws]
            [clojure.edn :as edn])
  (:import (java.time Instant)))

(defmacro -&gt;map [&amp; ks]
  (assert (every? symbol? ks))
  (zipmap (map keyword ks)
          ks))

(defn lazy-concat [colls]
  (lazy-seq
   (when-first [c colls]
     (lazy-cat c (lazy-concat (rest colls))))))

(defn log [msg data]
  (prn {:msg msg
        :data data
        :timestamp (str (Instant/now))}))

(defn error [msg data]
  (log msg data)
  (throw (ex-info msg data)))

(defn validate-aws-response [res]
  (when (:cognitect.anomalies/category res)
    (let [data (merge (select-keys res [:cognitect.anomalies/category])
                      {:err-msg (:Message res)
                       :err-type (:__type res)})]
      (error &quot;AWS request failed&quot; data)))
  res)

(defn mk-s3-req
  ([s3-bucket prefix s3-page-size]
   (mk-s3-req s3-bucket prefix s3-page-size nil))
  ([s3-bucket prefix s3-page-size continuation-token]
   (merge {:Bucket s3-bucket
           :Prefix prefix}
          (when s3-page-size
            {:MaxKeys s3-page-size})
          (when continuation-token
            {:ContinuationToken continuation-token}))))

(defn get-s3-page [{:keys [s3-client s3-bucket s3-page-size]}
                   prefix
                   {continuation-token :NextContinuationToken
                    truncated? :IsTruncated
                    page-num :page-num
                    :as prev}]
  (when prev (log &quot;Got page&quot; (dissoc prev :Contents)))
  (let [page-num (inc (or page-num 0))
        done? (false? truncated?)
        request (mk-s3-req s3-bucket prefix s3-page-size continuation-token)
        response (when-not done?
                   (log (format &quot;Requesting page %d&quot; page-num) request)
                   (-&gt; (aws/invoke s3-client {:op :ListObjectsV2
                                              :request request})
                       validate-aws-response
                       (assoc :page-num page-num)))]
    response))

(defn list-objects [{:keys [s3-bucket limit] :as logs-client} prefix]
  (log &quot;Listing S3 objects&quot; (merge (-&gt;map s3-bucket prefix)
                                   (when limit {:limit limit})))
  (let [apply-limit (if limit (partial take limit) identity)]
    (-&gt;&gt; (iteration (partial get-s3-page logs-client prefix)
                    :vf :Contents)
         lazy-concat
         apply-limit
         (map :Key))))
</code></pre><p>I won&apos;t explain all this here. If you&apos;re curious, please do read the <a href="page-2.html">Page
2</a> post.</p><p>In any case, having done all of this, let&apos;s try using it:</p><pre><code class="language-clojure">(comment

  (def cfg {:aws-region &quot;eu-west-1&quot;
            :s3-bucket &quot;misc.jmglov.net&quot;
            :s3-page-size 1000})
  ;; =&gt; #&apos;user/cfg

  (def ctx (assoc cfg :s3-client
                  (aws/client {:api :s3, :region &quot;eu-west-1&quot;})))
  ;; =&gt; #&apos;user/ctx

  (-&gt;&gt; (list-objects ctx &quot;&quot;)
       (take 5))
  ;; =&gt; (&quot;.write_access_check_file.temp&quot;
  ;;     &quot;1-what-do-i-want.json&quot;
  ;;     &quot;Abeba_Birhane.json&quot;
  ;;     &quot;Adrian_C_Jackson.json&quot;
  ;;     &quot;Advice_Aniyia_Williams.json&quot;)

  )
</code></pre><p>Now we&apos;re getting somewhere!</p><div class="markdown-heading"><h2 id="no-one-is-afraid-of-json-voorhees">No one is afraid of JSON Voorhees</h2><a href="#no-one-is-afraid-of-json-voorhees" class="anchor" aria-label="Permalink: No one is afraid of JSON Voorhees"><img src="assets/link.svg" /></a></div><p>I recall using this bucket for some transcription I did for the excellent <a href="https://blubrry.com/1475055/">Conversations with Kim Crayton</a> podcast, which is what all those JSON files are. Perhaps I can do some organising here by moving them to a separate &quot;folder&quot;. Let&apos;s just see how many I&apos;m dealing with here:</p><pre><code class="language-clojure">(ns user
  (:require ; ...
            [clojure.string :as str])
  (:import (java.time Instant)))

(comment

  (-&gt;&gt; (list-objects ctx &quot;&quot;)
       (filter #(str/ends-with? % &quot;.json&quot;))
       count)
  ;; =&gt; 224

  )
</code></pre><p>And how many of these are in the &quot;root directory&quot;?</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (list-objects ctx &quot;&quot;)
       (filter #(and (str/ends-with? % &quot;.json&quot;)
                     (not (str/includes? % &quot;/&quot;))))
       count)
  ;; =&gt; 209

  )
</code></pre><p>That is many! Let&apos;s see about moving one into another folder:</p><pre><code class="language-clojure">(comment

  (def src-filename (-&gt;&gt; (list-objects ctx &quot;&quot;)
                         (filter #(and (str/ends-with? % &quot;.json&quot;)
                                       (not (str/includes? % &quot;/&quot;))))
                         first))
  ;; =&gt; #&apos;user/src-filename

  (aws/invoke (:s3-client ctx) {:op :GetObject
                                :request {:Bucket (:s3-bucket ctx)
                                          :Key src-filename}})
  ;; =&gt; {:LastModified #inst &quot;2023-02-25T10:40:19.000-00:00&quot;,
  ;;     :ETag &quot;\&quot;95a40408c21908a18e596f9b46eb10ac\&quot;&quot;,
  ;;     :Body
  ;;     #object[java.io.BufferedInputStream 0x19011b9f &quot;java.io.BufferedInputStream@19011b9f&quot;],
  ;;     :Metadata {},
  ;;     :ServerSideEncryption &quot;AES256&quot;,
  ;;     :ContentLength 290662,
  ;;     :ContentType &quot;binary/octet-stream&quot;,
  ;;     :AcceptRanges &quot;bytes&quot;,
  ;;     :VersionId &quot;ROt3VOKf67.OaoHFFsBTWCVSL4vIb7MI&quot;}

  )
</code></pre><p>OK, seems like the <code>:Body</code> is what we want here. It&apos;s an input stream, which is exactly what the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html">PutObject</a> API request wants, according to <a href="https://github.com/cognitect-labs/aws-api/blob/44711d911988b4d8dd309c19277ce53848605b49/examples/s3_examples.clj#L64">aws-api/examples/s3_examples.clj</a>. Let&apos;s give it a shot:</p><pre><code class="language-clojure">(comment

  (def target-filename (format &quot;podcasts/conversations-with-kim-crayton/%s&quot; src-filename))
  ;; =&gt; #&apos;user/target-filename

  (let [{:keys [s3-client s3-bucket]} ctx
        obj (aws/invoke s3-client {:op :GetObject
                                   :request {:Bucket s3-bucket
                                             :Key src-filename}})]
    (aws/invoke s3-client {:op :PutObject
                           :request {:Bucket s3-bucket
                                     :Key target-filename
                                     :Body (:Body obj)}}))
  ;; =&gt; {:ETag &quot;\&quot;95a40408c21908a18e596f9b46eb10ac\&quot;&quot;,
  ;;     :ServerSideEncryption &quot;AES256&quot;,
  ;;     :VersionId &quot;KuURLdZOq.qwk3Q6OYNG92Q2C49JYivc&quot;}

  (aws/invoke (:s3-client ctx) {:op :GetObject
                                :request {:Bucket (:s3-bucket ctx)
                                          :Key target-filename}})
  ;; =&gt; {:LastModified #inst &quot;2024-02-08T15:37:40.000-00:00&quot;,
  ;;     :ETag &quot;\&quot;95a40408c21908a18e596f9b46eb10ac\&quot;&quot;,
  ;;     :Body
  ;;     #object[java.io.BufferedInputStream 0x65579e67 &quot;java.io.BufferedInputStream@65579e67&quot;],
  ;;     :Metadata {},
  ;;     :ServerSideEncryption &quot;AES256&quot;,
  ;;     :ContentLength 290662,
  ;;     :ContentType &quot;binary/octet-stream&quot;,
  ;;     :AcceptRanges &quot;bytes&quot;,
  ;;     :VersionId &quot;KuURLdZOq.qwk3Q6OYNG92Q2C49JYivc&quot;}

  )
</code></pre><p>Now all we have to do is remove the &quot;file&quot; from the &quot;root directory&quot;:</p><pre><code class="language-clojure">(comment

  (aws/invoke (:s3-client ctx) {:op :DeleteObject
                                :request {:Bucket (:s3-bucket ctx)
                                          :Key src-filename}})
  ;; =&gt; {:DeleteMarker true, :VersionId &quot;sY4dbN7Knyff0B67Id5BeenVAT1bmN.k&quot;}

  (aws/invoke (:s3-client ctx) {:op :GetObject
                                :request {:Bucket (:s3-bucket ctx)
                                          :Key src-filename}})
  ;; =&gt; {:Error
  ;;     {:HostIdAttrs {},
  ;;      :KeyAttrs {},
  ;;      :Message &quot;The specified key does not exist.&quot;,
  ;;      :Key &quot;1-what-do-i-want.json&quot;,
  ;;      :CodeAttrs {},
  ;;      :RequestIdAttrs {},
  ;;      :HostId
  ;;      &quot;kE4zTuMao5e8TbMPn7rs1h48fNc9kEuMfBqLmayvcP+/SmEfbgfBGCsmJ3iZKcl6hpeyYKvSWXU=&quot;,
  ;;      :MessageAttrs {},
  ;;      :RequestId &quot;YV31XT7C98PQWTMX&quot;,
  ;;      :Code &quot;NoSuchKey&quot;},
  ;;     :ErrorAttrs {},
  ;;     :cognitect.aws.http/status 404,
  ;;     :cognitect.anomalies/category :cognitect.anomalies/not-found,
  ;;     :cognitect.aws.error/code &quot;NoSuchKey&quot;}

  )
</code></pre><p><img alt="Bill and Ted saying: excellent" src="assets/excellent.jpg" title="We are not worthy of the REPL!" /></p><div class="markdown-heading"><h2 id="getting-all-corporate-and-boring-and-stuff">Getting all corporate and boring and stuff</h2><a href="#getting-all-corporate-and-boring-and-stuff" class="anchor" aria-label="Permalink: Getting all corporate and boring and stuff"><img src="assets/link.svg" /></a></div><p>We&apos;ve been happily playing on the playground, but now we&apos;ve created some stuff that might be useful, specifically a function that lists a bunch of objects and some code that moves an object from one key to another. Let&apos;s apply some organisation to make this stuff more reusable.</p><p>First, we can move all of the utility functions out of <code>user.clj</code> into a new <code>src/util.clj</code> file:</p><pre><code class="language-clojure">(ns util
  (:import (java.time Instant)))

(defmacro -&gt;map [&amp; ks]
  (assert (every? symbol? ks))
  (zipmap (map keyword ks)
          ks))

(defn lazy-concat [colls]
  (lazy-seq
   (when-first [c colls]
     (lazy-cat c (lazy-concat (rest colls))))))

(defn log [msg data]
  (prn {:msg msg
        :data data
        :timestamp (str (Instant/now))}))

(defn error [msg data]
  (log msg data)
  (throw (ex-info msg data)))
</code></pre><p>And then the S3-specific stuff goes in a new <code>src/s3.clj</code> file:</p><pre><code class="language-clojure">(ns s3
  (:require [com.grzm.awyeah.client.api :as aws]
            [clojure.string :as str]
            [util :refer [log error lazy-concat -&gt;map]]))

(defn validate-aws-response [res]
  (when (:cognitect.anomalies/category res)
    (let [data (merge (select-keys res [:cognitect.anomalies/category])
                      {:err-msg (:Message res)
                       :err-type (:__type res)})]
      (error &quot;AWS request failed&quot; data)))
  res)

(defn mk-s3-req
  ([s3-bucket prefix s3-page-size]
   (mk-s3-req s3-bucket prefix s3-page-size nil))
  ([s3-bucket prefix s3-page-size continuation-token]
   (merge {:Bucket s3-bucket
           :Prefix prefix}
          (when s3-page-size
            {:MaxKeys s3-page-size})
          (when continuation-token
            {:ContinuationToken continuation-token}))))

(defn get-s3-page [{:keys [s3-client s3-bucket s3-page-size]}
                   prefix
                   {continuation-token :NextContinuationToken
                    truncated? :IsTruncated
                    page-num :page-num
                    :as prev}]
  (when prev (log &quot;Got page&quot; (dissoc prev :Contents)))
  (let [page-num (inc (or page-num 0))
        done? (false? truncated?)
        request (mk-s3-req s3-bucket prefix s3-page-size continuation-token)
        response (when-not done?
                   (log (format &quot;Requesting page %d&quot; page-num) request)
                   (-&gt; (aws/invoke s3-client {:op :ListObjectsV2
                                              :request request})
                       validate-aws-response
                       (assoc :page-num page-num)))]
    response))

(defn list-objects [{:keys [s3-bucket limit] :as logs-client} prefix]
  (log &quot;Listing S3 objects&quot; (merge (-&gt;map s3-bucket prefix)
                                   (when limit {:limit limit})))
  (let [apply-limit (if limit (partial take limit) identity)]
    (-&gt;&gt; (iteration (partial get-s3-page logs-client prefix)
                    :vf :Contents)
         lazy-concat
         apply-limit
         (map :Key))))

(defn mk-client [{:keys [aws-region] :as cfg}]
  (assoc cfg :s3-client
         (aws/client {:api :s3, :region aws-region})))
</code></pre><p>With this plumbing, let&apos;s write a function that actually moves an object:</p><pre><code class="language-clojure">(defn move-object [{:keys [s3-client s3-bucket] :as ctx} source-key target-key]
  (let [obj (aws/invoke s3-client {:op :GetObject
                                   :request {:Bucket s3-bucket
                                             :Key source-key}})]
    (aws/invoke s3-client {:op :PutObject
                           :request {:Bucket s3-bucket
                                     :Key target-key
                                     :Body (:Body obj)}})
    (aws/invoke (:s3-client ctx) {:op :DeleteObject
                                  :request {:Bucket s3-bucket
                                            :Key source-key}})))
</code></pre><p>And now back in <code>user.clj</code>, let&apos;s try it all out:</p><pre><code class="language-clojure">(comment

  (let [source-key (-&gt;&gt; (s3/list-objects ctx &quot;&quot;)
                        (filter #(and (str/ends-with? % &quot;.json&quot;)
                                      (not (str/includes? % &quot;/&quot;))))
                        first)
        target-key (format &quot;podcasts/conversations-with-kim-crayton/%s&quot; source-key)]
    (s3/move-object ctx source-key target-key))
  ;; =&gt; {:DeleteMarker true, :VersionId &quot;B6.FetnSH9qYS7FwCJOuY0NxiPL1ur7b&quot;}

  )
</code></pre><div class="markdown-heading"><h2 id="wrapping-it-all-up-in-a-neat-little-package">Wrapping it all up in a neat little package</h2><a href="#wrapping-it-all-up-in-a-neat-little-package" class="anchor" aria-label="Permalink: Wrapping it all up in a neat little package"><img src="assets/link.svg" /></a></div><p>Having built this beautiful little playground, I now have a REPL just lying around that I can try stuff out in, automate little things that I would normally do with a Bash &quot;one-liner&quot; that quickly grows into a Bash &quot;100-liner&quot;, and if and when I discover useful little functions, move them into namespaces under <code>src/</code>, ready to be copied and pasted into real programs.</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-02-09-counting-blog-posts.html</id>
    <link href="https://jmglov.net/blog/2024-02-09-counting-blog-posts.html"/>
    <title>Counting blog posts in 50 simple steps</title>
    <updated>2024-02-09T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="An abacus" src="assets/2024-02-09-preview.png" title="Photo by Crissy Jarvis on Unsplash" /></p><p>As I was writing <a href="2024-02-08-back-in-the-hammock-again.html">yesterday&apos;s post</a>, I wanted to count the number of posts I had written during my last involuntary vacation in the summer of 2022. There is of course a very simple way to do this:</p><ol start="1"><li>Navigate to the <a href="archive.html">archive page</a> of my blog</li><li>Realise that whilst there are only (as of the writing of yesterday&apos;s post) two posts in 2024 (three as of the writing of this post, since yesterday&apos;s is now there, and in fact four as of the reading of this post, because now this post is also there) and three in 2023, there were enough in 2022 that counting them by hand smacks of effort</li><li>Decide to use <a href="https://github.com/babashka/babashka">Babashka</a> to count the posts, since this blog is powered by <a href="https://github.com/borkdude/quickblog">quickblog</a> and thus the posts are right at hand</li><li>Assert that it should be as easy as dropping a <code>user.clj</code> on the blog&apos;s classpath</li><li>Open up the blog&apos;s <a href="https://github.com/jmglov/jmglov.net/blob/main/bb.edn">bb.edn</a> to figure out how to do this:<pre><code class="language-clojure">{:deps {jmglov/jmglov {:local/root &quot;.&quot;}
        io.github.borkdude/quickblog {:local/root &quot;../clojure/quickblog&quot;}
        #_&quot;You use the newest SHA here:&quot;
        #_{:git/sha &quot;b69c11f4292702f78a8ac0a9f32379603bebf2af&quot;}
       }
 ;; ...
}
</code></pre></li><li>Realise that the classpath is set up in <code>deps.edn</code>, because of this incantation:<pre><code class="language-clojure">{jmglov/jmglov {:local/root &quot;.&quot;}
</code></pre></li><li>Open up <code>deps.edn</code> instead:<pre><code class="language-clojure">{:paths [&quot;.&quot; &quot;classes&quot;]
 :deps {markdown-clj/markdown-clj {:mvn/version &quot;1.10.7&quot;}
        org.babashka/cli {:mvn/version &quot;0.8.55&quot;}
        babashka/fs {:mvn/version &quot;0.1.6&quot;}
        org.clojure/data.xml {:mvn/version &quot;0.2.0-alpha6&quot;}
        hiccup/hiccup {:mvn/version &quot;2.0.0-alpha2&quot;}
        babashka/pods {:git/url &quot;https://github.com/babashka/pods&quot;
                       :git/sha &quot;93081b75e66fb4c4d161f89e714c6b9e8d55c8d5&quot;}
        rewrite-clj/rewrite-clj {:mvn/version &quot;1.1.45&quot;}
        selmer/selmer {:mvn/version &quot;1.12.53&quot;}}}
</code></pre></li><li>Armed with the knowledge that base directory is on the path, drop a <code>user.clj</code> there:<pre><code class="language-clojure">(ns user)
</code></pre></li><li>Poise your hands elegantly above your keyboard like a concert pianist, then, imagining the swells of the string section as they invite you in and the upraised faces of the expecting crowd, attack the keyboard with a <strong>C-c M-j</strong> (<code>cider-jack-in-clj</code>) and select babashka from the REPL options! 🎉</li><li>Refer back to <code>bb.edn</code> to see how the quickblog opts are defined:<pre><code class="language-clojure">{:deps { ; ...
        }
 :tasks
 {:init (def opts {:blog-title &quot;jmglov&apos;s blog&quot;
                   :blog-author &quot;Josh Glover&quot;
                   :blog-description &quot;A blog about stuff but also things.&quot;
                   :blog-root &quot;https://jmglov.net/blog/&quot;
                   :about-link &quot;https://jmglov.net/&quot;
                   :twitter-handle &quot;jmglov&quot;
                   :assets-dir &quot;blog/assets&quot;
                   :num-index-posts 3
                   :cache-dir &quot;.cache&quot;
                   :favicon true
                   :favicon-dir &quot;favicon&quot;
                   :out-dir &quot;public/blog&quot;
                   :posts-dir &quot;blog/posts&quot;
                   :templates-dir &quot;blog/templates&quot;})

  :requires ([babashka.cli]
             [babashka.fs :as fs]
             [clojure.string :as str]
             [quickblog.api :as qb]
             [quickblog.cli :as cli])
  ;; ...
 }}
</code></pre></li><li>Start to copy the <code>(def opts {...})</code> bit into <code>user.clj</code>, but then, struck by a blinding flash of insight that <code>bb.edn</code> is just EDN, decide to Not Repeat Yourself (<a href="https://en.wikipedia.org/wiki/Don&apos;t_repeat_yourself">NRY</a>, obv) and just read in <code>bb.edn</code> and set opts from what&apos;s defined there:<pre><code class="language-clojure">(ns user
  (:require [clojure.edn :as edn]))

(comment

  (-&gt; (slurp &quot;bb.edn&quot;)
      edn/read-string
      :tasks
      :init)
  ;; (def opts {:blog-title &quot;jmglov&apos;s blog&quot;
                :blog-author &quot;Josh Glover&quot;
                :blog-description &quot;A blog about stuff but also things.&quot;
                :blog-root &quot;https://jmglov.net/blog/&quot;
                :about-link &quot;https://jmglov.net/&quot;
                :twitter-handle &quot;jmglov&quot;
                :assets-dir &quot;blog/assets&quot;
                :num-index-posts 3
                :cache-dir &quot;.cache&quot;
                :favicon true
                :favicon-dir &quot;favicon&quot;
                :out-dir &quot;public/blog&quot;
                :posts-dir &quot;blog/posts&quot;
                :templates-dir &quot;blog/templates&quot;})
)
</code></pre></li></ol><pre><code>12. Celebrate your genius and [eval](https://clojuredocs.org/clojure.core/eval)
 that string (making sure of course that you&apos;re only eval&apos;ing it if it&apos;s
 `(def opts ...)` and nothing untoward and/or sinister)!
 ``` clojure
 (comment

   (let [[form &amp; params :as expr] (-&gt; (slurp &quot;bb.edn&quot;)
                                      edn/read-string
                                      :tasks
                                      :init)]
     (when (and (= &apos;def form) (= &apos;opts (first params)))
       (eval expr)))
   ;; =&gt; #&apos;user/opts
 
   opts
   ;; =&gt; {:blog-description &quot;A blog about stuff but also things.&quot;,
   ;;     :blog-author &quot;Josh Glover&quot;,
   ;;     :num-index-posts 3,
   ;;     :favicon-dir &quot;favicon&quot;,
   ;;     :posts-dir &quot;blog/posts&quot;,
   ;;     :assets-dir &quot;blog/assets&quot;,
   ;;     :templates-dir &quot;blog/templates&quot;,
   ;;     :favicon true,
   ;;     :out-dir &quot;public/blog&quot;,
   ;;     :blog-root &quot;https://jmglov.net/blog/&quot;,
   ;;     :link-posts true,
   ;;     :cache-dir &quot;.cache&quot;,
   ;;     :about-link &quot;https://jmglov.net/&quot;,
   ;;     :blog-title &quot;jmglov&apos;s blog&quot;}
 
 )
 ```
12. Revel in the power of Lisp: verily code is data and data is code!
13. Realise that you are a silly silly person and that there&apos;s a much less
 ridiculous way to do this: move the opts to a file named `opts.edn`...
 ``` clojure
     {:blog-title &quot;jmglov&apos;s blog&quot;
  :blog-author &quot;Josh Glover&quot;
  :blog-description &quot;A blog about stuff but also things.&quot;
  :blog-root &quot;https://jmglov.net/blog/&quot;
  :about-link &quot;https://jmglov.net/&quot;
  :assets-dir &quot;blog/assets&quot;
  :num-index-posts 3
  :cache-dir &quot;.cache&quot;
  :favicon true
  :favicon-dir &quot;favicon&quot;
  :out-dir &quot;public/blog&quot;
  :posts-dir &quot;blog/posts&quot;
  :templates-dir &quot;blog/templates&quot;
  :link-posts true}
 ```
14. ...and read them in `bb.edn`:
 ``` clojure
 { ; ...
  :tasks
  {:requires ([babashka.cli]
              [babashka.fs :as fs]
              [clojure.edn :as edn]
              [clojure.string :as str]
              [quickblog.api :as qb]
              [quickblog.cli :as cli])
   :init (def opts (slurp &quot;opts.edn&quot;))
   ;; ...
  }}
 ```
15. ...and also in `user.clj`:
 ``` clojure
 (ns user
   (:require [clojure.edn :as edn]))
   
 (comment
 
   (def opts (-&gt; (slurp &quot;opts.edn&quot;) edn/read-string))
   ;; =&gt; #&apos;user/opts
 
   opts
   ;; =&gt; {:blog-description &quot;A blog about stuff but also things.&quot;,
   ;;     :blog-author &quot;Josh Glover&quot;,
   ;;     :num-index-posts 3,
   ;;     :favicon-dir &quot;favicon&quot;,
   ;;     :posts-dir &quot;blog/posts&quot;,
   ;;     :assets-dir &quot;blog/assets&quot;,
   ;;     :templates-dir &quot;blog/templates&quot;,
   ;;     :favicon true,
   ;;     :out-dir &quot;public/blog&quot;,
   ;;     :blog-root &quot;https://jmglov.net/blog/&quot;,
   ;;     :link-posts true,
   ;;     :cache-dir &quot;.cache&quot;,
   ;;     :about-link &quot;https://jmglov.net/&quot;,
   ;;     :blog-title &quot;jmglov&apos;s blog&quot;}
 
  )
 ```
16. Now try and remember how to load posts in quickblog. Maybe [the API
    documentation](https://github.com/borkdude/quickblog/blob/ebf91f5859d36aeee1a52af14538f379eb76c64a/API.md#render)
 has a clue?
 ``` text
 (render opts)
 
 Renders posts declared in posts.edn to out-dir.
 ```
17. Conclude that whilst rendering the blog shouldn&apos;t be necessary to count the
 posts, the [source code for
    `render`](https://github.com/borkdude/quickblog/blob/ebf91f5859d36aeee1a52af14538f379eb76c64a/src/quickblog/api.clj#L467)
 must contain incantations of great power that load posts before rendering
 them:
 ``` clojure
 (defn render
   &quot;Renders posts declared in `posts.edn` to `out-dir`.&quot;
   [opts]
   (let [{:keys [assets-dir
                    assets-out-dir
                    cache-dir
                    favicon-dir
                    favicon-out-dir
                    out-dir
                    posts-file
                    templates-dir]
          :as opts}
         (-&gt; opts apply-default-opts lib/refresh-cache)]
   ;; ...
   ))
 ```
18. Armed with this arcane knowledge, return to `user.clj`:
 ``` clojure
 (ns user
   (:require ; ...
             [quickblog.api :as qb]
             [quickblog.internal :as lib]))
 
 (defn load-opts [base-opts]
   (-&gt; base-opts
       #&apos;qb/apply-default-opts
       lib/refresh-cache))
 
 (comment
 
   (def base-opts (-&gt; (slurp &quot;opts.edn&quot;) edn/read-string))
   ;; =&gt; #&apos;user/base-opts
 
   (def opts (load-opts base-opts))
   ;; =&gt; #&apos;user/opts
 
   (keys opts)
   ;; =&gt; (:blog-description
   ;;     :blog-author
   ;;     :num-index-posts
   ;;     :favicon-dir
   ;;     :posts-dir
   ;;     :assets-dir
   ;;     :modified-posts
   ;;     :cached-posts
   ;;     :templates-dir
   ;;     :deleted-posts
   ;;     :favicon
   ;;     :modified-metadata
   ;;     :out-dir
   ;;     :blog-root
   ;;     :modified-tags
   ;;     :link-posts
   ;;     :cache-dir
   ;;     :about-link
   ;;     :blog-title
   ;;     :posts)
 
  )
 ```
19. Count all the posts!
 ``` clojure
 (comment
 
   (-&gt;&gt; opts
        :posts
        count)
   ;; =&gt; 71
 
  )
 ```
20. Break out the champagne! 🍾
21. Remember that the goal wasn&apos;t to count all of the posts, but rather the ones
 from the summer of 2022 before I started my old new job 😢
22. See what a post looks like so you can figure out this whole date thing:
 ``` clojure
 (comment
 
   ;; =&gt; ([&quot;2022-08-26-doing-software-wrong.md&quot;
      ;;      {:description
      ;;       &quot;In which I make a bold statement, but then rather than explaining it or providing any evidence whatsoever, go on to talk about something completely different.&quot;,
      ;;       :tags #{&quot;waffle&quot;},
      ;;       :date &quot;2022-08-26&quot;,
      ;;       :file &quot;2022-08-26-doing-software-wrong.md&quot;,
      ;;       :title &quot;We&apos;re doing software wrong&quot;,
      ;;       :image-alt
      ;;       &quot;A man on a mobile phone stands in front of a wall with the word \&quot;productivity\&quot; written on it - Photo by Andreas Klassen on Unsplash&quot;,
      ;;       :image &quot;assets/2022-08-26-preview.jpg&quot;,
      ;;       :html #&lt;Delay@6b4fc6d6: :not-delivered&gt;}])
 
  )
 ```
23. Realise that `:posts` is a map of filename to post, but no matter!
``` clojure
(comment

(-&gt;&gt; opts
    :posts
    vals
    (map :date))
;; =&gt; (&quot;2022-08-26&quot;
;;     &quot;2022-06-22&quot;
;;     &quot;2023-11-12&quot;
;;     &quot;2022-07-01&quot;
;;     &quot;2022-07-31&quot;
;;     &quot;2022-07-09&quot;
;;     &quot;2022-06-21&quot;
;;     ...
;;     &quot;2022-07-02&quot;)

)
</code></pre><ol start="24"><li>Sigh as you come to terms with the fact that you&apos;re going to need to do some date parsing and you never remember how to use <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/package-summary.html">java.time</a> and argh!</li><li>Smile as you remember about <a href="https://github.com/juxt/tick">tick</a>, which is a library from our good friends at <a href="https://www.juxt.pro/">JUXT</a> that provides a nicer API for this sort of stuff</li><li>Since you hate restarting your REPL, use the power of Babashka to hotload the dependency right in <code>user.clj</code>:</li></ol><pre><code class="language-clojure">(ns user
  (:require [babashka.deps :as deps]
            ;; ...
            ))

(comment

  (deps/add-deps &apos;{:deps {tick/tick {:mvn/version &quot;0.7.5&quot;}}})
  ;; =&gt; nil

  (require &apos;[tick.core :as t])
  ;; =&gt; clojure.lang.ExceptionInfo: Could not resolve symbol: java.time.temporal.TemporalQuery user cljc/java_time/format/date_time_formatter.clj:33:444

 )
</code></pre><ol start="27"><li>Swear as you realise that tick must not work with Babashka 🤬</li><li>Scratch your head as you read that tick is &quot;a Clojure(Script) &amp; babashka library for dealing with time&quot; and explicitly mentions Babashka so 😕</li><li>Search #babashka on Clojurians Slack for tick and find <a href="https://clojurians.slack.com/archives/CLX41ASCS/p1677842827651279">borkdude
    mentioning</a> <a href="https://clojurians.slack.com/archives/C06MAR553/p1677842754963519">a message in
    #announcements</a> that claims that &quot;the new version works with babashka&quot;. Note the date of this message as 2023-04-03.</li><li>Suspect that you may be running an older version of Babashka that doesn&apos;t ship with <code>java.time.temporal.TemporalQuery</code> and have a look at <a href="https://github.com/babashka/babashka/blob/771f69d922b9c674bdfa1ae02f53691c54e28170/src/babashka/impl/classes.clj#L453">src/babashka/impl/classes.clj</a> in the Babashka codebase to see when it was added</li><li>Track down <a href="https://github.com/babashka/babashka/commit/ead237eee335fc3bc4cdfc88e3fb4af821878b3c">commit
    ead237e</a> and note that it made it into Babashka <a href="https://github.com/babashka/babashka/releases/tag/v1.2.174">v1.2.174</a></li><li>Figure out what version of Babashka you&apos;re running:<pre><code class="language-text">$ bb --version
babashka v1.1.173
</code></pre></li><li>Realise that you&apos;ve found the issue and need to upgrade Babashka</li><li>Since you&apos;re using <a href="https://github.com/nix-community/home-manager">Home
    Manager</a> on <a href="https://nixos.org/">NixOS</a> like a normal person who is totally normal, open up your <a href="https://github.com/jmglov/nixos-config/blob/79752ae530ab0036b569cc0bc848cdda29a43af8/jmglov/home.nix">home.nix</a></li><li>Note that apparently you&apos;re installing the binary version of Babashka in your own package that you wrote like a normal person who is totally normal and open up <a href="https://github.com/jmglov/nixos-config/blob/79752ae530ab0036b569cc0bc848cdda29a43af8/jmglov/pkgs/babashka-bin/default.nix">pkgs/babashka-bin/default.nix</a>:<pre><code class="language-nix">{ stdenv, ... }:

let
  arch = if stdenv.isAarch64 then &quot;aarch64&quot; else &quot;amd64&quot;;
  osName = if stdenv.isDarwin then
    &quot;macos&quot;
  else if stdenv.isLinux then
    &quot;linux&quot;
  else
    null;
  sha256 = assert !isNull osName;
    {
      linux = {
        aarch64 =
          &quot;bc7e733863486b334b8bff83ba13b416800e0ce45050153cb413906b46090d68&quot;;
        amd64 =
          &quot;25975d5424e7dea9fbaef5a6551ce7d3834631b5e28bdc4caf037bf45af57dfd&quot;;
      };
      macos = {
        # No MacOS builds for ARM at the moment
        # aarch64 =
        #   &quot;11c4b4bd0b534db1ecd732b03bc376f8b21bbda0d88cacb4bbe15b8469029123&quot;;
        amd64 =
          &quot;792ade86e61703170f3de3082183173db66a9a98b11d01c95ace0235f0a5e345&quot;;
      };
    }.${osName}.${arch};
in stdenv.mkDerivation rec {
  pname = &quot;babashka&quot;;
  version = &quot;1.1.173&quot;;
  filename = if osName == &quot;macos&quot; then
  # No static builds for MacOS
    &quot;babashka-${version}-${osName}-${arch}.tar.gz&quot;
  else
    &quot;babashka-${version}-${osName}-${arch}-static.tar.gz&quot;;

  src = builtins.fetchurl {
    inherit sha256;
    url =
      &quot;https://github.com/babashka/babashka/releases/download/v${version}/${filename}&quot;;
  };

  dontFixup = true;
  dontUnpack = true;

  installPhase = &apos;&apos;
    mkdir -p $out/bin
    cd $out/bin &amp;&amp; tar xvzf $src
  &apos;&apos;;
}
</code></pre></li><li>Avoid the urge to celebrate your own genius and instead pop over to the <a href="https://github.com/babashka/babashka/releases">Babashka releases page</a> on Github and find that the latest release is <a href="https://github.com/babashka/babashka/releases/tag/v1.3.188">v1.3.188</a></li><li>Grab the SHA256 hashes you&apos;re going to need to plug into your Nix package:<pre><code class="language-text">$ curl -L https://github.com/babashka/babashka/releases/download/v1.3.188/babashka-1.3.188-linux-aarch64-static.tar.gz.sha256
</code></pre></li></ol><p>417280537b20754b675b7552d560c4c2817a93fbcaa0d51e426a1bff385e3e47 <span class="formula"> curl -L https://github.com/babashka/babashka/releases/download/v1.3.188/babashka-1.3.188-linux-amd64-static.tar.gz.sha256
89431b0659e84a468da05ad78daf2982cbc8ea9e17f315fa2e51fecc78af7cc0
</span> curl -L <a href="https://github.com/babashka/babashka/releases/download/v1.3.188/babashka-1.3.188-macos-aarch64.tar.gz.sha256">https://github.com/babashka/babashka/releases/download/v1.3.188/babashka-1.3.188-macos-aarch64.tar.gz.sha256</a> 77eb9ec502260fa94008e1e43edc5678fab8dc1a5082b7eb3d28ae594ea54e09 <span class="formula"> curl -L https://github.com/babashka/babashka/releases/download/v1.3.188/babashka-1.3.188-macos-amd64.tar.gz.sha256
d8854833a052bb578360294d6975b85ed917b9f86da0068fb3c263f8cbcc9e15
```
38. Update the SHAs and Babashka version in your Nix package:
``` nix
let
# ...
sha256 = {
linux = {
aarch64 =
&quot;417280537b20754b675b7552d560c4c2817a93fbcaa0d51e426a1bff385e3e47&quot;;
amd64 =
&quot;89431b0659e84a468da05ad78daf2982cbc8ea9e17f315fa2e51fecc78af7cc0&quot;;
};
macos = {
aarch64 =
&quot;77eb9ec502260fa94008e1e43edc5678fab8dc1a5082b7eb3d28ae594ea54e09&quot;;
amd64 =
&quot;d8854833a052bb578360294d6975b85ed917b9f86da0068fb3c263f8cbcc9e15&quot;;
};
}.</span>{osName}.<span class="formula">{arch};
in stdenv.mkDerivation rec {
pname = &quot;babashka&quot;;
version = &quot;1.3.188&quot;;
# ...
}
```
39. Update Babashka:
``` text
</span> sudo nixos-rebuild switch building Nix... building the system configuration... these 8 derivations will be built: /nix/store/x9c0ip7xchwzhkhznvjz5r57krcqjm3r-babashka-1.3.188.drv /nix/store/lsq07jvqmk5kywbdrj55vh3ndjrw2vwm-home-manager-path.drv [...] building &apos;/nix/store/x9c0ip7xchwzhkhznvjz5r57krcqjm3r-babashka-1.3.188.drv&apos;... patching sources updateAutotoolsGnuConfigScriptsPhase configuring no configure script, doing nothing building no Makefile or custom buildPhase, doing nothing installing bb [...] activating the configuration... setting up /etc... reloading user units for jmglov... setting up tmpfiles restarting the following units: home-manager-jmglov.service <code>40. Trust but verify:</code> text $ bb --version babashka v1.3.188 <code>41. Hang your head in shame as you prepare to restart your REPL, but take the opportunity to add tick to your `deps.edn` so you won&apos;t have to hotload it in `user.clj`:</code> clojure {:paths [&quot;.&quot; &quot;classes&quot;] :deps { ; ... tick/tick {:mvn/version &quot;0.7.5&quot;}}} <code>42. Drop back into `user.clj`, then **C-c C-z** to hop to your REPL buffer, **C-c C-q** to quit it, then **C-c M-j** to start a new REPL, then require tick in the ns form:</code> clojure (ns user (:require ; ... [tick.core :as t])) <code>43. Evaluate the buffer with **C-c C-k** and get to ticking! 44. Figure out how to parse a date string like &quot;2022-07-02&quot; by looking at the [tick
    cheatsheet](https://github.com/juxt/tick/blob/master/docs/cheatsheet.md#fromto-strings), a sheet that lets you cheat, apparently:</code> clojure (comment</p><pre><code>  (t/date &quot;2022-07-02&quot;)
  ;; =&gt; #time/date &quot;2022-07-02&quot;

 )
```
</code></pre><ol start="46"><li>Turn the date strings into date dates:<pre><code class="language-clojure">(comment

  (def opts (-&gt; (slurp &quot;opts.edn&quot;) edn/read-string load-opts))
  ;; =&gt; #&apos;user/opts

  (-&gt;&gt; opts
       :posts
       vals
       (map (comp t/date :date)))
  ;; =&gt; (#time/date &quot;2022-08-26&quot;
  ;;     #time/date &quot;2022-06-22&quot;
  ;;     #time/date &quot;2023-11-12&quot;
  ;;     #time/date &quot;2022-07-01&quot;
  ;;     ...
  ;;     #time/date &quot;2022-07-02&quot;)

 )
</code></pre></li><li>Ask yourself what you were doing again?</li><li>Oh yeah, counting posts before September 1, 2022, which was when I started my old new job</li><li>Say this in Clojure, not English!<pre><code class="language-clojure">(comment

  (-&gt;&gt; opts
       :posts
       vals
       (remove #(= &quot;FIXME&quot; (:date %)))
       (map (comp t/date :date))
       (filter #(t/&lt; % (t/date &quot;2022-09-01&quot;)))
       count)
  ;; =&gt; 55

 )
</code></pre></li><li>Sit back and reflect on just how easy that was and how it took less time than just counting those 55 things with your finger</li></ol></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-01-22-clickr-goes-fe.html</id>
    <link href="https://jmglov.net/blog/2024-01-22-clickr-goes-fe.html"/>
    <title>clickr goes frontend</title>
    <updated>2024-01-22T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>![A cartoon version of the Drake hotline bling meme: Drake is disgusted by the
S3 console and delighted by the Flickr UI][drake] [drake]: assets/2024-01-22-drake.png &quot;How many Clojurians does it take to clone Flickr?&quot;</p><p>Previously on this blog, <a href="2024-01-17-clickr.html">my heart was filled with sadness as I realised that
archiving photos to S3 wasn&apos;t actually a Flickr
replacement</a>. Currently on this blog, my heart is filled with a steely resolve as I take my destiny into my own hands and... I guess write some CSS or something?</p><p>As cartoon Drake so helpfully points out above, the S3 console is missing a few of the features that you would expect from an online photo album:</p><ul><li>A highlighted image for the album</li><li>The album&apos;s name and description</li><li>Visual display of the photos in the album</li></ul><p>Clearly something must be done about this! Luckily for me, an S3 bucket can actually be used to serve up a website—in fact, this very blog is coming to you live from S3—so if I can just write some HTML alongside the photos, Robert should be one of my parents&apos; siblings. If you cast your mind back to last week, you may recall that in the process of backing up albums from Flickr, we wrote some code that had a pretty nice data representation of an album:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (get-albums ctx)
       first
       (download-album! ctx))
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :title &quot;clickr demo&quot;,
  ;;     :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;     :photos
  ;;     ({:description nil,
  ;;       :date-taken nil,
  ;;       :geo-data nil,
  ;;       :rotation -1,
  ;;       :width 0,
  ;;       :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;       :filename &quot;53460147147.jpg&quot;,
  ;;       :id &quot;53460147147&quot;,
  ;;       :object
  ;;       #object[com.flickr4java.flickr.photos.Photo 0x4a25d150 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;       :height 0}
  ;;      ;; [...]
  ;;      {:description nil,
  ;;       :date-taken nil,
  ;;       :geo-data nil,
  ;;       :rotation -1,
  ;;       :width 0,
  ;;       :title &quot;daniel-jennings-img-7554&quot;,
  ;;       :filename &quot;53460151727.jpg&quot;,
  ;;       :id &quot;53460151727&quot;,
  ;;       :object
  ;;       #object[com.flickr4java.flickr.photos.Photo 0x3fb5100f &quot;com.flickr4java.flickr.photos.Photo@436e36e8&quot;],
  ;;       :height 0}),
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photosets.Photoset 0x2be46a3b &quot;com.flickr4java.flickr.photosets.Photoset@2be46a3b&quot;]}

  )
</code></pre><p>This is a fantastic starting point, because if Clojure is good at anything, it&apos;s transforming data from one shape to another, and HTML is just data. Let&apos;s take a closer look at what this album looks like in Flickr, and see if we can&apos;t identify a basic layout to <s>steal</s> borrow with pride:</p><p>![The Flickr site, displaying the photos in the clickr demo album][flickralbum] [flickralbum]:[assets/2024-01-17-album-flickr.png &quot;OMG 🤩&quot;]</p><p>If we were to lay this out in HTML, it could look something like this:</p><pre><code class="language-html">&lt;body id=&quot;body&quot;&gt;
    &lt;div id=&quot;album&quot;&gt;
        &lt;div id=&quot;back&quot;&gt;⬅ Back to albums list&lt;/div&gt;
        &lt;div id=&quot;album-header&quot;&gt;
            &lt;div id=&quot;album-title&quot;&gt;clickr demo&lt;/div&gt;
            &lt;div id=&quot;album-description&quot;&gt;Photo album demo for my clickr blog post&lt;/div&gt;
        &lt;/div&gt;
        &lt;div id=&quot;photos&quot;&gt;
            &lt;img id=&quot;photo-53460147147&quot; src=&quot;53460147147.jpg&quot; /&gt;
            &lt;!-- ... --&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;
</code></pre><p>You only have to squint at the Clojure data structure a little bit to see how it could be massaged into this shape. So let&apos;s get massaging!</p><div class="markdown-heading"><h2 id="damn-the-hiccups,-full-speed-ahead!">Damn the hiccups, full speed ahead!</h2><a href="#damn-the-hiccups,-full-speed-ahead!" class="anchor" aria-label="Permalink: Damn the hiccups, full speed ahead!"><img src="assets/link.svg" /></a></div><p>One of the classic ways to turn Clojure data into HTML is <a href="https://github.com/weavejester/hiccup">Hiccup</a>, which I really like and have used quite a bit. However, in the production of this blog, I got introduced to <a href="https://github.com/yogthos/Selmer">Selmer</a>, which is the template system that <a href="https://github.com/borkdude/quickblog">quickblog</a> uses to render HTML, and is so cool that it is one of the batteries included in <a href="https://babashka.org/">Babashka</a>. All of this is to say: let&apos;s use Selmer here! I can actually just take the HTML fragment above and Selmerise it with only a few keystrokes!</p><pre><code class="language-html">&lt;body id=&quot;body&quot;&gt;
    &lt;div id=&quot;album&quot;&gt;
        &lt;div id=&quot;back&quot;&gt;⬅ Back to albums list&lt;/div&gt;
        &lt;div id=&quot;album-header&quot;&gt;
            &lt;div id=&quot;album-title&quot;&gt;{{album.title}}&lt;/div&gt;
            &lt;div id=&quot;album-description&quot;&gt;{{album.description}}&lt;/div&gt;
        &lt;/div&gt;
        &lt;div id=&quot;photos&quot;&gt;
            {% for photo in album.photos %}
            &lt;img id=&quot;photo-{{photo.id}}&quot; src=&quot;{{photo.filename}}&quot; /&gt;
            {% endfor %}
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;
</code></pre><p>OK, that was easy. But of course a <code>&lt;body&gt;</code> does not an HTML page make, so let&apos;s create a <code>resources/templates/album.html</code> file and throw in the rest of the stuff that we need:</p><pre><code class="language-html">&lt;!doctype html&gt;
&lt;html class=&quot;no-js&quot; lang=&quot;en&quot;&gt;

&lt;head&gt;
    &lt;title&gt;{{album.title}}&lt;/title&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;/head&gt;

&lt;body id=&quot;body&quot;&gt;
    &lt;!--[if lt IE 8]&gt;
          &lt;p class=&quot;browserupgrade&quot;&gt;
          You are using an &lt;strong&gt;outdated&lt;/strong&gt; browser. Please
          &lt;a href=&quot;http://browsehappy.com/&quot;&gt;upgrade your browser&lt;/a&gt; to improve
          your experience.
          &lt;/p&gt;
        &lt;![endif]--&gt;
    &lt;div id=&quot;album&quot;&gt;
        &lt;div id=&quot;back&quot;&gt;⬅ Back to albums list&lt;/div&gt;
        &lt;div id=&quot;album-header&quot;&gt;
            &lt;div id=&quot;album-title&quot;&gt;{{album.title}}&lt;/div&gt;
            &lt;div id=&quot;album-description&quot;&gt;{{album.description}}&lt;/div&gt;
        &lt;/div&gt;
        &lt;div id=&quot;photos&quot;&gt;
            {% for photo in album.photos %}
            &lt;img id=&quot;photo-{{photo.id}}&quot; src=&quot;{{photo.filename}}&quot; /&gt;
            {% endfor %}
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre><p>This is actually all we need to make an awesome photo album. Let&apos;s write the Clojure code that will write the HTML that will make the browser happy!</p><p>First, we need to add Selmer to our <code>deps.edn</code>:</p><pre><code class="language-clojure">{:paths [&quot;src&quot; &quot;dev&quot;]
 :deps {babashka/fs {:mvn/version &quot;0.4.19&quot;}
        com.cognitect.aws/api {:mvn/version &quot;0.8.686&quot;}
        com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.504&quot;}
        com.cognitect.aws/s3 {:mvn/version &quot;848.2.1413.0&quot;}
        com.flickr4java/flickr4java {:mvn/version &quot;3.0.1&quot;}
        selmer/selmer {:mvn/version &quot;1.12.59&quot;}}}
</code></pre><p>Then let&apos;s create a namespace that will be responsible for producing HTML:</p><pre><code class="language-clojure">(ns clickr.html
  (:require [selmer.parser :as selmer]))
</code></pre><p>Then we can write a function that turns an album into the HTML representation of said album:</p><pre><code class="language-clojure">(defn album-&gt;html [_ctx album]
  (selmer/render (slurp &quot;resources/templates/album.html&quot;)
                 {:album album}))
</code></pre><p>Yes, it really is that simple! But don&apos;t take my word for it; ask the REPL!</p><pre><code class="language-clojure">(comment

  (require &apos;[clickr.flickr :as flickr])
  ;; =&gt; nil

  (def config {:api-key &quot;beefface5678910&quot;
               :secret &quot;facecafe1234&quot;
               :s3-bucket &quot;photos.jmglov.net&quot;
               :s3-prefix &quot;clickr&quot;
               :out-dir &quot;/home/jmglov/Pictures/clickr&quot;})
  ;; =&gt; #&apos;clickr.html/config

  (def ctx (flickr/init-client config))
  ;; =&gt; #&apos;clickr.html/ctx

  (def album (-&gt;&gt; (flickr/get-albums ctx) first (flickr/download-album ctx)))
  ;; =&gt; #&apos;clickr.html/album

  (album-&gt;html ctx album)
  ;; =&gt; &quot;&lt;!doctype html&gt;\n&lt;html class=\&quot;no-js\&quot; lang=\&quot;en\&quot;&gt;\n\n&lt;head&gt;\n    &lt;title&gt;clickr demo&lt;/title&gt;\n ... \n&lt;/body&gt;\n\n&lt;/html&gt;\n&quot;

  )
</code></pre><p>Of course, all of this HTML isn&apos;t very useful unless we write it somewhere a browser can find it. Let&apos;s follow the same pattern we used for <code>download-album!</code>: we&apos;ll take the data representation of an album, write an <code>index.html</code> in its output directory (assuming it has already been downloaded), and then assoc the location of the HTML file into the album.</p><p>Since we&apos;re building paths, let&apos;s require in our old friend <code>babashka.fs</code>:</p><pre><code class="language-clojure">(ns clickr.html
  (:require [babashka.fs :as fs]
            [selmer.parser :as selmer]))
</code></pre><p>Now we have everything we need to write our function.</p><pre><code class="language-clojure">(defn write-album-html! [ctx {:keys [out-dir] :as album}]
  (when-not out-dir
    (throw (ex-info &quot;Album must be downloaded before writing it to HTML&quot;
                    {:album album})))
  (let [html (album-&gt;html ctx album)
        html-file (fs/file out-dir &quot;index.html&quot;)]
    (spit html-file html)
    (assoc album :html-file html-file)))

(comment

  (write-album-html! ctx album)
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :title &quot;clickr demo&quot;,
  ;;     :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;     :photos (...)
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photosets.Photoset 0x2e486856 &quot;com.flickr4java.flickr.photosets.Photoset@2e486856&quot;],
  ;;     :out-dir #object[java.io.File 0x68210928 &quot;/tmp/72177720314024335&quot;],
  ;;     :html-file
  ;;     #object[java.io.File 0x6c47b5ea &quot;/tmp/72177720314024335/index.html&quot;]}

  )
</code></pre><p>If we open up <code>/tmp/72177720314024335/index.html</code> in a web browser, we are sure to be greeted with a glorious sight!</p><p><img alt="A webpage with three lines of text and no photos" src="assets/2024-01-22-disappointment.png" title="This is not the album you&apos;re looking for" /></p><p>OK, so that was a crushing disappointment. 🙁</p><p>Remember how amazing this looks in Flickr? Let&apos;s use the browser&apos;s inspector to peek behind the curtain and see how Flickr does it:</p><p><img alt="Web browser inspector with a photo div highlighted on Flickr" src="assets/2024-01-22-flickr-magic.png" title="Pay full attention to the CSS behind the curtain" /></p><p>Ah, so they&apos;re not using <code>&lt;img&gt;</code> tags at all; they&apos;re using <code>&lt;div&gt;</code> tags with some magic <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-image">background-image</a> CSS property. So CSS is the key to this whole thing, eh? People, it looks like we&apos;re gonna need a stylesheet!</p><div class="markdown-heading"><h2 id="getting-stylish">Getting stylish</h2><a href="#getting-stylish" class="anchor" aria-label="Permalink: Getting stylish"><img src="assets/link.svg" /></a></div><p>Doing some clever reverse engineering of Flickr, we whip up the following stylesheet:</p><pre><code class="language-css">body {
  font-family: Proxima Nova,helvetica neue,helvetica,arial,sans-serif;
}

#album {
  box-sizing: border-box;
  margin-left: auto;
  margin-right: auto;
}

#album-header {
  align-items: center;
  background-color: #000;
  background-position: 50%;
  background-size: cover;
  color: #fff;
  display: flex;
  flex-direction: column;
  height: 300px;
  justify-content: center;
  position: relative;
  text-shadow: 0 1px 1px #000;
}

#album-header &gt; div {
  color: #ffffff;
  font-weight: 300;
  overflow: hidden;
  text-align: center;
  text-overflow: ellipsis;
  text-shadow: 0 1px 1px #000000;
}

#album-title {
  font-size: 2em;
  white-space: nowrap;
}

#album-description {
  font-size: 24px;
  font-style: italic;
  line-height: 29px;
  margin-top: 13px;
  max-height: 29px;
  word-wrap: break-word;
}

#photos {
  position: relative;
}

.photo {
  background-position: 50%;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
}
</code></pre><p>Now we need to write this to the album directory next to <code>index.html</code>. Let&apos;s drop this CSS into <code>resources/templates/style.css</code> and write an <code>album-&gt;css</code> function. Whilst <code>style.css</code> doesn&apos;t actually contain any template variables, maybe it could one day, so let&apos;s just run it through Selmer, which is basically a no-op on files not containing template variables.</p><pre><code class="language-clojure">(defn album-&gt;css [_ctx album]
  (selmer/render (slurp &quot;resources/templates/style.css&quot;)
                 {:album album}))
</code></pre><p>Hrm... this looks exactly the same as <code>album-&gt;html</code> except for the filename, so let&apos;s refactor a tiny bit:</p><pre><code class="language-clojure">(defn apply-album-template [_ctx template-file album]
  (selmer/render (slurp template-file)
                 {:album album}))

(defn album-&gt;html [ctx album]
  (apply-album-template ctx &quot;resources/templates/album.html&quot; album))

(defn album-&gt;css [ctx album]
  (apply-album-template ctx &quot;resources/templates/style.css&quot; album))
</code></pre><p>Now we just need to plug this into <code>write-album-html!</code> to write <code>style.css</code> into the album directory:</p><pre><code class="language-clojure">(defn write-album-html! [ctx {:keys [out-dir] :as album}]
  (when-not out-dir
    (throw (ex-info &quot;Album must be downloaded before writing it to HTML&quot;
                    {:album album})))
  (let [html (album-&gt;html ctx album)
        html-file (fs/file out-dir &quot;index.html&quot;)
        css (album-&gt;css ctx album)
        css-file (fs/file out-dir &quot;style.css&quot;)]
    (spit html-file html)
    (spit css-file css)
    (assoc album :html-file html-file, :css-file css-file)))
</code></pre><p>Oh yeah, and include the stylesheet in the HTML template:</p><pre><code class="language-html">&lt;head&gt;
    &lt;title&gt;{{album.title}}&lt;/title&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;
&lt;/head&gt;
</code></pre><p>Let&apos;s test this out in the REPL again:</p><pre><code class="language-clojure">(comment

  (write-album-html! ctx album)
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :title &quot;clickr demo&quot;,
  ;;     :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;     :photos (...)
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photosets.Photoset 0x2e486856 &quot;com.flickr4java.flickr.photosets.Photoset@2e486856&quot;],
  ;;     :out-dir #object[java.io.File 0x68210928 &quot;/tmp/72177720314024335&quot;],
  ;;     :html-file
  ;;     #object[java.io.File 0x4e5079c0 &quot;/tmp/72177720314024335/index.html&quot;],
  ;;     :css-file #object[java.io.File 0x334cab6a &quot;/tmp/72177720314024335/style.css&quot;]}

  )
</code></pre><p>Cool! If we now reload the browser on <code>/tmp/72177720314024335/index.html</code>, we see some stuff move around and fonts turn prettier and so on, so we&apos;ve got our styles.</p><div class="markdown-heading"><h2 id="div-and-conquer">div and conquer</h2><a href="#div-and-conquer" class="anchor" aria-label="Permalink: div and conquer"><img src="assets/link.svg" /></a></div><p>The next thing we need to do is replace our <code>&lt;img&gt;</code> tags with <code>&lt;div&gt;</code> ones. While we&apos;re at it, we might as well also use the first photo in the album as the background of the album header div, since Flickr does that and it looks pretty daggone cool!</p><pre><code class="language-html">    &lt;div id=&quot;album-header&quot; style=&quot;background-image: url(&apos;{{album.photos.0.filename}}&apos;)&quot;&gt;
        &lt;div id=&quot;back&quot;&gt;⬅ Back to albums list&lt;/div&gt;
        &lt;div id=&quot;album-header&quot;&gt;
            &lt;div id=&quot;album-title&quot;&gt;{{album.title}}&lt;/div&gt;
            &lt;div id=&quot;album-description&quot;&gt;{{album.description}}&lt;/div&gt;
        &lt;/div&gt;
        &lt;div id=&quot;photos&quot;&gt;
            {% for photo in album.photos %}
            &lt;div id=&quot;photo-{{photo.id}}&quot; class=&quot;photo&quot; style=&quot;background-image: url(&apos;{{photo.filename}}&apos;);&quot;&gt;
            &lt;/div&gt;
            {% endfor %}
        &lt;/div&gt;
    &lt;/div&gt;
</code></pre><p>If we re-render our album, however</p><pre><code class="language-clojure">(comment

  (write-album-html! ctx album)
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :title &quot;clickr demo&quot;,
  ;;     :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;     :photos (...)
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photosets.Photoset 0x2e486856 &quot;com.flickr4java.flickr.photosets.Photoset@2e486856&quot;],
  ;;     :out-dir #object[java.io.File 0x68210928 &quot;/tmp/72177720314024335&quot;],
  ;;     :html-file
  ;;     #object[java.io.File 0x4e5079c0 &quot;/tmp/72177720314024335/index.html&quot;],
  ;;     :css-file #object[java.io.File 0x334cab6a &quot;/tmp/72177720314024335/style.css&quot;]}

  )
</code></pre><p>Two things are surprising:</p><ol start="1"><li>Our first photo isn&apos;t displayed as the background of the album header div, despite the <a href="https://github.com/yogthos/Selmer?tab=readme-ov-file#variables-and-tags">Selmer
   docs</a> claiming that we can index into nested data stuctures.</li><li>Our photos have gone from being way too big to being way too small. So small, in fact, that even the world&apos;s most powerful scanning tunneling microscope could not detect them.</li></ol><p>The first point is only surprising because I forgot how Clojure works. To see why, let&apos;s try out the example from the Selmer docs for ourselves:</p><pre><code class="language-clojure">(comment

  (selmer/render &quot;{{foo.bar.0.baz}}&quot; {:foo {:bar [{&quot;baz&quot; &quot;hi&quot;}]}})
  ;; =&gt; &quot;hi&quot;

  )
</code></pre><p>OK, so <a href="https://github.com/yogthos">good ol&apos; Yogthos</a> isn&apos;t a liar, which is good, because I&apos;ve read a lot of his stuff and believed what he was saying. Having trusted and verified, let&apos;s do the same thing with our album:</p><pre><code class="language-clojure">(comment

  (selmer/render &quot;{{album.photos.0.filename}}&quot; {:album album})
  ;; =&gt; &quot;&quot;

  (-&gt; album :photos first :filename)
  ;; =&gt; &quot;53460147147.jpg&quot;

  )
</code></pre><p>What gives? He&apos;s got a vector of <code>:bar</code>s in his <code>:foo</code>, and we&apos;ve got a list of <code>:photos</code> in our <code>:album</code>, so what&apos;s the difference here? 🤔</p><p>Oh wait... I said he has a vector and we have a list. Those words are different. And not only are they different, one of them is a flat out lie! 😬</p><pre><code class="language-clojure">(comment

  (def yogthos-data {:foo {:bar [{&quot;baz&quot; &quot;hi&quot;}]}})
  ;; =&gt; #&apos;clickr.html/yogthos-data

  (type (get-in yogthos-data [:foo :bar]))
  ;; =&gt; clojure.lang.PersistentVector

  (type (:photos album))
  ;; =&gt; clojure.lang.LazySeq

  (get-in yogthos-data [:foo :bar 0 &quot;baz&quot;])
  ;; =&gt; &quot;hi&quot;

  (get-in album [:photos 0 :filename])
  ;; =&gt; nil

  )
</code></pre><p>So yeah, you can&apos;t index into a lazy sequence like you can a vector. Luckily, it&apos;s easy to turn a lazy sequence into a vector:</p><pre><code class="language-clojure">(comment

  (get-in (vec (:photos album)) [0 :filename])
  ;; =&gt; &quot;53460147147.jpg&quot;

  )
</code></pre><p>Since we&apos;ve been superDRY and extracted a function to do the templating stuff, we can make a one line change to fix this:</p><pre><code class="language-clojure">(defn apply-album-template [_ctx template-file album]
  (selmer/render (slurp template-file)
                 {:album (update album :photos vec)}))

(comment

  (write-album-html! ctx album)
  ;; =&gt; { ... }

  )

</code></pre><p>If we reload the page in our browser, we see a cool space station photo in the album header, but the second problem remains: no photos!</p><p>If we inspect one of the divs, we see what&apos;s going on pretty quickly:</p><p><img alt="The album webpage with no visible photos" src="assets/2024-01-22-oops.png" title="Wherefore art thou, dear photos?" /></p><p>All of the photo divs are 0 pixels wide by 0 pixels high. 😬</p><p>If we look back at Flickr, we see that they set a <code>width</code> and <code>height</code> style on each photo element. We can try that just to see what happens:</p><pre><code class="language-html">        &lt;div id=&quot;photos&quot;&gt;
            {% for photo in album.photos %}
            &lt;div id=&quot;photo-{{photo.id}}&quot; class=&quot;photo&quot;
                style=&quot;background-image: url(&apos;{{photo.filename}}&apos;); width: 300px; height: 180px;&quot;&gt;
            &lt;/div&gt;
            {% endfor %}
        &lt;/div&gt;
</code></pre><p>OK, now we can see some photo, by which I mean only one photo. Inspecting the page, we see that all of the divs are there and have the correct width and height, but they seem to be on top of each other. Which is less than ideal, bordering on decidedly suboptimal. 🙁</p><p><img alt="The album webpage with only one visible photo" src="assets/2024-01-22-single.png" title="Sometimes one is not enough" /></p><p>OK, so maybe that&apos;s what all of those <code>transform: translate</code> CSS incantations are about. Reading <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate">the
documentation</a>, it seems that we can do cool stuff like</p><pre><code class="language-CSS">transform: translate(10px, 20px);
</code></pre><p>to move an element 10 pixels to the right and 20 pixels down. So if we want to have a nice three column layout like Flickr&apos;s with 4 pixels between each image, we could lay things out something like this:</p><pre><code class="language-html">&lt;div style=&quot;transform: translate(0px,   4px);   ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(304px, 4px);   ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(608px, 4px);   ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(0px,   184px); ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(304px, 184px); ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(608px, 184px); ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(0px,   368px); ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(304px, 368px); ...&quot;&gt;&lt;/div&gt;
</code></pre><p><img alt="The album webpage with only one visible photo" src="assets/2024-01-22-janked.png" title="Sometimes one is not enough" /></p><p>I mean, this is... better? Except all of the photos are cropped in an odd way, and don&apos;t make use of the full width of the screen, and don&apos;t resize nicely like Flickr&apos;s do and... well, kinda suck.</p><p>It looks like we&apos;re going to need some math and stuff to dig ourselves out of this hole. 😱</p><div class="markdown-heading"><h2 id="tell-me-about-yourself">Tell me about yourself</h2><a href="#tell-me-about-yourself" class="anchor" aria-label="Permalink: Tell me about yourself"><img src="assets/link.svg" /></a></div><p>The first order of business is to figure out what the dimensions of the photos we download are. If we cast our eyes back to the data representation of a photo, we see:</p><pre><code class="language-clojure">(comment

  (-&gt; album :photos first)
  ;; =&gt; {:description nil,
  ;;     :date-taken nil,
  ;;     :geo-data nil,
  ;;     :rotation -1,
  ;;     :width 0,
  ;;     :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;     :filename &quot;53460147147.jpg&quot;,
  ;;     :id &quot;53460147147&quot;,
  ;;     :out-file
  ;;     #object[java.io.File 0x13356709 &quot;/tmp/72177720314024335/53460147147.jpg&quot;],
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photos.Photo 0x4291d927 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;     :height 0}

  )
</code></pre><p>The problem is that <code>width</code> and <code>height</code> are both 0, which is definitely not so helpful. Since Flickr won&apos;t tell us what we need to know, let&apos;s see if Java can.</p><p>Luckily, there&apos;s a <a href="https://docs.oracle.com/javase/8/docs/api/javax/imageio/ImageIO.html">javax.imageio.ImageIO</a> class that looks like it will do exactly what we need!</p><pre><code class="language-clojure">(comment

  (import &apos;(javax.imageio ImageIO))
  ;; =&gt; javax.imageio.ImageIO

  (let [img (ImageIO/read (-&gt; album :photos first :out-file))]
    {:width (.getWidth img)
     :height (.getHeight img)})
  ;; =&gt; {:width 1024, :height 576}

  )
</code></pre><p>Nice! Let&apos;s go back to our <code>clickr.flickr</code> namespace and add this to our <code>download-photo!</code> function so that we get the correct width and height for each photo. First, we need to import the <code>ImageIO</code> class:</p><pre><code class="language-clojure">(ns clickr.flickr
  (:require [babashka.fs :as fs]
            [clickr.util :as util]
            [clojure.java.io :as io]
            [clojure.string :as str])
  (:import (com.flickr4java.flickr Flickr
                                   RequestContext
                                   REST)
           (com.flickr4java.flickr.auth Permission)
           (com.flickr4java.flickr.photos Size)
           (com.flickr4java.flickr.util FileAuthStore)
           (java.io BufferedInputStream
                    FileOutputStream)
           (javax.imageio ImageIO)))
</code></pre><p>And then we can do the actual reading of the image file:</p><pre><code class="language-clojure">(defn download-photo! [{:keys [flickr out-dir] :as ctx}
                       {:keys [filename] :as photo}]
  (let [p-interface (.getPhotosInterface (:client flickr))
        out-file (fs/file out-dir filename)]
    (with-open [in (BufferedInputStream. (.getImageAsStream p-interface (:object photo) Size/LARGE))
                out (FileOutputStream. out-file)]
      (io/copy in out))
    (let [img (ImageIO/read out-file)]
      (assoc photo
             :out-file out-file
             :width (.getWidth img)
             :height (.getHeight img)))))

(comment

  (download-photo! ctx (-&gt; album :photos first))
  ;; =&gt; {:description nil,
  ;;     :date-taken nil,
  ;;     :geo-data nil,
  ;;     :rotation -1,
  ;;     :width 1024,
  ;;     :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;     :filename &quot;53460147147.jpg&quot;,
  ;;     :id &quot;53460147147&quot;,
  ;;     :out-file
  ;;     #object[java.io.File 0x7a5efcc7 &quot;/home/jmglov/Pictures/clickr/53460147147.jpg&quot;],
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photos.Photo 0x3d11130b &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;     :height 576}

  )
</code></pre><p>Lookin&apos; good!</p><p>There&apos;s just one thing that annoys me here, which is that we&apos;re always downloading the file, even if it already exists locally. Let&apos;s fix that real quick whilst we&apos;re here:</p><pre><code class="language-clojure">(defn download-photo! [{:keys [flickr out-dir] :as ctx}
                       {:keys [filename] :as photo}]
  (let [p-interface (.getPhotosInterface (:client flickr))
        out-file (fs/file out-dir filename)]
    (when-not (fs/exists? out-file)
      (with-open [in (BufferedInputStream. (.getImageAsStream p-interface (:object photo) Size/LARGE))
                  out (FileOutputStream. out-file)]
        (io/copy in out)))
    (let [img (ImageIO/read out-file)]
      (assoc photo
             :out-file out-file
             :width (.getWidth img)
             :height (.getHeight img)))))
</code></pre><p>OK, now that we know the dimensions of each photo, what do we do with that? I guess we could extend our template to add the width and height and translate stuff, then do some calculations on the photos and write it to the HTML...</p><pre><code class="language-html">        &lt;div id=&quot;photos&quot;&gt;
            {% for photo in album.photos %}
            &lt;div id=&quot;photo-{{photo.id}}&quot; class=&quot;photo&quot;
                style=&quot;background-image: url(&apos;{{photo.filename}}&apos;); width: {{photo.width}}px; height: {{photo.height}}px; transform: translate({{photo.offset-x}}px, {{photo.offset-y}}px);&quot;&gt;
            &lt;/div&gt;
            {% endfor %}
        &lt;/div&gt;
</code></pre><p>But this seems kinda yucky. Also we have no way of knowing how wide the browser window will be, so we can&apos;t make good use of the space, and we can&apos;t dynamically resize when the browser window is resized, and so on and so forth. 😢</p><p>My friends, I&apos;m afraid we&apos;re going to have to resort to JavaScript! 😱</p><p>But wait... this is a Clojure blog (sort of), and we Clojurians have a secret weapon!</p><p><img alt="A photo of David Nolen and Mike Fikes with a ClojureScript logo" src="assets/2024-01-22-clojurescript.png" title="Nolen and Fikes rock, ClojureScript reaches!" /></p><div class="markdown-heading"><h2 id="mellon-collie-and-the-infinite-sadness-of-getting-clojurescript-to-build">Mellon Collie and the Infinite Sadness of getting ClojureScript to build</h2><a href="#mellon-collie-and-the-infinite-sadness-of-getting-clojurescript-to-build" class="anchor" aria-label="Permalink: Mellon Collie and the Infinite Sadness of getting ClojureScript to build"><img src="assets/link.svg" /></a></div><p>The only problem with ClojureScript is that it transpiles to JavaScript, which means you need to somehow get that JavaScript built and then stick it somewhere the browser can find it and OMG that smacks of effort!</p><p>We have lovely tools such as <a href="https://github.com/thheller/shadow-cljs">shadow-cljs</a> which turn the infinite sadness into finite sadness, but I&apos;m going to go on record as not being too happy about sadness (though sadness has a part to play in the human experience, so maybe I should be happy about that?), so am I SOL (er, Sorta Outta Luck?) at this point?</p><p>Of course not, because we Clojurians have more than one secret weapon!</p><p><img alt="A photo of Michiel Borkent AKA borkdude saying &apos;Can I get a borkdude?&apos;" src="assets/2024-01-22-borkdude.png" title="Get borked, man!" /></p><p>A friend and were discussing borkdude&apos;s prodigious output one day, and one of us made the observation that there was something Unix-y about his stuff, that he provided a bunch of basic pieces that could be combined to do pretty much whatever you need to do, but without sucking in all of Maven Central as transitive dependencies. I don&apos;t know if this is a great comparison, or if borkdude himself would agree, but hey! this is my blog, and borkdude can write a polemic about how much I suck on his own blog if he wants to.</p><p>Anyway.</p><p>One of the most amazing things borkdude provideth is this thing called <a href="https://github.com/babashka/scittle/">Scittle</a>, which allows you to &quot;execute Clojure(Script) directly from browser script tags via SCI&quot;. This is an absolute game changer for lazy programmers like me, or even non-lazy programmers unlike me who want to put some ClojureScript on a page but aren&apos;t setting out to build complex Single Page Apps.</p><p>So let&apos;s drop a scittle in our <code>&lt;head&gt;</code> and get to ClojureScripting!</p><pre><code class="language-html">&lt;head&gt;
    &lt;title&gt;{{album.title}}&lt;/title&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta http-equiv=&quot;x-ua-compatible&quot; content=&quot;ie=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;

    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
</code></pre><p>With this one little line, I now have the full power of ClojureScript at my disposal! I can now solve problems like knowing how wide my window is:</p><pre><code class="language-html">&lt;head&gt;
    &lt;!-- ... --&gt;

    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;application/x-scittle&quot;&gt;
      (println (str &quot;Window width: &quot; (.-innerWidth js/window) &quot;px&quot;))
    &lt;/script&gt;
&lt;/head&gt;
</code></pre><p>Having dropped this into my <code>resources/templates/album.html</code>, if I <code>write-album-html!</code> again, reload my browser, and take a look at the JavaScript console, wondrous sights fill my eyes:</p><p><img alt="The album webpage, displaying &apos;Window width: 1362px&apos; in the JavaScript console" src="assets/2024-01-22-width.png" title="Behold the wonder of Scittle!" /></p><p>Of course, ClojureScript without a REPL is like a lovely bowl of mango sorbet without a spoon, so let&apos;s visit the <a href="https://github.com/babashka/scittle/tree/main/doc/nrepl">Scittle
docs</a> and get ourselves a lovely silver spoon!</p><p>According to that page, all I need to do is drop the following into my HTML file:</p><pre><code class="language-html">&lt;head&gt;
    &lt;!-- ... --&gt;

    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.js&quot; type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script&gt;var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.nrepl.js&quot;
        type=&quot;application/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;application/x-scittle&quot; src=&quot;album.cljs&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
</code></pre><p>Then I can pop an <code>album.cljs</code> right next to my <code>index.html</code> and win!</p><p>Let&apos;s try this out. I&apos;ll create a basic <code>resources/templates/album.cljs</code>:</p><pre><code class="language-clojure">(ns album)

(defn print-window-width []
  (println (str &quot;Window width: &quot; (.-innerWidth js/window) &quot;px&quot;)))
</code></pre><p>And back in my <code>src/clickr/html.clj</code>, write it to the output dir along with the other files:</p><pre><code class="language-clojure">(defn write-album-html! [ctx {:keys [out-dir] :as album}]
  (when-not out-dir
    (throw (ex-info &quot;Album must be downloaded before writing it to HTML&quot;
                    {:album album})))
  (let [html (album-&gt;html ctx album)
        html-file (fs/file out-dir &quot;index.html&quot;)
        css (album-&gt;css ctx album)
        css-file (fs/file out-dir &quot;style.css&quot;)
        cljs (apply-album-template ctx &quot;resources/templates/album.cljs&quot; album)
        cljs-file (fs/file out-dir &quot;album.cljs&quot;)]
    (spit html-file html)
    (spit css-file css)
    (spit cljs-file cljs)
    (assoc album :html-file html-file, :css-file css-file, :cljs-file cljs-file)))

(comment

  (write-album-html! ctx album)
  ;; =&gt; { ... }

  )
</code></pre><p>But when we reload our page, we get some gross stuff about <code>DOMException</code>s and <code>CORS</code> and other things that make us go &quot;hmm?&quot;.</p><pre><code class="language-text">scittle.nrepl.js:18 Uncaught DOMException: Failed to construct &apos;WebSocket&apos;: The URL &apos;ws://:1340/_nrepl&apos; is invalid.
    at https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.nrepl.js:18:158
    at https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.nrepl.js:20:4
index.html:1 Access to XMLHttpRequest at &apos;file:///tmp/72177720314024335/album.cljs&apos; from origin &apos;null&apos; has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, isolated-app, brave, https, chrome-untrusted, data, chrome-extension, chrome.
scittle.js:1881 GET file:///tmp/72177720314024335/album.cljs net::ERR_FAILED
</code></pre><p>This is the opposite of fun. <code>(complement fun)</code>, if you will. It looks like we&apos;re going to need an actual webserver to continue here. Luckily, if we but read a tiny bit further in <code>scittle/doc/nrepl/README.md</code>, it seems that we can have a webserver quite easily:</p><blockquote><p>When you run bb dev in this directory, and then open <a href="http://localhost:1341">http://localhost:1341</a> you should be able evaluate expressions in playground.cljs. See a demo here.</p><p>Note that the nREPL server connection stays alive even after the browser window refreshes.</p></blockquote><p>So if we grab the <a href="https://github.com/babashka/scittle/blob/main/doc/nrepl/bb.edn">bb.edn</a> from here and drop it in our <code>resources/templates/</code> directory, and add it to our ever-expanding <code>write-album-html!</code> function...</p><pre><code class="language-clojure">(defn write-album-html! [ctx {:keys [out-dir] :as album}]
  (when-not out-dir
    (throw (ex-info &quot;Album must be downloaded before writing it to HTML&quot;
                    {:album album})))
  (let [html (album-&gt;html ctx album)
        html-file (fs/file out-dir &quot;index.html&quot;)
        css (album-&gt;css ctx album)
        css-file (fs/file out-dir &quot;style.css&quot;)
        cljs (apply-album-template ctx &quot;resources/templates/album.cljs&quot; album)
        cljs-file (fs/file out-dir &quot;album.cljs&quot;)
        bb-edn (apply-album-template ctx &quot;resources/templates/bb.edn&quot; album)
        bb-edn-file (fs/file out-dir &quot;bb.edn&quot;)]
    (spit html-file html)
    (spit css-file css)
    (spit cljs-file cljs)
    (spit bb-edn-file bb-edn)
    (assoc album :html-file html-file, :css-file css-file
           :cljs-file cljs-file, :bb-edn-file bb-edn-file)))

(comment

  (write-album-html! ctx album)
  ;; =&gt; { ... }

  )
</code></pre><p>Now we can pop over to <code>/tmp/72177720314024335/</code> and fire up Babashka:</p><pre><code class="language-text">: jmglov@laurana; cd /tmp/72177720314024335/
: jmglov@laurana; bb dev
Serving static assets at http://localhost:1341
nREPL server started on port 1339...
Websocket server started on 1340...
</code></pre><p>and then load up <a href="http://localhost:1341/">http://localhost:1341/</a> in our web browser, open up <code>/tmp/72177720314024335/album.cljs</code> in Emacs, run <code>cider-connect-cljs</code>, select <code>localhost</code> then port <code>1339</code>, select <code>nbb</code> as the ClojureScript REPL type, maybe hit <code>C-g</code> a few times if we see something like</p><pre><code class="language-text">Fri Jan 19 09:03:52 CET 2024 [worker-3] ERROR - handle websocket frame org.httpkit.server.Frame$TextFrame@1de1c580
java.lang.RuntimeException: No reader function for tag object
        at clojure.lang.EdnReader$TaggedReader.readTagged(EdnReader.java:801)
        at clojure.lang.EdnReader$TaggedReader.invoke(EdnReader.java:783)
        [...]
</code></pre><p>in the terminal where we&apos;re running <code>bb dev</code> (there&apos;s a <a href="https://clojurians.slack.com/archives/C034FQN490E/p1703238977455889">whole
thread</a> over on Clojurians Slack about this where borkdude and Benjamin fixed this, but I switched laptops since then—a long story for another time—and it came back, but it doesn&apos;t hurt anything, so I just carried on with my disgusting workaround), and then whack <code>C-c C-k</code> (your keybindings may vary, of course, so it&apos;s <code>cider-load-buffer</code> you want) and drop a <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a> in the file</p><pre><code class="language-clojure">(comment

  (print-window-width)
  ;; =&gt; nil

  )
</code></pre><p>and then <code>C-c C-v f c e</code> (<code>cider-pprint-eval-last-sexp-to-comment</code>) and finally pop a bottle of emoji! 🥂</p><p><img alt="The album webpage, displaying &apos;Window width: 1362px&apos; in the JavaScript console" src="assets/2024-01-22-repl.png" title="Now we&apos;re cooking with REPL!" /></p><p>OK, so let&apos;s take stock of what we&apos;ve done here. We now have a webpage which loads Scittle which in turn loads our shiny new <code>album.cljs</code>, which we can load in our web browser by virtue of a Babashka webserver configured by the <code>bb.edn</code> we dropped in the album dir, and oh by the way, we can connect a REPL to it and cause stuff to happen. That&apos;s something we can now build a Flickr clone on!</p><div class="markdown-heading"><h2 id="sizing-things-up">Sizing things up</h2><a href="#sizing-things-up" class="anchor" aria-label="Permalink: Sizing things up"><img src="assets/link.svg" /></a></div><p>Let&apos;s make a few design decisions about how the album should look. And by &quot;make design decisions&quot;, I mean &quot;rip design decisions off from Flickr&quot;. Here&apos;s what we want:</p><ol start="1"><li>If the browser window is reasonably wide, the album should be 80% the width of the window</li><li>If the browser window is reasonably wide, display 3 photos per row</li><li>All rows should be the same width as the album header</li><li>All photos in a row should be scaled to the same height</li><li>As the window is resized, photos should be rescaled to fit nicely</li><li>If the window is too small to display three photos per row, display two per row instead, and expand the album to fill the width of the window</li><li>If the window is too small to display two photos per row, display one per row instead</li></ol><p>Let&apos;s start off by just assuming the window is reasonably wide and seeing if we can&apos;t get the photos displayed three to a row, with the row being the same width as the album header and all photos in each row being the same size.</p><p>The first order of business is to expose the photos metadata to ClojureScript. Thanks to our decision to run all of our resource files through Selmer, this turns out to be a one-liner in <code>album.cljs</code>:</p><pre><code class="language-clojure">(ns album)

(def photos {{photos-edn | safe}})
</code></pre><p>Of course, that <code>photos-edn</code> has to come from somewhere, so let&apos;s pop into our <code>clickr.html</code> namespace and turn our photos datastructure into some EDN:</p><pre><code class="language-clojure">(comment

  (def album (-&gt;&gt; (flickr/get-albums ctx)
                  first
                  (flickr/download-album! ctx)))
  ;; =&gt; #&apos;clickr.html/album

  (with-out-str
    (prn (:photos album)))
  ;; =&gt; &quot;({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title \&quot;sean-hargreaves-phoenix-new-5-final-a\&quot;, :filename \&quot;53460147147.jpg\&quot;, :id \&quot;53460147147\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x11aef77d \&quot;com.flickr4java.flickr.photos.Photo@14ea992b\&quot;], :height 576} {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title \&quot;patryk-urbaniak-for-all-mankind-004\&quot;, :filename \&quot;53461405604.jpg\&quot;, :id \&quot;53461405604\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x63127ec5 \&quot;com.flickr4java.flickr.photos.Photo@22e889e0\&quot;], :height 576} {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title \&quot;jared-michael-forallmankind-011\&quot;, :filename \&quot;53461091151.jpg\&quot;, :id \&quot;53461091151\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x46c7dec8 \&quot;com.flickr4java.flickr.photos.Photo@33f7f318\&quot;], :height 512} {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title \&quot;sean-hargreaves-transport-ship-new-final-1b\&quot;, :filename \&quot;53461088046.jpg\&quot;, :id \&quot;53461088046\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x25078237 \&quot;com.flickr4java.flickr.photos.Photo@88e20c4f\&quot;], :height 576} {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title \&quot;sean-hargreaves-057-asteroid-mining-ship-platformcables-1b-sh-2022-7-08\&quot;, :filename \&quot;53460163402.jpg\&quot;, :id \&quot;53460163402\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x43748cf5 \&quot;com.flickr4java.flickr.photos.Photo@451d67cd\&quot;], :height 576} {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 722, :title \&quot;jean-luc-sabourin-fam-season-2-soviet-notext\&quot;, :filename \&quot;53460161007.jpg\&quot;, :id \&quot;53460161007\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x33e03608 \&quot;com.flickr4java.flickr.photos.Photo@c948c4a2\&quot;], :height 1023} {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 666, :title \&quot;trung-doan-mankind\&quot;, :filename \&quot;53461214223.jpg\&quot;, :id \&quot;53461214223\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x4b299f22 \&quot;com.flickr4java.flickr.photos.Photo@1a270f5c\&quot;], :height 1000} {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1023, :title \&quot;daniel-jennings-img-7554\&quot;, :filename \&quot;53460151727.jpg\&quot;, :id \&quot;53460151727\&quot;, :object #object[com.flickr4java.flickr.photos.Photo 0x5226aa4a \&quot;com.flickr4java.flickr.photos.Photo@436e36e8\&quot;], :height 299})\n&quot;

  )
</code></pre><p>OK, that technically worked, but... gross! It would be much nicer if this mess was human readable in some way. Luckily for us, Rich Hickey provideth, in the form of <a href="https://clojuredocs.org/clojure.pprint/pprint">clojure.pprint/pprint</a>. Let&apos;s just swap that in for <code>prn</code> and see how it goes:</p><pre><code class="language-clojure">
(comment

  (require &apos;[clojure.pprint :as pprint])
  ;; =&gt; nil

  (with-out-str
    (pprint/pprint (:photos album)))
  ;; =&gt; &quot;({:description nil,\n  :date-taken nil,\n  :geo-data nil,\n  :rotation -1,\n  :width 1024,\n  :title \&quot;sean-hargreaves-phoenix-new-5-final-a\&quot;,\n  :filename \&quot;53460147147.jpg\&quot;,\n  :id \&quot;53460147147\&quot;,\n  :object\n  #object[com.flickr4java.flickr.photos.Photo 0x11aef77d \&quot;com.flickr4java.flickr.photos.Photo@14ea992b\&quot;],\n  :height 576}\n ... {:description nil,\n  :date-taken nil,\n  :geo-data nil,\n  :rotation -1,\n  :width 1023,\n  :title \&quot;daniel-jennings-img-7554\&quot;,\n  :filename \&quot;53460151727.jpg\&quot;,\n  :id \&quot;53460151727\&quot;,\n  :object\n  #object[com.flickr4java.flickr.photos.Photo 0x5226aa4a \&quot;com.flickr4java.flickr.photos.Photo@436e36e8\&quot;],\n  :height 299})\n&quot;

  )
</code></pre><p>OK, that still looks silly in my REPL, but if I print it, I get:</p><pre><code class="language-clojure">({:description nil,
  :date-taken nil,
  :geo-data nil,
  :rotation -1,
  :width 1024,
  :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  :filename &quot;53460147147.jpg&quot;,
  :id &quot;53460147147&quot;,
  :out-file
  #object[java.io.File 0x13356709 &quot;/tmp/72177720314024335/53460147147.jpg&quot;],
  :object
  #object[com.flickr4java.flickr.photos.Photo 0x4291d927 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  :height 576}
 {:description nil,
  :date-taken nil,
  :geo-data nil,
  :rotation -1,
  :width 1024,
  :title &quot;patryk-urbaniak-for-all-mankind-004&quot;,
  :filename &quot;53461405604.jpg&quot;,
  :id &quot;53461405604&quot;,
  :out-file
  #object[java.io.File 0x17191ef4 &quot;/tmp/72177720314024335/53461405604.jpg&quot;],
  :object
  #object[com.flickr4java.flickr.photos.Photo 0xb886372 &quot;com.flickr4java.flickr.photos.Photo@22e889e0&quot;],
  :height 576}
 ;; ...
 )
</code></pre><p>This is better, in that it can be read by a human. Let&apos;s make sure that it can be read by a machine, though:</p><pre><code class="language-clojure">(comment

  (require &apos;[clojure.edn :as edn])
  ;; =&gt; nil

  (-&gt; (with-out-str
        (pprint/pprint (:photos album)))
      edn/read-string)
  ;; =&gt; Execution error at clickr.html/eval27054 (REPL:243).
  ;;    No reader function for tag object

  )
</code></pre><p>Oopsy! I think those <code>#object</code> literals are causing trouble. No worries, we can just dissoc them:</p><pre><code class="language-clojure">(comment

  (-&gt; (with-out-str
        (pprint/pprint (-&gt; album
                           :photos
                           (map #(dissoc % :out-file :object)))))
      edn/read-string)
  ;; =&gt; Execution error (IllegalArgumentException) at clickr.html/eval27066$fn (REPL:241).
  ;;    Don&apos;t know how to create ISeq from: clickr.html$eval27066$fn__27067$fn__27068

  )
</code></pre><p>Arg! Looks like the reader is having trouble with that lazy sequence. Sounds familiar, eh? 🙄 Let&apos;s turn it into a vector:</p><pre><code class="language-clojure">
(comment

  (-&gt; (with-out-str
        (pprint/pprint (-&gt;&gt; album
                            :photos
                            (map #(dissoc % :out-file :object))
                            vec)))
      edn/read-string)
  ;; =&gt; [{:description nil,
  ;;      :date-taken nil,
  ;;      :geo-data nil,
  ;;      :rotation -1,
  ;;      :width 1024,
  ;;      :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;      :filename &quot;53460147147.jpg&quot;,
  ;;      :id &quot;53460147147&quot;,
  ;;      :height 576}
  ;;     [...]
  ;;     {:description nil,
  ;;      :date-taken nil,
  ;;      :geo-data nil,
  ;;      :rotation -1,
  ;;      :width 1023,
  ;;      :title &quot;daniel-jennings-img-7554&quot;,
  ;;      :filename &quot;53460151727.jpg&quot;,
  ;;      :id &quot;53460151727&quot;,
  ;;      :height 299}]

  )
</code></pre><p>Nice, now we can round-trip our EDN, so let&apos;s plug this into the CLJS template.</p><pre><code class="language-clojure">(ns clickr.html
  (:require [babashka.fs :as fs]
            [selmer.parser :as selmer]
            [clojure.pprint :as pprint]))

(defn -&gt;edn [data]
  (with-out-str (pprint/pprint data)))

(defn apply-album-template [_ctx template-file album]
  (selmer/render (slurp template-file)
                 {:album (update album :photos vec)
                  :photos-edn (-&gt;&gt; album
                                   :photos
                                   (map #(dissoc % :out-file :object))
                                   vec
                                   -&gt;edn)}))

(comment

  (write-album-html! ctx album)
  ;; =&gt; { ... }

  )
</code></pre><p>If we take a look at the resulting <code>/tmp/72177720314024335/album.cljs</code>, we see that by golly do we ever have photos!</p><pre><code class="language-clojure">(ns album)

(def photos [{:description nil,
  :date-taken nil,
  :geo-data nil,
  :rotation -1,
  :width 0,
  :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  :filename &quot;53460147147.jpg&quot;,
  :id &quot;53460147147&quot;,
  :height 0}
 ;; [...]
 {:description nil,
  :date-taken nil,
  :geo-data nil,
  :rotation -1,
  :width 0,
  :title &quot;daniel-jennings-img-7554&quot;,
  :filename &quot;53460151727.jpg&quot;,
  :id &quot;53460151727&quot;,
  :height 0}]
)
</code></pre><p>Let&apos;s open up <code>/tmp/72177720314024335/album.cljs</code> directly in Emacs so we can continue our REPL-driven development without the need to keep evaluating <code>write-album-html!</code>. We&apos;ll start out by reloading the browser to make sure it&apos;s picking up the latest <code>album.cljs</code>. This should be the last time we&apos;ll need to reload the page, unless something goes wrong. Next, let&apos;s evaluate the entire buffer (<code>C-c C-k</code> or <code>cider-load-buffer</code> or however you do stuff in your editor), and finally make sure all is good with our REPL connection:</p><pre><code class="language-clojure">(comment

  (println &quot;OK, I&apos;m reloaded!&quot;)
  ;; =&gt; nil

  )
</code></pre><p>Opening up the JavaScript console in our browser, we see the message we printed out, so all is good there. Time to get to actually computing stuff and things!</p><p>Our first rule was:</p><p><strong>1. If the browser window is reasonably wide, the album should be 80% the width of the window</strong></p><p>Let&apos;s add a function to get the current window width:</p><pre><code class="language-clojure">(defn get-window-width []
  (.-innerWidth js/window))

(comment

  (get-window-width)
  ;; =&gt; 1513

  )
</code></pre><p>Great! Now let&apos;s define what we mean by &quot;reasonably wide&quot;. We want to display 3 photos side by side, and having them be 300 pixels wide seems like a good size. Then we&apos;re going to need 4 pixels of padding between each photo, so that adds up to 908 pixels. This is the width of the album div, though, and it will need to fit into 80% of the window width, meaning that the window needs to be... um, some number of pixels wide?</p><p>OK, instead of dividing by 0.8, let&apos;s actually write our code with the album div in mind instead of the window width. We can encode all of these rules in some nice Clojure data:</p><pre><code class="language-clojure">(def config
  {:album-min-width 900
   :album-width-pct 0.8
   :num-photos-per-row 3
   :photo-padding 4})
</code></pre><p>Now let&apos;s write a function that computes the width of the album div based on all those computations that I was trying to do in my head:</p><pre><code class="language-clojure">(defn provisional-album-width [{:keys [album-width-pct] :as config}]
  (* (get-window-width) album-width-pct))

(comment

  (provisional-album-width config)
  ;; =&gt; 1210.4

  )
</code></pre><p>Cool, so at the current window width, the album is wide enough. Let&apos;s now set the width to that provisional width. This requires us to know the name of the album div so we can grab it from the DOM, so let&apos;s add that to our config:</p><pre><code class="language-clojure">(def config
  {:album-div-name &quot;album&quot;
   :album-min-width 900
   :album-width-pct 0.8
   :num-photos-per-row 3
   :photo-padding 4})

(comment

  (.getElementById js/document (:album-div-name config))
  ;; =&gt; #object[HTMLDivElement [object HTMLDivElement]]

  )
</code></pre><p>Looks promising! To set the width of that div, we need to set a style property on it:</p><pre><code class="language-clojure">(comment

  (-&gt; (.getElementById js/document (:album-div-name config))
      .-style
      (.setProperty &quot;width&quot; &quot;1210.4px&quot;))
  ;; =&gt; nil

  )
</code></pre><p>As soon as we evaluate this in the REPL, the div resizes live in our browser window! 🤯</p><p><img alt="The album webpage with the album div 80% of the window width" src="assets/2024-01-22-pctwidth.png" title="Such REPL driving!" /></p><p>Now that we&apos;ve figured out all the pieces, let&apos;s write a function that sets the album width:</p><pre><code class="language-clojure">(defn set-album-width!
  &quot;Sets the width of the album div based on the current window size and returns
   the new size of the album div.&quot;
  [{:keys [album-div-name album-min-width num-photos-per-row photo-padding]
    :as config}]
  (let [provisional-width (provisional-album-width config)
        padding-width (* photo-padding (dec num-photos-per-row))
        min-width (+ album-min-width padding-width)
        new-width (if (&gt;= provisional-width min-width)
                    provisional-width
                    (* (get-window-width) 0.95))]
    (-&gt; (.getElementById js/document album-div-name)
        .-style
        (.setProperty &quot;width&quot; (str new-width &quot;px&quot;)))
    new-width))

(comment

  (set-album-width! config)
  ;; =&gt; 1210.4

  )
</code></pre><p>The div has resized again, this time to 80% of the window width! 🎉</p><div class="markdown-heading"><h2 id="scaling-photos-is-easier-than-scaling-everest,-right?">Scaling photos is easier than scaling Everest, right?</h2><a href="#scaling-photos-is-easier-than-scaling-everest,-right?" class="anchor" aria-label="Permalink: Scaling photos is easier than scaling Everest, right?"><img src="assets/link.svg" /></a></div><p>Let&apos;s have a look at our next rule:</p><p><strong>2. If the browser window is reasonably wide, display 3 photos per row</strong></p><p>Splitting the photos into rows is quite straightforward:</p><pre><code class="language-clojure">(comment

  (partition-all 3 photos)
  ;; =&gt; (({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;, :filename &quot;53460147147.jpg&quot;, :id &quot;53460147147&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title &quot;patryk-urbaniak-for-all-mankind-004&quot;, :filename &quot;53461405604.jpg&quot;, :id &quot;53461405604&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title &quot;jared-michael-forallmankind-011&quot;, :filename &quot;53461091151.jpg&quot;, :id &quot;53461091151&quot;, :height 512})
  ;;     ({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title &quot;sean-hargreaves-transport-ship-new-final-1b&quot;, :filename &quot;53461088046.jpg&quot;, :id &quot;53461088046&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1024, :title &quot;sean-hargreaves-057-asteroid-mining-ship-platformcables-1b-sh-2022-7-08&quot;, :filename &quot;53460163402.jpg&quot;, :id &quot;53460163402&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 722, :title &quot;jean-luc-sabourin-fam-season-2-soviet-notext&quot;, :filename &quot;53460161007.jpg&quot;, :id &quot;53460161007&quot;, :height 1023})
  ;;     ({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 666, :title &quot;trung-doan-mankind&quot;, :filename &quot;53461214223.jpg&quot;, :id &quot;53461214223&quot;, :height 1000}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 1023, :title &quot;daniel-jennings-img-7554&quot;, :filename &quot;53460151727.jpg&quot;, :id &quot;53460151727&quot;, :height 299}))

  )
</code></pre><p>Moving on to the next rule:</p><p><strong>3. All rows should be the same width as the album header</strong></p><p>The width of a row is the width of the photos in the row plus the padding between them, so given the width of a row and the number of photos in it, we can figure out how wide each photo should be like so:</p><pre><code class="language-clojure">(comment

  (let [row-width (set-album-width! config)
        padding-width (* (dec (:num-photos-per-row config))
                         (:photo-padding config))]
    (-&gt; row-width
        (- padding-width)
        (/ (:num-photos-per-row config))))
  ;; =&gt; 400.8

  )
</code></pre><p>Now we can scale the photos like this:</p><pre><code class="language-clojure">(defn scale-photos [_config target-width photos]
  (map #(assoc % :width target-width) photos))

(comment

  (-&gt;&gt; photos
       (scale-photos config 400.8)
       (map :width))
  ;; =&gt; (400.8 400.8 400.8 400.8 400.8 400.8 400.8 400.8)

  )
</code></pre><p>Let&apos;s write a function that updates the styles of the div corresponding to a specific photo:</p><pre><code class="language-clojure">(defn set-photo-styles! [_config {:keys [id width height] :as photo}]
  (let [div-id (str &quot;photo-&quot; id)]
    (doto (-&gt; (.getElementById js/document div-id) -style)
      (.setProperty &quot;width&quot; (str width &quot;px&quot;))
      (.setProperty &quot;height&quot; (str height &quot;px&quot;)))
    photo))

(comment

  (-&gt;&gt; photos
       (scale-photos config 400.8)
       (map (partial set-photo-styles! config)))
  ;; =&gt; ({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;, :filename &quot;53460147147.jpg&quot;, :id &quot;53460147147&quot;, :height 576} ... )

  )
</code></pre><p>OK, this is progress. We&apos;ve successfully set the width of all photo divs:</p><p><img alt="The album webpage with all photos set to 400.8 pixels width" src="assets/2024-01-22-scaled.png" title="Don&apos;t let perfect be the enemy of wrong" /></p><p>The next step is to use the <code>transform: translate()</code> stuff we learned about earlier to arrange the photos how we want them. Given our desired width of 400.8 pixels and height of 576 pixels (the height of the first photo, which must be the height of all the photos, right?), we want something like this:</p><pre><code class="language-html">&lt;div style=&quot;transform: translate(0px,     4px);    ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(404.8px, 4px);    ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(809.6px, 4px);    ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(0px,     580px);  ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(404.8px, 580px);  ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(809.6px, 580px);  ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(0px,     1160px); ...&quot;&gt;&lt;/div&gt;
&lt;div style=&quot;transform: translate(404.8px, 1160px); ...&quot;&gt;&lt;/div&gt;
</code></pre><p>Let&apos;s see if we can figure out how to make this happen, starting with a single row. To make it easier to see what&apos;s going on, let&apos;s hide all the photos not in the first row:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (drop 3)
       (map (fn [{:keys [id width height] :as photo}]
              (let [div-id (str &quot;photo-&quot; id)]
                (-&gt; (.getElementById js/document div-id)
                    .-style
                    (.setProperty &quot;display&quot; &quot;none&quot;)))))
       doall)
  ;; =&gt; (nil nil nil nil nil)

  )
</code></pre><p>Having done this, let&apos;s update our <code>set-photo-styles!</code> function to set the <code>transform</code> CSS property based on the <code>:x-offset</code> and <code>:y-offset</code> keys of a photo:</p><pre><code class="language-clojure">(defn set-photo-styles!
  [_config {:keys [id width height x-offset y-offset] :as photo}]
  (let [div-id (str &quot;photo-&quot; id)
        transform (str &quot;translate(&quot; x-offset &quot;px, &quot; y-offset &quot;px)&quot;)]
    (doto (-&gt; (.getElementById js/document div-id) .-style)
      (.setProperty &quot;width&quot; (str width &quot;px&quot;))
      (.setProperty &quot;height&quot; (str height &quot;px&quot;))
      (.setProperty &quot;transform&quot; transform))
    photo))

(comment

  (let [[p1 p2 p3 &amp; _] (scale-photos config 400.8 photos)]
    (set-photo-styles! config (assoc p1 :x-offset 0, :y-offset 4))
    (set-photo-styles! config (assoc p2 :x-offset 404.8, :y-offset 4))
    (set-photo-styles! config (assoc p3 :x-offset 809.6, :y-offset 4)))
  ;; =&gt; {:description nil, :date-taken nil, :geo-data nil, :y-offset 4, :rotation -1, :width 400.8, :title &quot;jared-michael-forallmankind-011&quot;, :filename &quot;53461091151.jpg&quot;, :id &quot;53461091151&quot;, :height 512, :x-offset 809.6}

  )
</code></pre><p>We cheated a bit there, but the results look good:</p><p><img alt="The album webpage with the first row laid out correctly" src="assets/2024-01-22-manual.png" title="Don&apos;t underestimate the power of hard-coding!" /></p><p>Let&apos;s see if we can do this without hard-coding all the things. We basically want to set the x-offset of each photo to the x-offset of the previous photo, plus the width of the previous photo, plus the padding, so we need a function like <code>map</code>, except that it remembers stuff from the previous item being mapped over. There is of course a function like that: <a href="https://clojuredocs.org/clojure.core/reduce">reduce</a>. Let&apos;s try it out:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (scale-photos config 400.8)
       (take 3)
       (reduce (fn [{:keys [x-offset] :as acc} {:keys [width] :as photo}]
                 (let [new-x-offset (+ x-offset width (:photo-padding config))]
                   (-&gt; acc
                       (assoc :x-offset new-x-offset)
                       (update :arranged conj (assoc photo :x-offset x-offset)))))
               {:x-offset 0, :arranged []})
       :arranged
       (map (partial set-photo-styles! config))
       (map :x-offset))
  ;; =&gt; (0 404.8 809.6)

  )
</code></pre><p>What we&apos;re doing here is computing the x-offset for the next photo in row as we iterate over the photos, then setting the x-offset of the current photo to the previously computed x-offset and appending it to the vector of arranged photos. We can see that it worked since the x-offsets of each photo are the same as we computed by hand above, and when we fed the row to <code>set-photo-styles!</code>, nothing moved in the browser! 🎉</p><p>Let&apos;s give this function a name to make it a little less mysterious:</p><pre><code class="language-clojure">(defn arrange-row [{:keys [photo-padding] :as config} photos]
  (-&gt;&gt; photos
       (reduce (fn [{:keys [x-offset] :as acc} {:keys [width] :as photo}]
                 (let [new-x-offset (+ x-offset width photo-padding)]
                   (-&gt; acc
                       (assoc :x-offset new-x-offset)
                       (update :arranged conj (assoc photo :x-offset x-offset)))))
               {:x-offset 0, :arranged []})
       :arranged))

(comment

  (-&gt;&gt; photos
       (scale-photos config 400.8)
       (take 3)
       (arrange-row config)
       (map (partial set-photo-styles! config))
       (map :x-offset))
  ;; =&gt; (0 404.8 809.6)

  )
</code></pre><p>Much better!</p><div class="markdown-heading"><h2 id="getting-down-2d">Getting down 2D</h2><a href="#getting-down-2d" class="anchor" aria-label="Permalink: Getting down 2D"><img src="assets/link.svg" /></a></div><p>Now that we&apos;ve dealt with a single row, let&apos;s see if we can apply the same strategy to the y-offset for all rows. But first, let&apos;s make all the photos visible again:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (drop 3)
       (map (fn [{:keys [id width height] :as photo}]
              (let [div-id (str &quot;photo-&quot; id)]
                (-&gt; (.getElementById js/document div-id)
                    .-style
                    (.removeProperty &quot;display&quot;)))))
       doall)
  ;; =&gt; (&quot;none&quot; &quot;none&quot; &quot;none&quot; &quot;none&quot; &quot;none&quot;)

  )
</code></pre><p>We want to start by scaling the photos to our desired width and then partitioning them into rows:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (scale-photos config 400.8)
       (partition-all 3))
  ;; =&gt; (({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;, :filename &quot;53460147147.jpg&quot;, :id &quot;53460147147&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;patryk-urbaniak-for-all-mankind-004&quot;, :filename &quot;53461405604.jpg&quot;, :id &quot;53461405604&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;jared-michael-forallmankind-011&quot;, :filename &quot;53461091151.jpg&quot;, :id &quot;53461091151&quot;, :height 512})
  ;;     ({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;sean-hargreaves-transport-ship-new-final-1b&quot;, :filename &quot;53461088046.jpg&quot;, :id &quot;53461088046&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;sean-hargreaves-057-asteroid-mining-ship-platformcables-1b-sh-2022-7-08&quot;, :filename &quot;53460163402.jpg&quot;, :id &quot;53460163402&quot;, :height 576}
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;jean-luc-sabourin-fam-season-2-soviet-notext&quot;, :filename &quot;53460161007.jpg&quot;, :id &quot;53460161007&quot;, :height 1023})
  ;;     ({:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;trung-doan-mankind&quot;, :filename &quot;53461214223.jpg&quot;, :id &quot;53461214223&quot;, :height 1000} 
  ;;      {:description nil, :date-taken nil, :geo-data nil, :rotation -1, :width 400.8, :title &quot;daniel-jennings-img-7554&quot;, :filename &quot;53460151727.jpg&quot;, :id &quot;53460151727&quot;, :height 299}))

  )
</code></pre><p>Having done that, we can <code>reduce</code> over the rows, calculating the y-offset for the next row as the current y-offset plus the height of the row:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (scale-photos config 400.8)
       (partition-all 3)
       (reduce (fn [{:keys [y-offset] :as acc} row-photos]
                 (let [new-y-offset (+ y-offset
                                       (:height (first row-photos))
                                       (:photo-padding config))
                       arranged-row (-&gt;&gt; row-photos
                                         (arrange-row config)
                                         (map #(assoc % :y-offset y-offset)))]
                   (-&gt; acc
                       (assoc :y-offset new-y-offset)
                       (update :arranged concat arranged-row))))
               {:y-offset (:photo-padding config), :arranged []})
       :arranged
       (map (partial set-photo-styles! config))
       (map (juxt :x-offset :y-offset)))
  ;; =&gt; ([0 4] [404.8 4] [809.6 4] [0 584] [404.8 584] [809.6 584] [0 1164] [404.8 1164])

  )
</code></pre><p>OK, this seems about right. Let&apos;s clean this mess up a bit:</p><pre><code class="language-clojure">(defn arrange-photos
  [{:keys [num-photos-per-row photo-padding] :as config} photos]
  (-&gt;&gt; photos
       (partition-all num-photos-per-row)
       (reduce (fn [{:keys [y-offset] :as acc} row-photos]
                 (let [arranged-row (-&gt;&gt; row-photos
                                         (arrange-row config)
                                         (map #(assoc % :y-offset y-offset)))
                       new-y-offset (+ y-offset
                                       (:height (first arranged-row))
                                       photo-padding)]
                   (-&gt; acc
                       (assoc :y-offset new-y-offset)
                       (update :arranged concat arranged-row))))
               {:y-offset photo-padding, :arranged []})
       :arranged))

(defn display-album!
  [{:keys [num-photos-per-row photo-padding] :as config} photos]
  (let [album-width (set-album-width! config)
        padding-width (* photo-padding (dec num-photos-per-row))
        photo-width (-&gt; (- album-width padding-width)
                        (/ num-photos-per-row))]
    (-&gt;&gt; photos
         (scale-photos config photo-width)
         (arrange-photos config)
         (map (partial set-photo-styles! config))
         doall)))

(comment

  (display-album! config photos)
  ;; =&gt; ( ... )

  )
</code></pre><p>Now, let&apos;s have a quick look at the browser. Yeah, things look reasonably nice... until we scroll down. 😬</p><p>Let&apos;s compare what our album looks like to what it looks like on Flickr:</p><p><img alt="A cartoon version of the Drake hotline bling meme: Drake is disgusted by our album and delighted by the Flickr UI" src="assets/2024-01-22-compare.png" title="OMG my eeeeeyyyeees!" /></p><p>Oh good lord Paladine what in the actual abyss?! Our photos are cropped weirdly and apparently we forgot all about this:</p><p><strong>4. All photos in a row should be scaled to the same height</strong></p><p>Let the self-flagellation begin! Or maybe we just fix the height thing. Whichever.</p><div class="markdown-heading"><h2 id="opting-for-the-latter-is-the-brave-thing-to-do">Opting for the latter is the brave thing to do</h2><a href="#opting-for-the-latter-is-the-brave-thing-to-do" class="anchor" aria-label="Permalink: Opting for the latter is the brave thing to do"><img src="assets/link.svg" /></a></div><p>We have a function called <code>scale-photos</code>, but what it&apos;s actually doing is setting the width. Scaling would be resizing both width and height, maintaining the same aspect ratio. Let&apos;s see if we can fix that:</p><pre><code class="language-clojure">(defn scale-photos [_config scaling-factor photos]
  (-&gt;&gt; photos
       (map (fn [photo]
              (-&gt; photo
                  (update :height / scaling-factor)
                  (update :width / scaling-factor))))))
</code></pre><p>So if we want to scale each photo down to half size, we&apos;d do this:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (scale-photos config 2)
       (map (juxt :width :height)))
  ;; =&gt; ([512 288] [512 288] [512 256] [512 288] [512 288] [361 511.5] [333 500] [511.5 149.5])

  (-&gt;&gt; photos
       (map (juxt :width :height)))
  ;; =&gt; ([1024 576] [1024 576] [1024 512] [1024 576] [1024 576] [722 1023] [666 1000] [1023 299])
  
  )
</code></pre><p>That looks pretty good. Now, how to compute the scaling factor? Let&apos;s say we have a row of three photos, with a total width of 3072, and an album width of 1210.4:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (take 3)
       (map :width)
       (reduce +))
  ;; =&gt; 3072

  (provisional-album-width config)
  ;; =&gt; 1210.4

  )
</code></pre><p>To get the scaling factor, we just need to divide the total width of the photos by the width of the album, taking padding into consideration, of course:</p><pre><code class="language-clojure">(comment

  (let [{:keys [num-photos-per-row photo-padding]} config]
    (-&gt; (-&gt;&gt; photos
             (take num-photos-per-row)
             (map :width)
             (reduce +))
        (/ (- (provisional-album-width config)
              (* photo-padding (dec num-photos-per-row))))))
  ;; =&gt; 2.5548902195608783

  )
</code></pre><p>This has just revealed something interesting that we should have noticed far earlier: the total width of the photos in a row varies, unless all of the photos just happen to be the same width (which is not the case for us):</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; photos
       (partition-all 3)
       (map #(reduce + (map :width %))))
  ;; =&gt; (3072 2770 1689)

  )
</code></pre><p>This means that we need to scale each row independently, which we can actually do right in <code>arrange-row</code>, as long as we provide album width in the config map. Let&apos;s write a function to compute the scale factor so as not to make a mess in <code>arrange-row</code>:</p><pre><code class="language-clojure">(defn get-scale-factor [{:keys [album-width photo-padding] :as config} photos]
  (let [row-width (-&gt;&gt; photos
                       (map :width)
                       (reduce +))
        available-width (- album-width (* photo-padding (dec (count photos))))]
    (/ row-width available-width)))

(comment

  (-&gt;&gt; photos
       (partition-all 3)
       (map (partial get-scale-factor (assoc config :album-width 1210.4))))
  ;; =&gt; (2.5548902195608783 2.303725881570193 1.4000331564986737)

  )
</code></pre><p>Now we can add the scaling to <code>arrange-row</code>:</p><pre><code class="language-clojure">(defn arrange-row [{:keys [photo-padding] :as config} photos]
  (let [scale-factor (get-scale-factor config photos)]
    (-&gt;&gt; photos
         (scale-photos config scale-factor)
         (reduce (fn [{:keys [x-offset] :as acc} {:keys [width] :as photo}]
                   (let [new-x-offset (+ x-offset width photo-padding)]
                     (-&gt; acc
                         (assoc :x-offset new-x-offset)
                         (update :arranged conj (assoc photo :x-offset x-offset)))))
                 {:x-offset 0, :arranged []})
         :arranged)))
</code></pre><p>And finally we need to add the album width to the config map in <code>display-album!</code> and remove the call to <code>scale-photos</code>, since that&apos;s happening for each row now:</p><pre><code class="language-clojure">(defn display-album!
  [{:keys [num-photos-per-row photo-padding] :as config} photos]
  (let [album-width (set-album-width! config)
        config (assoc config :album-width album-width)
        padding-width (* photo-padding (dec num-photos-per-row))
        photo-width (-&gt; (- album-width padding-width)
                        (/ num-photos-per-row))]
    (-&gt;&gt; photos
         (arrange-photos config)
         (map (partial set-photo-styles! config))
         doall)))

(comment

  (-&gt;&gt; (display-album! config photos)
       (map #(select-keys % [:width :height :x-offset :y-offset])))
  ;; =&gt; ({:width 400.8, :height 225.45, :x-offset 0, :y-offset 4}
  ;;     {:width 400.8, :height 225.45, :x-offset 404.8, :y-offset 4}
  ;;     {:width 400.8, :height 200.4, :x-offset 809.6, :y-offset 4}
  ;;     {:width 444.4973285198556, :height 250.0297472924188, :x-offset 0, :y-offset 584}
  ;;     {:width 444.4973285198556, :height 250.0297472924188, :x-offset 448.4973285198556, :y-offset 584}
  ;;     {:width 313.4053429602888, :height 444.0632490974729, :x-offset 896.9946570397112, :y-offset 584}
  ;;     {:width 475.7030195381883, :height 714.2687981053879, :x-offset 0, :y-offset 1164}
  ;;     {:width 730.6969804618118, :height 213.56637063351096, :x-offset 479.7030195381883, :y-offset 1164})

  )
</code></pre><p>We&apos;re almost there now! The final missing piece is to normalise the height of the photos before scaling them for the row width. Let&apos;s write a function that scales down photos so they&apos;re all the same height as the shortest photo:</p><pre><code class="language-clojure">(defn normalise-height [_config photos]
  (let [min-height (apply min (map :height photos))]
    (-&gt;&gt; photos
         (map (fn [{:keys [height width] :as photo}]
                (if (&gt; height min-height)
                  (assoc photo
                         :height min-height
                         :width (/ min-height (/ height width)))
                  photo))))))

(comment

  (-&gt;&gt; photos
       (take 3)
       (normalise-height config)
       (map (juxt :width :height)))
  ;; =&gt; ([910.2222222222222 512] [910.2222222222222 512] [1024 512])

  )
</code></pre><p>Now we just need to plug this into <code>arrange-row</code>:</p><pre><code class="language-clojure">(defn arrange-row [{:keys [photo-padding] :as config} photos]
  (let [normalised-photos (normalise-height config photos)
        scale-factor (get-scale-factor config normalised-photos)]
    (-&gt;&gt; normalised-photos
         (scale-photos config scale-factor)
         (reduce (fn [{:keys [x-offset] :as acc} {:keys [width] :as photo}]
                   (let [new-x-offset (+ x-offset width photo-padding)]
                     (-&gt; acc
                         (assoc :x-offset new-x-offset)
                         (update :arranged conj (assoc photo :x-offset x-offset)))))
                 {:x-offset 0, :arranged []})
         :arranged)))

(comment

  (-&gt;&gt; (display-album! config photos)
       (map #(select-keys % [:width :height :x-offset :y-offset])))
  ;; =&gt; ({:width 384.76800000000003, :height 216.43200000000002, :x-offset 0, :y-offset 4}
  ;;     {:width 384.76800000000003, :height 216.43200000000002, :x-offset 388.76800000000003, :y-offset 4}
  ;;     {:width 432.86400000000003, :height 216.43200000000002, :x-offset 777.5360000000001, :y-offset 4}
  ;;     {:width 501.6282612020187, :height 282.16589692613553, :x-offset 0, :y-offset 224.43200000000002}
  ;;     {:width 501.6282612020187, :height 282.16589692613553, :x-offset 505.6282612020187, :y-offset 224.43200000000002}
  ;;     {:width 199.1434775959627, :height 282.16589692613553, :x-offset 1011.2565224040374, :y-offset 224.43200000000002}
  ;;     {:width 196.57030865682486, :height 295.1506135988361, :x-offset 0, :y-offset 510.59789692613555}
  ;;     {:width 1009.8296913431751, :height 295.1506135988361, :x-offset 200.57030865682486, :y-offset 510.59789692613555})

  )
</code></pre><p>With great trepidation, we glance at our browser window... and see wonderful things!</p><p><img alt="A cartoon version of the Drake hotline bling meme: Drake is delighted by our album and delighted by the Flickr UI" src="assets/2024-01-22-yay.png" title="They keep callin&apos; on my cellphone, my cellphone" /></p><p>I would actually argue that our album is more aesthetically pleasing than the Flickr version, since it doesn&apos;t have a huge gap at the lower right-hand corner. 😍</p><div class="markdown-heading"><h2 id="are-you-feeling-dynamic?">Are you feeling dynamic?</h2><a href="#are-you-feeling-dynamic?" class="anchor" aria-label="Permalink: Are you feeling dynamic?"><img src="assets/link.svg" /></a></div><p>As happy as we are with ourselves (and deservedly so), we still have three rules left to follow:</p><p><strong>5. As the window is resized, photos should be rescaled to fit nicely</strong></p><p><strong>6. If the window is too small to display three photos per row, display two per row instead, and expand the album to fill the width of the window</strong></p><p><strong>7. If the window is too small to display two photos per row, display one per row instead</strong></p><p>Rule #5 is fairly straightforward. If we create a function that will update the page by calling <code>display-album!</code> with the correct arguments, we can add an event handler to the browser <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a>:</p><pre><code class="language-clojure">(defn update-page! [&amp; _]
  (display-album! config photos))

(.addEventListener js/window &quot;resize&quot; update-page!)
(update-page!)
</code></pre><p>We&apos;ll also call <code>update-page!</code> when the page loads for the first time. If we evaluate the buffer, nothing seems to happen, but if we resize the window now, our photos rescale! 🎉</p><p>Now let&apos;s figure out how to handle rules #6 and #7. What we can do is define a list of minimum photo widths that will cause a reduction in the number of photos per row:</p><pre><code class="language-clojure">(def config
  {:album-div-name &quot;album&quot;
   :album-min-width 900
   :album-width-pct 0.8
   :min-photo-widths [275 240]
   :num-photos-per-row 3
   :photo-padding 4})
</code></pre><p>We can then compute the number of photos per row by trying the default value, and if that results in the average photo width dipping below the first minimum width, reduce the photos per row by one and see if the new average width is smaller than the next minimum width, and so on. If you don&apos;t know what I mean, don&apos;t worry; this is probably easier to say in Clojure than in English:</p><pre><code class="language-clojure">(defn get-num-photos-per-row
  [{:keys [min-photo-widths num-photos-per-row] :as config} album-width]
  (loop [num-photos num-photos-per-row
         [min-width &amp; min-widths] min-photo-widths]
    (let [avg-width (/ album-width num-photos)]
      (if (or (nil? min-width)
              (= 1 num-photos)
              (&gt;= avg-width min-width))
        num-photos
        (recur (dec num-photos) min-widths)))))

(comment

  (get-num-photos-per-row config 1200)
  ;; =&gt; 3

  (get-num-photos-per-row config 800)
  ;; =&gt; 2

  (get-num-photos-per-row config 400)
  ;; =&gt; 1

  (get-num-photos-per-row config 100)
  ;; =&gt; 1

  (get-num-photos-per-row (assoc config :num-photos-per-row 4) 1600)
  ;; =&gt; 4

  )
</code></pre><p>Now if we hook this into <code>display-album!</code>, we should see the number of photos per row change as we resize the window:</p><pre><code class="language-clojure">(defn display-album!
  [{:keys [num-photos-per-row photo-padding] :as config} photos]
  (let [album-width (set-album-width! config)
        num-photos-per-row (get-num-photos-per-row config album-width)
        config (assoc config
                      :album-width album-width
                      :num-photos-per-row num-photos-per-row)
        padding-width (* photo-padding (dec num-photos-per-row))
        photo-width (-&gt; (- album-width padding-width)
                        (/ num-photos-per-row))]
    (-&gt;&gt; photos
         (arrange-photos config)
         (map (partial set-photo-styles! config))
         doall)))
</code></pre><p>Let&apos;s see:</p><p><img alt="The album with a window size of 906 and 3 photos per row" src="assets/2024-01-22-three.png" title="906 pixels gives us 3 photos per row" /></p><p><img alt="The album with a window size of 754 and 3 photos per row" src="assets/2024-01-22-two.png" title="754 pixels gives us 3 photos per row" /></p><p><img alt="The album with a window size of 451 and 3 photos per row" src="assets/2024-01-22-one.png" title="451 pixels gives us 3 photos per row" /></p><p>Pretty pretty pretty pretty cool.</p><p>And with that, let&apos;s declare victory! There are of course many features that could be added, such as:</p><ul><li>Making the &quot;← Back to albums list&quot; actually take you back to a list of albums (which doesn&apos;t currently exist)</li><li>Clicking on a photo to display it full size</li><li>Displaying the photo title and description when mousing over it, like Flickr does</li></ul><p>and so on and so forth. And who knows what the future will bring; there may yet be another post describing how to implement one or more of those things, but I think that 10,924 words is enough for one post, don&apos;t you?</p><p>Part 1: <a href="2024-01-17-clickr.html">clickr, or a young man&apos;s Flickr clonejure</a></p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2024-01-17-clickr.html</id>
    <link href="https://jmglov.net/blog/2024-01-17-clickr.html"/>
    <title>clickr, or a young man's Flickr clonejure</title>
    <updated>2024-01-17T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><img alt="A space station" src="assets/2024-01-17-phoenix.jpg" title="The Phoenix rises!" /></p><p>Way back when, before I got my first Macbook (the white 2006 model, so cool!) and thus had no iPhoto to keep all of my photos for me, I used some open source photo album thingy on Linux (it was so long ago that I don&apos;t even remember what it was called) on a server running under my desk with a fixed IP. Using this amazing setup, I could create photo albums and share them with family who wanted to keep up with my thrilling life. When we moved to Tokyo in 2005, I got rid of the Linux server (and the desk it was under and the apartment the desk was in) and brought only a laptop with me. When we first arrived, we didn&apos;t even have internet, so I borrowed wifi from someone in the next building who had helpfully eschewed a password, and I thought it would be a bit cheeky to locate that person and ask them to purchase a fixed IP so that I could run a webserver so I could share photo albums with my family.</p><p>Luckily for me, two people named Stewart Butterfield and Caterina Fake felt my pain and started a company called Ludicorp and tried to create a web-based massively multiplayer online game called Game Neverending, which they failed to do but made some pretty cool tools for assets which they then decided could be turned into an online photo sharing service which they named Flickr.</p><p>Which is a very long-winded way of saying—and unless you&apos;re very new to this blog, you will know that I am a very long-winded person—that I signed up for Flickr for my photo-sharing needs.</p><p>A few years later, I bought the aforementioned Macbook, and started using iPhoto, which was much nicer than copying photos from a memory card onto my hard drive and then uploading them to Flickr, so I got kinda lazy about creating albums on Flickr, until my son was born and my family started demanding to see pictures of him.</p><p>Flash forward to many years later, and now we all have smartphones and stuff (even my mom!), so we just take pictures which automatically go to iCloud and iPhoto and iDon&apos;tKnowWhereElse and then share them with each other in Signal and Telegram and WhatsApp and 95 other smartphone messaging apps like normal people, so we don&apos;t really use Flickr any more. In fact, I only remember we have Flickr when they email me once a year to remind me they&apos;re about to charge my credit card another $100 or whatever.</p><p>My reluctance to pay for something that I don&apos;t use is exceeded only by my reluctance to spend time on manually migrating off that thing, so I didn&apos;t do anything about this until a couple of years ago, when I just so happened to get the annual renewal email right before my winter vacation started, so I was like &quot;Oh, now I&apos;ll have some free time and I&apos;ll probably be bored so I should probably see if Flickr has an API that I could use to download my photos and put them onto S3 like the good lord intended.&quot;</p><p>Flickr did in fact have an API, and better yet, they had a <a href="https://github.com/boncey/Flickr4Java">Java
client</a>, which I wrapped up in some Clojure and named <a href="https://github.com/jmglov/clickr">clickr</a> because it&apos;s like Flickr in Clojure ha ha ha I&apos;m so clever. I got the listing of albums and downloading of photos and uploading of them to S3 working pretty easily, but for some reason didn&apos;t actually back up the albums to S3 except for the first one, probably because I evaluated some code in the REPL to start the back up and then switched tabs to read a blog or something and then forgot what I was doing and closed my laptop or something similarly absentminded.</p><p>Flash forward to a couple of weeks ago, when I once again got the famous email from Flickr and remembered that I really should get around to backing up those albums so I can stop paying Flickr and pay AWS a few more cents a year to store them for me. Since I now hate Clojure and only love <a href="https://babashka.org/">Babashka</a>, I decided that instead of going back to the Clojure wrapper around the Java library, I&apos;d whip up a quick HTTP client in Babashka instead and then just use <a href="https://github.com/grzm/awyeah-api">awyeah-api</a> for the S3-ing. I got a few hours into struggling with signing requests to get an OAuth access token which I could then get the user&apos;s (me) authorization to exchange for an access token—you know, <a href="https://www.flickr.com/services/api/auth.oauth.html">as you do</a>—when I decided that my life was way to short for taking a URL such as</p><pre><code class="language-text">https://www.flickr.com/services/oauth/request_token
?oauth_nonce=89601180
&amp;oauth_timestamp=1305583298
&amp;oauth_consumer_key=653e7a6ecc1d528c516cc8f92cf98611
&amp;oauth_signature_method=HMAC-SHA1
&amp;oauth_version=1.0
&amp;oauth_callback=http%3A%2F%2Fwww.example.com
</code></pre><p>and creating a base string such as</p><pre><code class="language-text">GET&amp;https%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Frequest_token&amp;oauth_callback%3Dhttp%253A%252F%252Fwww.example.com%26oauth_consumer_key%3D653e7a6ecc1d528c516cc8f92cf98611%26oauth_nonce%3D95613465%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1305586162%26oauth_version%3D1.0
</code></pre><p>and then generating the following signature</p><pre><code class="language-text">7w18YS2bONDPL%2FzgyzP5XTr5af4%3D
</code></pre><p>and then wondering why in the hell Flickr&apos;s API kept giving me a signature incorrect error when the damn signature was obviously correct because you know...</p><p><img alt="A diagram showing the three step OAuth flow for Flickr" src="assets/2024-01-17-flickr-oauth-flow.jpg" title="What in the actual what?" /></p><p>I rapidly came to the conclusion that I should retreat to the safe embrace of JVM Clojure and just let the Java client do all the nasty work of authenticating so I could do the fun work of Clojuring.</p><div class="markdown-heading"><h2 id="onwards-and-upwards!">Onwards and upwards!</h2><a href="#onwards-and-upwards!" class="anchor" aria-label="Permalink: Onwards and upwards!"><img src="assets/link.svg" /></a></div><p>I cloned my trusty <a href="https://github.com/jmglov/clickr">clickr</a> repo, then screamed as I saw a <code>project.clj</code> and realised that I didn&apos;t even have <a href="https://leiningen.org/">Leiningen</a> installed because I roll with <a href="https://clojure.org/guides/deps_and_cli">tools.deps</a> now and I can&apos;t remember any lein commands and OMG it&apos;s nearly 2024 (this was a few weeks ago, remember?) and I&apos;d better generate a <code>deps.edn</code> like a normal person:</p><pre><code class="language-clojure">{:paths [&quot;src&quot; &quot;dev&quot;]
 :deps {com.flickr4java/flickr4java {:mvn/version &quot;3.0.1&quot;}}}
</code></pre><p>Having done this, I could open <code>src/clickr/flickr.clj</code> and try and remember how to use some code I wrote a <s>million</s> couple years ago and didn&apos;t document in any way, shape, or form because I&apos;m a bad boy and life&apos;s too short for documentation!</p><p>According to Flickr4Java:</p><blockquote><p>To use the API just construct an instance of the class com.flickr4java.flickr.test.Flickr and request the interfaces which you need to work with.</p></blockquote><pre><code class="language-java">String apiKey = &quot;YOUR_API_KEY&quot;;
String sharedSecret = &quot;YOUR_SHARED_SECRET&quot;;
Flickr f = new Flickr(apiKey, sharedSecret, new REST());
</code></pre><p>OK, so we can start our namespace out by importing the Flickr client:</p><pre><code class="language-clojure">(ns clickr.flickr
  (:import (com.flickr4java.flickr Flickr
                                   REST)))
</code></pre><p>And then C-c M-j (<code>cider-jack-in-clj</code>) to start a REPL, and then C-c C-k (<code>cider-load-buffer</code>) to evaluate the buffer, then it seems like I need an API key and the corresponding secret, which I can grab from <a href="https://www.flickr.com/services/apps/by/jmglov">https://www.flickr.com/services/apps/by/jmglov</a>. Lemme just drop that in a map for safe-keeping and do a little C-v f c e (<code>cider-pprint-eval-last-sexp-to-comment</code>, obv):</p><pre><code class="language-clojure">(comment

  (def config {:api-key &quot;beefface5678910&quot;
               :secret &quot;facecafe1234&quot;})
  ;; =&gt; #&apos;clickr.flickr/config

  )
</code></pre><p>OK, so creating a client should be as simple as this:</p><pre><code class="language-clojure">  (def flickr (Flickr. (:api-key config) (:secret config) (REST.)))
  ;; =&gt; #&apos;clickr.flickr/flickr
</code></pre><p>And with this, it should be easy to figure out how to get a list of albums, right? Right?</p><div class="markdown-heading"><h2 id="what-the-flickr?">What the Flickr?</h2><a href="#what-the-flickr?" class="anchor" aria-label="Permalink: What the Flickr?"><img src="assets/link.svg" /></a></div><p>Popping over to <a href="https://www.flickr.com/services/api/">Flickr&apos;s API reference</a>, I&apos;ll just do a quick search for album and... 0 occurrences? Wait what now?</p><p>OK, time to scan the page for something that looks album-ish. 🙄</p><p>Ah, <a href="https://www.flickr.com/services/api/flickr.photosets.getList.html">photosets.getList</a> looks promising. <a href="https://github.com/search?q=repo%3Aboncey%2FFlickr4Java%20photoset&amp;type=code">Searching the Flickr4Java repo for
photoset</a> turns up a <a href="https://github.com/boncey/Flickr4Java/blob/e6b8b51f89c87260039485427ed0b7dbb1354eed/src/examples/java/Backup.java">src/examples/java/Backup.java</a>, which looks quite helpful:</p><pre><code class="language-java">public class Backup {
    private final String nsid;
    private final Flickr flickr;
    private AuthStore authStore;

    public Backup(String apiKey, String nsid, String sharedSecret, File authsDir) throws FlickrException {
        flickr = new Flickr(apiKey, sharedSecret, new REST());
        this.nsid = nsid;

        if (authsDir != null) {
            this.authStore = new FileAuthStore(authsDir);
        }
    }

    // ...

    public static void main(String[] args) throws Exception {
        if (args.length &lt; 4) {
            System.out.println(&quot;Usage: java &quot; + Backup.class.getName() + &quot; api_key nsid shared_secret output_dir&quot;);
            System.exit(1);
        }
        Backup bf = new Backup(args[0], args[1], args[2], new File(System.getProperty(&quot;user.home&quot;) + File.separatorChar + &quot;.flickrAuth&quot;));
        bf.doBackup(new File(args[3]));
    }
}
</code></pre><p>If we look at the <code>doBackup()</code> method, it looks like there&apos;s some authorisation we need to do above and beyond the API key and secret, which aligns with all the Flickr API docs said about &quot;every request must be signed OAuth blah blah blah&quot;:</p><pre><code class="language-java">RequestContext rc = RequestContext.getRequestContext();

if (this.authStore != null) {
    Auth auth = this.authStore.retrieve(this.nsid);
    if (auth == null) {
        this.authorize();
    } else {
        rc.setAuth(auth);
    }
}
</code></pre><p>Assuming we have no <code>Auth</code> object from the start, let&apos;s have a look at what the <code>authorize()</code> method does:</p><pre><code class="language-java">private void authorize() throws IOException, FlickrException {
    AuthInterface authInterface = flickr.getAuthInterface();
    OAuth1RequestToken requestToken = authInterface.getRequestToken();

    String url = authInterface.getAuthorizationUrl(requestToken, Permission.READ);
    System.out.println(&quot;Follow this URL to authorise yourself on Flickr&quot;);
    System.out.println(url);
    System.out.println(&quot;Paste in the token it gives you:&quot;);
    System.out.print(&quot;&gt;&gt;&quot;);

    String tokenKey = new Scanner(System.in).nextLine();

    OAuth1Token accessToken = authInterface.getAccessToken(requestToken, tokenKey);

    Auth auth = authInterface.checkToken(accessToken);
    RequestContext.getRequestContext().setAuth(auth);
    this.authStore.store(auth);
    System.out.println(&quot;Thanks.  You probably will not have to do this every time.  Now starting backup.&quot;);
}
</code></pre><p>OK, translating this to Clojure is pretty straight-forward. I&apos;ll start with my usual approach when dealing with API clients of creating a &quot;context&quot; which contains my config, various clients, and any other data that I might need to pass around. Let&apos;s create an <code>init-client</code> function that takes my config as an argument and returns such a context:</p><pre><code class="language-clojure">(defn init-client [{:keys [api-key secret] :as ctx}]
  (assoc ctx :flickr {:client (Flickr. api-key secret (REST.))}))
</code></pre><p>We can call that and get a context back containing the client:</p><pre><code class="language-clojure">(comment

  (def config {:api-key &quot;beefface5678910&quot;
               :secret &quot;facecafe1234&quot;})
  ;; =&gt; #&apos;clickr.flickr/config

  (init-client config)
  ;; =&gt; {:api-key &quot;beefface5678910&quot;,
  ;;     :secret &quot;facecafe1234&quot;,
  ;;     :flickr
  ;;     {:client
  ;;      #object[com.flickr4java.flickr.Flickr 0x12246439 &quot;com.flickr4java.flickr.Flickr@12246439&quot;]}}

  )
</code></pre><p>Now I have a client, but I need to perform the authorisation dance from the Java code. In the constructor of the Java class, they create a <code>FileAuthStore</code> in the <code>authsDir</code>, which is actually the directory called <code>output_dir</code> in the <code>main()</code> function. 🙄</p><p>Let&apos;s be a good citizen by creating this auth store in the user&apos;s home directory. In order to do this, let&apos;s add the awesome <a href="https://github.com/babashka/fs">babashka.fs</a> library to our deps:</p><pre><code class="language-clojure">{:paths [&quot;src&quot; &quot;dev&quot;]
 :deps {babashka/fs {:mvn/version &quot;0.4.19&quot;}
        com.flickr4java/flickr4java {:mvn/version &quot;3.0.1&quot;}}}
</code></pre><p>babashka.fs contains a bunch of really useful utility functions that work in both Babashka and JVM Clojure!</p><p>Tragically, after adding a new dep, I need to restart my REPL. It is possible to hotload dependencies into a running REPL process, which should have <a href="https://clojure.org/news/2023/04/14/clojure-1-12-alpha2">gotten
easier in Clojure
1.12</a>, and of course borkdude has a <a href="https://github.com/borkdude/deps.add-lib">deps.add-lib</a> project which should make it even easier, but I haven&apos;t used this stuff yet, so I&apos;ll just do the primitive thing and restart (swearing under my breath), of course.</p><p>Now that we have babashka.fs, creating a <code>FileAuthStore</code> in the <code>~/.flickrAuth</code> directory is as simple as this:</p><pre><code class="language-clojure">(ns clickr.flickr
  (:require [babashka.fs :as fs])
  (:import (com.flickr4java.flickr Flickr
                                   REST)
           (com.flickr4java.flickr.util FileAuthStore)))

(defn make-auth-store []
  (FileAuthStore. (fs/file (fs/home) &quot;.flickrAuth&quot;)))
</code></pre><p>Let&apos;s create the auth store in <code>init-client</code> and add it to the context along with the Flickr client itself:</p><pre><code class="language-clojure">(defn init-client [{:keys [api-key secret] :as ctx}]
  (let [client (Flickr. api-key secret (REST.))
        auth-store (make-auth-store)]
    (assoc ctx :flickr {:client client, :auth-store auth-store})))
</code></pre><p>Now that we have a way to create an auth store, let&apos;s write an <code>authorise</code> function to exchange a request token for an access token:</p><pre><code class="language-clojure">(ns clickr.flickr
  (:require [babashka.fs :as fs])
  (:import (com.flickr4java.flickr Flickr
                                   REST)
           (com.flickr4java.flickr.auth Permission)
           (com.flickr4java.flickr.util FileAuthStore)))

(defn authorise [{:keys [flickr] :as ctx}]
  (let [{:keys [client]} flickr
        auth-interface (.getAuthInterface client)
        req-token (.getRequestToken auth-interface)
        url (.getAuthorizationUrl auth-interface req-token Permission/READ)]
    (update ctx :flickr assoc :url url, :req-token req-token)))
</code></pre><p>Let&apos;s try it out:</p><pre><code class="language-clojure">(comment

  (def ctx (init-client config))
  ;; =&gt; #&apos;clickr.flickr/ctx

  (authorise ctx)
  ;; =&gt; {:api-key &quot;beefface5678910&quot;,
  ;;     :secret &quot;facecafe1234&quot;,
  ;;     :flickr
  ;;     {:client
  ;;      #object[com.flickr4java.flickr.Flickr 0x12246439 &quot;com.flickr4java.flickr.Flickr@12246439&quot;]
  ;;      :auth-store
  ;;      #object[com.flickr4java.flickr.util.FileAuthStore 0x6b1f411f &quot;com.flickr4java.flickr.util.FileAuthStore@6b1f411f&quot;]
  ;;      :url
  ;;      &quot;https://www.flickr.com/services/oauth/authorize?oauth_token=72157720906512072-49cebfb020e7fb06&amp;perms=read&quot;
  ;;      :req-token
  ;;      #object[com.github.scribejava.core.model.OAuth1RequestToken 0x2617e72c &quot;com.github.scribejava.core.model.OAuth1RequestToken@43e76617&quot;]}}

  )
</code></pre><p>If I visit that URL in a web browser where we&apos;re signed into Flickr, I&apos;m prompted to authorise the app corresponding to the API key I previously created:</p><p><img alt="A prompt to authorize an app to my Flickr account" src="assets/2024-01-17-flickr-prompt.png" title="What could possibly go wrong?" /></p><p>If I click &quot;OK, I&apos;ll authorize it&quot;, I get a code that I should &quot;type into the application&quot;. Let&apos;s set that up by modifying the <code>authorise</code> function to accept a code, which it will use to exchange the request token for an access token, then store that access token in the auth store that we previously created.</p><pre><code class="language-clojure">(ns clickr.flickr
  (:require [babashka.fs :as fs])
  (:import (com.flickr4java.flickr Flickr
                                   RequestContext
                                   REST)
           (com.flickr4java.flickr.auth Permission)
           (com.flickr4java.flickr.util FileAuthStore)))

(defn authorise [{:keys [flickr] :as ctx}]
  (let [{:keys [client auth-store req-token token-key]} flickr
        auth-interface (.getAuthInterface client)]
    (if (and req-token token-key)
      (let [access-token (.getAccessToken auth-interface req-token token-key)
            auth (.checkToken auth-interface access-token)]
        (.setAuth (RequestContext/getRequestContext) auth)
        (.store auth-store auth)
        (update ctx :flickr dissoc :req-token :token-key :url))
      (let [req-token (.getRequestToken auth-interface)
            url (.getAuthorizationUrl auth-interface req-token Permission/READ)]
        (update ctx :flickr assoc :url url, :req-token req-token)))))
</code></pre><p>The idea here is that if you pass a request token and token code in the Flickr context, you want to exchange a request token for an access token, and if you don&apos;t, you want to obtain a request token and the URL to authorise it.</p><p>OK, let&apos;s give it a whirl:</p><pre><code class="language-clojure">(comment

  (def ctx (authorise ctx))
  ;; =&gt; #&apos;clickr.flickr/ctx

  (get-in ctx [:flickr :url])
  ;; =&gt; &quot;https://www.flickr.com/services/oauth/authorize?oauth_token=72157720906550331-8cf736dfbfe34398&amp;perms=read&quot;

  (authorise (assoc-in ctx [:flickr :token-key] &quot;123-456-789&quot;))
  ;; =&gt; {:api-key &quot;beefface5678910&quot;,
  ;;     :secret &quot;facecafe1234&quot;,
  ;;     :flickr
  ;;     {:client
  ;;      #object[com.flickr4java.flickr.Flickr 0x67f9df60 &quot;com.flickr4java.flickr.Flickr@67f9df60&quot;],
  ;;      :auth-store
  ;;      #object[com.flickr4java.flickr.util.FileAuthStore 0x237de92 &quot;com.flickr4java.flickr.util.FileAuthStore@237de92&quot;]}}

  )
</code></pre><p>In theory, we should now have a Flickr4Java request context with an access token, and that access token stored in our auth store. Let&apos;s check out what&apos;s in the auth store:</p><pre><code class="language-clojure">(comment

  (.retrieveAll (get-in ctx [:flickr :auth-store]))
  ;; =&gt; [#object[com.flickr4java.flickr.auth.Auth 0x7737c4f2 &quot;com.flickr4java.flickr.auth.Auth@7737c4f2&quot;]]

  )
</code></pre><p>Ooh, exciting!</p><p>If we cast our mind back to that Java code:</p><pre><code class="language-java">Auth auth = this.authStore.retrieve(this.nsid);
if (auth == null) {
    this.authorize();
} else {
    rc.setAuth(auth);
}
</code></pre><p>we see that the <code>authorize()</code> method is only called if we don&apos;t have an access token (the <code>Auth</code> object). If we have one, we just stuff it in the request context and move on with our life. Let&apos;s make one final change to our <code>authorise</code> function to do the same thing:</p><pre><code class="language-clojure">(defn authorise [{:keys [flickr] :as ctx}]
  (let [{:keys [client auth-store req-token token-key]} flickr
        auth-interface (.getAuthInterface client)
        auth (-&gt; auth-store .retrieveAll first)]
    (cond
      ;; We have a valid access token from the auth store
      auth
      (do
        (.setAuth (RequestContext/getRequestContext) auth)
        (update ctx :flickr assoc :auth auth))

      ;; We have a request token and a token key, so exchange the request
      ;; token for an access token
      (and req-token token-key)
      (let [access-token (.getAccessToken auth-interface req-token token-key)
            auth (.checkToken auth-interface access-token)]
        (.setAuth (RequestContext/getRequestContext) auth)
        (.store auth-store auth)
        (update ctx :flickr dissoc :req-token :token-key :url))

      ;; We don&apos;t have any tokens, so grab a request token and the URL to
      ;; authorise it
      :default
      (let [req-token (.getRequestToken auth-interface)
            url (.getAuthorizationUrl auth-interface req-token Permission/READ)]
        (update ctx :flickr assoc :url url, :req-token req-token)))))
</code></pre><p>We can see if it works by creating a brand new client and calling <code>authorise</code> on it:</p><pre><code class="language-clojure">(comment

  (-&gt; (init-client config) authorise)
  ;; =&gt; {:api-key &quot;beefface5678910&quot;,
  ;;     :secret &quot;facecafe1234&quot;,
  ;;     :flickr
  ;;     {:client
  ;;      #object[com.flickr4java.flickr.Flickr 0x15c343a9 &quot;com.flickr4java.flickr.Flickr@15c343a9&quot;],
  ;;      :auth-store
  ;;      #object[com.flickr4java.flickr.util.FileAuthStore 0x6df7251f &quot;com.flickr4java.flickr.util.FileAuthStore@6df7251f&quot;]
  ;;      :auth
  ;;      #object[com.flickr4java.flickr.auth.Auth 0x4d1d0eb0 &quot;com.flickr4java.flickr.auth.Auth@4d1d0eb0&quot;]}}

  )
</code></pre><p>That calls for a celebration!</p><p>![A woman on a beach at sunrise with her head thrown back, saying &quot;Victory&quot;][victory] [victory]:[assets/2023-11-11-victory.jpg &quot;Victory!&quot;]</p><p>Given that you only need to go through the rigmarole of exchanging a request token for an auth token once, I feel like it&apos;s reasonable to have <code>init-client</code> go ahead and authorise the client. This will work just fine for the rigmarole case as well, since you can just call <code>authorise</code> on the client yourself if it has a <code>:url</code> key set, so there&apos;s no harm in doing this.</p><pre><code class="language-clojure">(defn init-client [{:keys [api-key secret] :as ctx}]
  (let [client (Flickr. api-key secret (REST.))
        auth-store (make-auth-store)]
    (-&gt; ctx
        (assoc :flickr {:client client, :auth-store auth-store})
        authorise)))
</code></pre><div class="markdown-heading"><h2 id="ok,-so-what-about-those-albums-again?">OK, so what about those albums again?</h2><a href="#ok,-so-what-about-those-albums-again?" class="anchor" aria-label="Permalink: OK, so what about those albums again?"><img src="assets/link.svg" /></a></div><p>Before we got sidetracked by all of this annoying security stuff, the actual goal was to get a list of my photo albums, which we learned are apparently called &quot;photosets&quot; in the Flickr API. Let&apos;s have a look at how the example Java code deals with them:</p><pre><code class="language-java">PhotosetsInterface pi = flickr.getPhotosetsInterface();
Iterator sets = pi.getList(this.nsid).getPhotosets().iterator();
</code></pre><p>The <code>nsid</code> thingy turns out to just be my Flickr user ID, which I can grab from the <code>Auth</code> object. Let&apos;s grab an album and see what it&apos;s all about!</p><pre><code class="language-clojure">(comment

  (def album
    (let [ps-interface (.getPhotosetsInterface (get-in ctx [:flickr :client]))
          user-id (.. (get-in ctx [:flickr :auth]) getUser getId)]
      (-&gt; ps-interface (.getList user-id) .getPhotosets first)))
  ;; =&gt; #&apos;clickr.flickr/album

  album
  ;; =&gt; #object[com.flickr4java.flickr.photosets.Photoset 0x726a87d4 &quot;com.flickr4java.flickr.photosets.Photoset@726a87d4&quot;]

  )
</code></pre><p>Cool, I guess. Looking at the Flickr API reference for <a href="https://www.flickr.com/services/api/flickr.photosets.getList.html">photosets.getList</a>, we can see an example XML response:</p><pre><code class="language-xml">&lt;photosets page=&quot;1&quot; pages=&quot;1&quot; perpage=&quot;30&quot; total=&quot;2&quot; cancreate=&quot;1&quot;&gt;
  &lt;photoset id=&quot;72157626216528324&quot; primary=&quot;5504567858&quot; secret=&quot;017804c585&quot; server=&quot;5174&quot; farm=&quot;6&quot; photos=&quot;22&quot; videos=&quot;0&quot; count_views=&quot;137&quot; count_comments=&quot;0&quot; can_comment=&quot;1&quot; date_create=&quot;1299514498&quot; date_update=&quot;1300335009&quot;&gt;
    &lt;title&gt;Avis Blanche&lt;/title&gt;
    &lt;description&gt;My Grandma&apos;s Recipe File.&lt;/description&gt;
  &lt;/photoset&gt;
  &lt;photoset id=&quot;72157624618609504&quot; primary=&quot;4847770787&quot; secret=&quot;6abd09a292&quot; server=&quot;4153&quot; farm=&quot;5&quot; photos=&quot;43&quot; videos=&quot;12&quot; count_views=&quot;523&quot; count_comments=&quot;1&quot; can_comment=&quot;1&quot; date_create=&quot;1280530593&quot; date_update=&quot;1308091378&quot;&gt;
    &lt;title&gt;Mah Kittehs&lt;/title&gt;
    &lt;description&gt;Sixty and Niner. Born on the 3rd of May, 2010, or thereabouts. Came to my place on Thursday, July 29, 2010.&lt;/description&gt;
  &lt;/photoset&gt;
&lt;/photosets&gt;
</code></pre><p>Let&apos;s make some assumptions about what getters the <code>Photoset</code> class has and see if we can find out anything interesting about our album:</p><pre><code class="language-clojure">(comment

  (.getId album)
  ;; =&gt; &quot;72177720314024335&quot;

  (.getTitle album)
  ;; =&gt; &quot;clickr demo&quot;

  (.getDescription album)
  ;; =&gt; &quot;Photo album demo for my clickr blog post&quot;

  )
</code></pre><p>Nice! Given this, let&apos;s write a function that turns a <code>Photoset</code> into a plain old map (or POM—that&apos;s what that means, right?):</p><pre><code class="language-clojure">(defn -&gt;album [photoset]
  {:id (.getId photoset)
   :title (.getTitle photoset)
   :description (.getDescription photoset)
   :object photoset})

(comment

  (-&gt;album album)
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :title &quot;clickr demo&quot;,
  ;;     :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photosets.Photoset 0x726a87d4 &quot;com.flickr4java.flickr.photosets.Photoset@726a87d4&quot;]}

  )
</code></pre><p>And now that we have this, why not a function that grabs all of my albums?</p><pre><code class="language-clojure">(defn get-albums [{:keys [flickr] :as ctx}]
  (let [user-id (.. (:auth flickr) getUser getId)]
    (-&gt;&gt; (-&gt; (:client flickr)
             (.getPhotosetsInterface)
             (.getList user-id)
             (.getPhotosets))
         (map -&gt;album))))

(comment

  (-&gt;&gt; (get-albums ctx)
       count)
  ;; =&gt; 165

  (-&gt;&gt; (get-albums ctx)
       (take 2))
  ;; =&gt; ({:id &quot;72177720314024335&quot;,
  ;;      :title &quot;clickr demo&quot;,
  ;;      :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;      :object
  ;;      #object[com.flickr4java.flickr.photosets.Photoset 0x9d8b7ae &quot;com.flickr4java.flickr.photosets.Photoset@9d8b7ae&quot;]}
  ;;     {:id &quot;72157706528674711&quot;,
  ;;      :title &quot;Kai&apos;s 8th Birthday&quot;,
  ;;      :description
  ;;      &quot;April 2015. Kaiche&apos;s first year at SIS. Treating his classmates to muffins in class. Sushi and cake with mommy and daddy. &quot;,
  ;;      :object
  ;;      #object[com.flickr4java.flickr.photosets.Photoset 0x1bb741fe &quot;com.flickr4java.flickr.photosets.Photoset@1bb741fe&quot;]})

  )
</code></pre><p>Alright, it looks like I have quite a few albums to deal with here. But an album should contain some photos, right? Let&apos;s see if we can figure out how to grab them.</p><p>In Java, that apparently looks like this:</p><pre><code class="language-java">Photoset set = (Photoset) sets.next();
PhotoList photos = pi.getPhotos(set.getId(), 500, 1);
</code></pre><p>Let&apos;s try that in Clojure:</p><pre><code class="language-clojure">(comment

  (def album (-&gt; (get-albums ctx) first))
  ;; =&gt; #&apos;clickr.flickr/album

  (def ps-interface (.getPhotosetsInterface (get-in ctx [:flickr :client])))
  ;; =&gt; #&apos;clickr.flickr/ps-interface

  (def photos (.getPhotos ps-interface (:id album) 500 1))
  ;; =&gt; #&apos;clickr.flickr/photos

  (count photos)
  ;; =&gt; 8

  (first photos)
  ;; =&gt; #object[com.flickr4java.flickr.photos.Photo 0xd254585 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;]
  )
</code></pre><p>According to the Flickr API documentation for <a href="https://www.flickr.com/services/api/flickr.photosets.getPhotos.html">photosets.getPhotos</a>, the <code>500</code> and the <code>1</code> are the number of photos to return per page and the page number, both of which are the default values. Seems fine.</p><p>The docs are a little sparse on what&apos;s in a photo, though:</p><pre><code class="language-xml">&lt;photoset id=&quot;4&quot; primary=&quot;2483&quot; page=&quot;1&quot; perpage=&quot;500&quot; pages=&quot;1&quot; total=&quot;2&quot;&gt;
  &lt;photo id=&quot;2484&quot; secret=&quot;123456&quot; server=&quot;1&quot; title=&quot;my photo&quot; isprimary=&quot;0&quot; /&gt;
  &lt;photo id=&quot;2483&quot; secret=&quot;123456&quot; server=&quot;1&quot; title=&quot;flickr rocks&quot; isprimary=&quot;1&quot; /&gt;
&lt;/photoset&gt;
</code></pre><p>Let&apos;s ask the JVM what getters the photo class has:</p><pre><code class="language-clojure">  (def photo (first photos))
  ;; =&gt; #&apos;clickr.flickr/photo

  (-&gt;&gt; photo class .getDeclaredMethods
       (map #(.getName %))
       (filter #(str/starts-with? % &quot;get&quot;))
       sort)
  ;; =&gt; (&quot;getBaseImageUrl&quot;
  ;;     &quot;getComments&quot;
  ;;     &quot;getCountry&quot;
  ;;     &quot;getCounty&quot;
  ;;     &quot;getDateAdded&quot;
  ;;     &quot;getDatePosted&quot;
  ;;     &quot;getDateTaken&quot;
  ;;     &quot;getDescription&quot;
  ;;     &quot;getEditability&quot;
  ;;     &quot;getFarm&quot;
  ;;     &quot;getGeoData&quot;
  ;;     &quot;getHdMp4&quot;
  ;;     &quot;getHdMp4Url&quot;
  ;;     &quot;getIconFarm&quot;
  ;;     &quot;getIconServer&quot;
  ;;     &quot;getId&quot;
  ;;     &quot;getImage&quot;
  ;;     &quot;getImageAsStream&quot;
  ;;     &quot;getLarge1600Size&quot;
  ;;     &quot;getLarge1600Url&quot;
  ;;     &quot;getLarge2048Size&quot;
  ;;     &quot;getLarge2048Url&quot;
  ;;     &quot;getLargeAsStream&quot;
  ;;     &quot;getLargeImage&quot;
  ;;     &quot;getLargeSize&quot;
  ;;     &quot;getLargeUrl&quot;
  ;;     &quot;getLastUpdate&quot;
  ;;     &quot;getLicense&quot;
  ;;     &quot;getLocality&quot;
  ;;     &quot;getMedia&quot;
  ;;     &quot;getMediaStatus&quot;
  ;;     &quot;getMedium640Size&quot;
  ;;     &quot;getMedium640Url&quot;
  ;;     &quot;getMedium800Size&quot;
  ;;     &quot;getMedium800Url&quot;
  ;;     &quot;getMediumAsStream&quot;
  ;;     &quot;getMediumImage&quot;
  ;;     &quot;getMediumSize&quot;
  ;;     &quot;getMediumUrl&quot;
  ;;     &quot;getMobileMp4&quot;
  ;;     &quot;getMobileMp4Url&quot;
  ;;     &quot;getNotes&quot;
  ;;     &quot;getOriginalAsStream&quot;
  ;;     &quot;getOriginalBaseImageUrl&quot;
  ;;     &quot;getOriginalFormat&quot;
  ;;     &quot;getOriginalHeight&quot;
  ;;     &quot;getOriginalImage&quot;
  ;;     &quot;getOriginalImage&quot;
  ;;     &quot;getOriginalImageAsStream&quot;
  ;;     &quot;getOriginalSecret&quot;
  ;;     &quot;getOriginalSize&quot;
  ;;     &quot;getOriginalUrl&quot;
  ;;     &quot;getOriginalWidth&quot;
  ;;     &quot;getOwner&quot;
  ;;     &quot;getPathAlias&quot;
  ;;     &quot;getPermissions&quot;
  ;;     &quot;getPhotoUrl&quot;
  ;;     &quot;getPlaceId&quot;
  ;;     &quot;getPublicEditability&quot;
  ;;     &quot;getRegion&quot;
  ;;     &quot;getRotation&quot;
  ;;     &quot;getSecret&quot;
  ;;     &quot;getServer&quot;
  ;;     &quot;getSiteMP4Size&quot;
  ;;     &quot;getSiteMP4Url&quot;
  ;;     &quot;getSizes&quot;
  ;;     &quot;getSmall320Size&quot;
  ;;     &quot;getSmall320Url&quot;
  ;;     &quot;getSmallAsInputStream&quot;
  ;;     &quot;getSmallImage&quot;
  ;;     &quot;getSmallSize&quot;
  ;;     &quot;getSmallSquareAsInputStream&quot;
  ;;     &quot;getSmallSquareImage&quot;
  ;;     &quot;getSmallSquareUrl&quot;
  ;;     &quot;getSmallUrl&quot;
  ;;     &quot;getSquareLargeSize&quot;
  ;;     &quot;getSquareLargeUrl&quot;
  ;;     &quot;getSquareSize&quot;
  ;;     &quot;getStats&quot;
  ;;     &quot;getTags&quot;
  ;;     &quot;getTakenGranularity&quot;
  ;;     &quot;getThumbnailAsInputStream&quot;
  ;;     &quot;getThumbnailImage&quot;
  ;;     &quot;getThumbnailSize&quot;
  ;;     &quot;getThumbnailUrl&quot;
  ;;     &quot;getTitle&quot;
  ;;     &quot;getUrl&quot;
  ;;     &quot;getUrls&quot;
  ;;     &quot;getUsage&quot;
  ;;     &quot;getVideoOriginalSize&quot;
  ;;     &quot;getVideoOriginalUrl&quot;
  ;;     &quot;getVideoPlayerSize&quot;
  ;;     &quot;getVideoPlayerUrl&quot;
  ;;     &quot;getViews&quot;)
</code></pre><p>Let&apos;s write a <code>-&gt;photo</code> function to POM-ify this suckah!</p><pre><code class="language-clojure">(defn -&gt;photo [photo]
  {:id (.getId photo)
   :title (.getTitle photo)
   :description (.getDescription photo)
   :date-taken (.getDateTaken photo)
   :width (.getOriginalWidth photo)
   :height (.getOriginalHeight photo)
   :geo-data (.getGeoData photo)
   :rotation (.getRotation photo)
   :object photo})

(comment

  (-&gt;photo photo)
  ;; =&gt; {:description nil,
  ;;     :date-taken nil,
  ;;     :geo-data nil,
  ;;     :rotation -1,
  ;;     :width 0,
  ;;     :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;     :id &quot;53460147147&quot;,
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photos.Photo 0xd254585 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;     :height 0}

  )
</code></pre><p>And now that we have this, let&apos;s add the photos to the the album map:</p><pre><code class="language-clojure">(defn -&gt;album [{:keys [flickr] :as ctx} photoset]
  (let [ps-interface (.getPhotosetsInterface (:client flickr))]
    {:id (.getId photoset)
     :title (.getTitle photoset)
     :description (.getDescription photoset)
     :photos (-&gt;&gt; (.getPhotos ps-interface (:id album) 500 1)
                  (map (partial -&gt;photo ctx)))
     :object photoset}))
</code></pre><p>Note that in order to list the photos in an album, we need the <code>PhotosetInterface</code>, which we get from the Flickr client in the context, so we need to add the context as an argument to <code>-&gt;album</code>. In fact, let&apos;s make it a convention that <code>ctx</code> is always the first argument to functions in this namespace, and add it to <code>-&gt;photo</code> as well:</p><pre><code class="language-clojure">(defn -&gt;photo [_ctx photo]
  {:id (.getId photo)
   :title (.getTitle photo)
   :description (.getDescription photo)
   :date-taken (.getDateTaken photo)
   :width (.getOriginalWidth photo)
   :height (.getOriginalHeight photo)
   :geo-data (.getGeoData photo)
   :rotation (.getRotation photo)
   :object photo})
</code></pre><p>We don&apos;t actually need it in this function, so we&apos;ll prepend an underscore to the arg name so CIDER or LSP or clj-kondo or whatever tooling you&apos;re using won&apos;t yell at us that it&apos;s unused. This is a convention that I first discovered in Erlang, and I think it&apos;s a cool way to say that &quot;this is the context, which we don&apos;t need here (yet)&quot;.</p><p>Finally, we need to pass the context along in <code>get-albums</code> as well:</p><pre><code class="language-clojure">(defn get-albums [{:keys [flickr] :as ctx}]
  (let [user-id (.. (:auth flickr) getUser getId)]
    (-&gt;&gt; (-&gt; (:client flickr)
             (.getPhotosetsInterface)
             (.getList user-id)
             (.getPhotosets))
         (map (partial -&gt;album ctx)))))
</code></pre><div class="markdown-heading"><h2 id="making-off-with-the-goods">Making off with the goods</h2><a href="#making-off-with-the-goods" class="anchor" aria-label="Permalink: Making off with the goods"><img src="assets/link.svg" /></a></div><p>Now that we have a way to list albums and the photos within them, let&apos;s see how to download said photos. Reading on in <code>Backup.java</code>, I encounter this good stuff:</p><pre><code class="language-java">Photo p = (Photo) setIterator.next();
String url = p.getLargeUrl();
URL u = new URL(url);
String filename = u.getFile();
filename = filename.substring(filename.lastIndexOf(&quot;/&quot;) + 1, filename.length());
System.out.println(&quot;Now writing &quot; + filename + &quot; to &quot; + setDirectory.getCanonicalPath());
BufferedInputStream inStream = new BufferedInputStream(photoInt.getImageAsStream(p, Size.LARGE));
File newFile = new File(setDirectory, filename);

FileOutputStream fos = new FileOutputStream(newFile);

int read;

while ((read = inStream.read()) != -1) {
    fos.write(read);
}
fos.flush();
fos.close();
inStream.close();
</code></pre><p>That looks like one way to do it. 😬</p><p>Let&apos;s see if we can clean this up a little. This whole mess:</p><pre><code class="language-java">while ((read = inStream.read()) != -1) {
    fos.write(read);
}
</code></pre><p>can be replaced with <a href="https://clojuredocs.org/clojure.java.io/copy">clojure.java.io/copy</a>, so let&apos;s update the <code>ns</code> form to require in <code>clojure.java.io</code>, and import the other Java classes mentioned in this code snippet whilst we&apos;re at it:</p><pre><code class="language-clojure">(ns clickr.flickr
  (:require [babashka.fs :as fs]
            [clojure.java.io :as io])
  (:import (com.flickr4java.flickr Flickr
                                   RequestContext
                                   REST)
           (com.flickr4java.flickr.auth Permission)
           (com.flickr4java.flickr.photos Size)
           (com.flickr4java.flickr.util FileAuthStore)
           (java.io BufferedInputStream
                    FileOutputStream)))
</code></pre><p>I also find this stuff to get the filename of the photo to be a bit annoying:</p><pre><code class="language-java">String url = p.getLargeUrl();
URL u = new URL(url);
String filename = u.getFile();
filename = filename.substring(filename.lastIndexOf(&quot;/&quot;) + 1, filename.length());
</code></pre><p>Let&apos;s make the filename the photo&apos;s ID plus its format. We can do this in our <code>-&gt;photo</code> function like so:</p><pre><code class="language-clojure">(defn -&gt;photo [_ photo]
  (let [id (.getId photo)
        extension (.getOriginalFormat photo)
        filename (format &quot;%s.%s&quot; id extension)]
    {:id id
     :filename filename
     :title (.getTitle photo)
     :description (.getDescription photo)
     :date-taken (.getDateTaken photo)
     :width (.getOriginalWidth photo)
     :height (.getOriginalHeight photo)
     :geo-data (.getGeoData photo)
     :rotation (.getRotation photo)
     :object photo}))
</code></pre><p>Now we can write a function to download a photo nicely. To be good citizens, let&apos;s put the file in the tmp directory (<code>/tmp</code> on Linux and MacOS, who knows where on Windows). Luckily for us, babashka.fs has a handy <code>temp-dir</code> function that can do this! 🎉</p><pre><code class="language-clojure">(defn download-photo! [{:keys [flickr] :as ctx}
                       {:keys [filename] :as photo}]
  (let [p-interface (.getPhotosInterface (:client flickr))]
    (with-open [in (BufferedInputStream. (.getImageAsStream p-interface (:object photo) Size/LARGE))
                out (FileOutputStream. (fs/file (fs/temp-dir) filename))]
      (io/copy in out))))
</code></pre><p>Now let&apos;s try calling it and seeing if it works!</p><pre><code class="language-clojure">(comment

  (def album (-&gt; (get-albums ctx) first))
  ;; =&gt; #&apos;clickr.flickr/album

  (def photo (-&gt; album :photos first))
  ;; =&gt; #&apos;clickr.flickr/photo

  photo
  ;; =&gt; {:description nil,
  ;;     :date-taken nil,
  ;;     :geo-data nil,
  ;;     :rotation -1,
  ;;     :width 0,
  ;;     :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;     :filename &quot;53460147147.jpg&quot;,
  ;;     :id &quot;53460147147&quot;,
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photos.Photo 0x5d288375 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;     :height 0}

  (download-photo! ctx photo)
  ;; =&gt; nil

  (fs/exists? (fs/file (fs/temp-dir) (:filename photo)))
  ;; =&gt; true

  )
</code></pre><p>Sure enough, we now have a <code>/tmp/53460147147.jpg</code> file!</p><p><img alt="A space station" src="assets/2024-01-17-phoenix.jpg" title="The Phoenix rises!" /></p><div class="markdown-heading"><h2 id="backing-things-up">Backing things up</h2><a href="#backing-things-up" class="anchor" aria-label="Permalink: Backing things up"><img src="assets/link.svg" /></a></div><p>Now that we&apos;ve proven that we can download a photo, let&apos;s think about how we want the backup process to work. What we probably want is to create a &quot;folder&quot; in our S3 bucket for each album, and then put all of the photos for that album inside it. Let&apos;s write a function to download an entire album.</p><p>The first order of business is to create a directory to hold the photos in the album that we&apos;re about to download. Let&apos;s use the album ID as the name of the directory and drop it in the tmp directory:</p><pre><code class="language-clojure">(comment

  (fs/file (fs/temp-dir) (:id album))
  ;; =&gt; #object[java.io.File 0x4e8e72c2 &quot;/tmp/72177720314024335&quot;]

  )
</code></pre><p>We can now use <code>create-dirs</code> to create the directory:</p><pre><code class="language-clojure">
(comment

  (-&gt;&gt; (fs/file (fs/temp-dir) (:id album)) fs/create-dirs)
  ;; =&gt; #object[sun.nio.fs.UnixPath 0x1fbb7d68 &quot;/tmp/72177720314024335&quot;]

  )
</code></pre><p>OK, so we have a directory to hold the photos, but we&apos;re going to have to update <code>download-photo!</code> to use that directory instead of dropping stuff straight into <code>/tmp</code>. Easy enough:</p><pre><code class="language-clojure">(defn download-photo! [{:keys [flickr out-dir] :as ctx}
                       {:keys [filename] :as photo}]
  (let [p-interface (.getPhotosInterface (:client flickr))]
    (with-open [in (BufferedInputStream. (.getImageAsStream p-interface (:object photo) Size/LARGE))
                out (FileOutputStream. (fs/file out-dir filename))]
      (io/copy in out))))

(comment

  (def album-dir (-&gt;&gt; (fs/file (fs/temp-dir) (:id album)) fs/create-dirs))
  ;; =&gt; #&apos;clickr.flickr/album-dir

  (download-photo! (assoc ctx :out-dir album-dir) photo)
  ;; =&gt; nil

  (fs/exists? (fs/file album-dir (format &quot;%s.jpg&quot; (:id photo))))
  ;; =&gt; true

  )
</code></pre><p>Having thus tamed <code>download-photo!</code>, we can write <code>download-album!</code>:</p><pre><code class="language-clojure">(defn download-album! [ctx {:keys [id photos] :as album}]
  (let [album-dir (-&gt;&gt; id (fs/file (fs/temp-dir)) fs/create-dirs fs/file)]
    (-&gt;&gt; photos
         (map (partial download-photo! (assoc ctx :out-dir album-dir)))
         doall)))

(comment

  (download-album! ctx album)
  ;; =&gt; (nil nil nil nil nil nil nil nil)

  (fs/glob album-dir &quot;*&quot;)
  ;; =&gt; [#object[sun.nio.fs.UnixPath 0x72466b2f &quot;/tmp/72177720314024335/53461405604.jpg&quot;]
  ;;     #object[sun.nio.fs.UnixPath 0x788d40e5 &quot;/tmp/72177720314024335/53460163402.jpg&quot;]
  ;;     #object[sun.nio.fs.UnixPath 0x26f7ff12 &quot;/tmp/72177720314024335/53460161007.jpg&quot;]
  ;;     #object[sun.nio.fs.UnixPath 0x250e8e92 &quot;/tmp/72177720314024335/53460147147.jpg&quot;]
  ;;     #object[sun.nio.fs.UnixPath 0x17fa6f15 &quot;/tmp/72177720314024335/53461214223.jpg&quot;]
  ;;     #object[sun.nio.fs.UnixPath 0x5e28f67 &quot;/tmp/72177720314024335/53461091151.jpg&quot;]
  ;;     #object[sun.nio.fs.UnixPath 0x1cf4ffa6 &quot;/tmp/72177720314024335/53460151727.jpg&quot;]
  ;;     #object[sun.nio.fs.UnixPath 0x4ddf88b4 &quot;/tmp/72177720314024335/53461088046.jpg&quot;]]

  )
</code></pre><p>Fantastic! Though I have to admit that I don&apos;t find the list of <code>nil</code>s very friendly. Let&apos;s make one last change to <code>download-photo</code> so that it returns the photo, with the location of the downloaded file added to it:</p><pre><code class="language-clojure">(defn download-photo! [{:keys [flickr out-dir] :as ctx}
                       {:keys [filename] :as photo}]
  (let [p-interface (.getPhotosInterface (:client flickr))
        out-file (fs/file out-dir filename)]
    (with-open [in (BufferedInputStream. (.getImageAsStream p-interface (:object photo) Size/LARGE))
                out (FileOutputStream. out-file)]
      (io/copy in out))
    (assoc photo :out-file out-file)))

(comment

  (download-photo! (assoc ctx :out-dir album-dir) photo)
  ;; =&gt; {:description nil,
  ;;     :date-taken nil,
  ;;     :geo-data nil,
  ;;     :rotation -1,
  ;;     :width 0,
  ;;     :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;     :filename &quot;53460147147.jpg&quot;,
  ;;     :id &quot;53460147147&quot;,
  ;;     :out-file
  ;;     #object[java.io.File 0x44f5abfa &quot;/tmp/72177720314024335/53460147147.jpg&quot;],
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photos.Photo 0x4d361782 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;     :height 0}

  )
</code></pre><p>Much nicer! We can now do the same thing to <code>download-album!</code>:</p><pre><code class="language-clojure">(defn download-album! [ctx {:keys [id photos] :as album}]
  (let [album-dir (-&gt;&gt; id (fs/file (fs/temp-dir)) fs/create-dirs fs/file)
        photos (-&gt;&gt; photos
                    (map (partial download-photo! (assoc ctx :out-dir album-dir)))
                    doall)]
    (assoc album :out-dir album-dir, :photos photos)))

(comment

  (download-album! ctx album)
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :title &quot;clickr demo&quot;,
  ;;     :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;     :photos
  ;;     ({:description nil,
  ;;       :date-taken nil,
  ;;       :geo-data nil,
  ;;       :rotation -1,
  ;;       :width 0,
  ;;       :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;       :filename &quot;53460147147.jpg&quot;,
  ;;       :id &quot;53460147147&quot;,
  ;;       :out-file
  ;;       #object[java.io.File 0x163fa069 &quot;/tmp/72177720314024335/53460147147.jpg&quot;],
  ;;       :object
  ;;       #object[com.flickr4java.flickr.photos.Photo 0x4d361782 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;       :height 0}
  ;; [...]
  ;;      {:description nil,
  ;;       :date-taken nil,
  ;;       :geo-data nil,
  ;;       :rotation -1,
  ;;       :width 0,
  ;;       :title &quot;daniel-jennings-img-7554&quot;,
  ;;       :filename &quot;53460151727.jpg&quot;,
  ;;       :id &quot;53460151727&quot;,
  ;;       :out-file
  ;;       #object[java.io.File 0x289e2344 &quot;/tmp/72177720314024335/53460151727.jpg&quot;],
  ;;       :object
  ;;       #object[com.flickr4java.flickr.photos.Photo 0x805e360 &quot;com.flickr4java.flickr.photos.Photo@436e36e8&quot;],
  ;;       :height 0}),
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photosets.Photoset 0x19d70721 &quot;com.flickr4java.flickr.photosets.Photoset@19d70721&quot;],
  ;;     :out-dir #object[java.io.File 0x67b12ec4 &quot;/tmp/72177720314024335&quot;]}

  )
</code></pre><div class="markdown-heading"><h2 id="uploading-to-s3">Uploading to S3</h2><a href="#uploading-to-s3" class="anchor" aria-label="Permalink: Uploading to S3"><img src="assets/link.svg" /></a></div><p>We&apos;re most of the way there now. The final piece of the puzzle is taking our lovely directory full of downloaded files and putting it on S3, as described above. To accomplish this, let&apos;s avail ourselves of the Cognitect <a href="https://github.com/cognitect-labs/aws-api">aws-api</a> library that has <a href="tags/aws.html">served us
so well in the past</a>. First, let&apos;s add it to <code>deps.edn</code>:</p><pre><code class="language-clojure">{:paths [&quot;src&quot; &quot;dev&quot;]
 :deps {babashka/fs {:mvn/version &quot;0.4.19&quot;}
        com.cognitect.aws/api {:mvn/version &quot;0.8.686&quot;}
        com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.504&quot;}
        com.cognitect.aws/s3 {:mvn/version &quot;848.2.1413.0&quot;}
        com.flickr4java/flickr4java {:mvn/version &quot;3.0.1&quot;}}}
</code></pre><p>Sadly, we&apos;ll now need to restart our REPL. I really need to get hot reloading working! Sounds like a project for another day, though I&apos;m sure it will be <a href="tags/50-simple-steps.html">incredibly simple</a>...</p><p>In any case, having now restarted our REPL, let&apos;s create a <code>clickr.s3</code> namespace for ourselves:</p><pre><code class="language-clojure">(ns clickr.s3
  (:require [cognitect.aws.client.api :as aws]
            [clojure.string :as str]
            [clojure.java.io :as io])
  (:import (java.io ByteArrayInputStream)))
</code></pre><p>Now we&apos;ll need an S3 client. Let&apos;s follow the same pattern we used for our Flickr client:</p><pre><code class="language-clojure">(defn init-client [{:keys [aws-region] :as ctx}]
  (let [client (aws/client {:api :s3, :region aws-region})]
    (assoc ctx :s3 {:client client})))
</code></pre><p>Now we can actually use the same config as we used before! 🤯 We just need to add the AWS region in there, then we can call <code>init-client</code>:</p><pre><code class="language-clojure">
(comment

  (def config {:api-key &quot;beefface5678910&quot;
               :secret &quot;facecafe1234&quot;
               :aws-region &quot;eu-west-1&quot;})
  ;; =&gt; #&apos;clickr.s3/config

  (def ctx (init-client config))
  ;; =&gt; #&apos;clickr.s3/ctx

  (-&gt; ctx :s3 :client)
  ;; =&gt; #object[cognitect.aws.client.impl.Client 0x6b5a7704 &quot;cognitect.aws.client.impl.Client@6b5a7704&quot;]

  )
</code></pre><p>With a working client in hand, we can write a function to upload a photo. Let&apos;s follow the same pattern as <code>download-photo!</code>: do the side-effecting thing and then return the photo, assoc-ing in the S3 key where we uploaded it.</p><pre><code class="language-clojure">(defn upload-photo! [{:keys [s3 s3-bucket] :as ctx}
                     {:keys [out-file] :as photo}]
  (let [s3-key :???]
    (aws/invoke (:client s3)
                {:op :PutObject
                 :request {:Bucket s3-bucket
                           :Key s3-key
                           :Body :???}})
    (assoc photo :s3-key s3-key)))
</code></pre><p>OK, a couple things here. First, we need to add the S3 bucket to our context. That&apos;s easy enough:</p><pre><code class="language-clojure">
(comment

  (def config {:api-key &quot;beefface5678910&quot;
               :secret &quot;facecafe1234&quot;
               :aws-region &quot;eu-west-1&quot;
               :s3-bucket &quot;photos.jmglov.net&quot;})
  ;; =&gt; #&apos;clickr.s3/config

  (def ctx (init-client config))
  ;; =&gt; #&apos;clickr.s3/ctx

  ctx
  ;; =&gt; {:api-key &quot;beefface5678910&quot;,
  ;;     :secret &quot;facecafe1234&quot;,
  ;;     :aws-region &quot;eu-west-1&quot;,
  ;;     :s3-bucket &quot;photos.jmglov.net&quot;,
  ;;     :s3
  ;;     {:client
  ;;      #object[cognitect.aws.client.impl.Client 0xcd319cb &quot;cognitect.aws.client.impl.Client@cd319cb&quot;]}}

  )
</code></pre><p>Next, we need a way to read in the photo file. babashka.fs comes to the rescue again with a function called <code>read-all-bytes</code>! Let&apos;s require in babashka.fs:</p><pre><code class="language-clojure">(ns clickr.s3
  (:require [babashka.fs :as fs]
            [cognitect.aws.client.api :as aws]))
</code></pre><p>And now we can use that in our <code>upload-photo!</code> function:</p><pre><code class="language-clojure">(defn upload-photo! [{:keys [s3 s3-bucket] :as ctx}
                     {:keys [out-file] :as photo}]
  (let [s3-key :???]
    (aws/invoke (:client s3)
                {:op :PutObject
                 :request {:Bucket s3-bucket
                           :Key s3-key
                           :Body (fs/read-all-bytes out-file)}})
    (assoc photo :s3-key s3-key)))
</code></pre><p>Finally, we need to figure out what the S3 key should be. Using the convention from <code>download-album!</code>, we know the photo will be in a directory corresponding to the album ID. Let&apos;s use that as the key and prepend <code>clickr/</code> to it so that we don&apos;t pollute the top-level of the S3 bucket with a bunch of nonsense. We can grab the directory and filename using our old friend babashka.fs, of course:</p><pre><code class="language-clojure">(comment

  (def photo {:out-file &quot;/tmp/72177720314024335/53460151727.jpg&quot;})
  ;; =&gt; #&apos;clickr.s3/photo

  (-&gt; photo :out-file fs/file-name)
  ;; =&gt; &quot;53460151727.jpg&quot;

  (-&gt; photo :out-file fs/parent fs/file-name)
  ;; =&gt; &quot;72177720314024335&quot;

  )
</code></pre><p>Cool! With this, we have enough to construct the S3 key:</p><pre><code class="language-clojure">(defn upload-photo! [{:keys [s3 s3-bucket] :as ctx}
                     {:keys [out-file] :as photo}]
  (let [s3-key (format &quot;%s/%s/%s&quot;
                       &quot;clickr&quot;
                       (-&gt; photo :out-file fs/parent fs/file-name)
                       (-&gt; photo :out-file fs/file-name))]
    (aws/invoke (:client s3)
                {:op :PutObject
                 :request {:Bucket s3-bucket
                           :Key s3-key
                           :Body (fs/read-all-bytes out-file)}})
    (assoc photo :s3-key s3-key)))
</code></pre><p>We can try this out:</p><pre><code class="language-clojure">(comment

  (upload-photo! ctx photo)
  ;; =&gt; {:out-file &quot;/tmp/72177720314024335/53460151727.jpg&quot;,
  ;;     :s3-key &quot;clickr/72177720314024335/53460151727.jpg&quot;}

  )
</code></pre><p>And one should always trust but verify, right?</p><pre><code class="language-text">: jmglov@laurana; aws s3 ls s3://photos.jmglov.net/clickr/72177720314024335/53460151727.jpg
2024-01-17 12:06:17      90743 53460151727.jpg
</code></pre><p>Wow, that was surprisingly painless!</p><p>One thing that&apos;s bothering me a little, though, is that hardcoded &quot;clickr&quot; in there. Let&apos;s move that to the config like we did with the S3 bucket:</p><pre><code class="language-clojure">(defn upload-photo! [{:keys [s3 s3-bucket s3-prefix] :as ctx}
                     {:keys [out-file] :as photo}]
  (let [s3-key (format &quot;%s/%s/%s&quot;
                       s3-prefix
                       (-&gt; photo :out-file fs/parent fs/file-name)
                       (-&gt; photo :out-file fs/file-name))]
    (aws/invoke (:client s3)
                {:op :PutObject
                 :request {:Bucket s3-bucket
                           :Key s3-key
                           :Body (fs/read-all-bytes out-file)}})
    (assoc photo :s3-key s3-key)))

(comment

  (def config {:api-key &quot;beefface5678910&quot;
               :secret &quot;facecafe1234&quot;
               :aws-region &quot;eu-west-1&quot;
               :s3-bucket &quot;photos.jmglov.net&quot;
               :s3-prefix &quot;clickr&quot;})
  ;; =&gt; #&apos;clickr.s3/config

  (def ctx (init-client config))
  ;; =&gt; #&apos;clickr.s3/ctx

  ctx
  ;; =&gt; {:api-key &quot;beefface5678910&quot;,
  ;;     :secret &quot;facecafe1234&quot;,
  ;;     :aws-region &quot;eu-west-1&quot;,
  ;;     :s3-bucket &quot;photos.jmglov.net&quot;,
  ;;     :s3-prefix &quot;clickr&quot;,
  ;;     :s3
  ;;     {:client
  ;;      #object[cognitect.aws.client.impl.Client 0x2dc1f1c2 &quot;cognitect.aws.client.impl.Client@2dc1f1c2&quot;]}}

  (upload-photo! ctx photo)
  ;; =&gt; {:out-file &quot;/tmp/72177720314024335/53460151727.jpg&quot;,
  ;;     :s3-key &quot;clickr/72177720314024335/53460151727.jpg&quot;}

  )
</code></pre><p>Having done this, writing a function to upload all the photos in an album is quite straightforward:</p><pre><code class="language-clojure">(defn upload-album! [ctx {:keys [photos] :as album}]
  (update album :photos #(doall (map (partial upload-photo! ctx) %))))

(comment

  (def album-dir &quot;/tmp/72177720314024335&quot;)
  ;; =&gt; #&apos;clickr.s3/album-dir

  (def album {:id &quot;72177720314024335&quot;
              :out-dir album-dir
              :photos (-&gt;&gt; (fs/glob album-dir &quot;*&quot;)
                           (map (fn [out-file] {:out-file (str out-file)})))})
  ;; =&gt; #&apos;clickr.s3/album

  (upload-album! ctx album)
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :out-dir &quot;/tmp/72177720314024335&quot;,
  ;;     :photos
  ;;     ({:out-file &quot;/tmp/72177720314024335/53461405604.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53461405604.jpg&quot;}
  ;;      {:out-file &quot;/tmp/72177720314024335/53460163402.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53460163402.jpg&quot;}
  ;;      {:out-file &quot;/tmp/72177720314024335/53460161007.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53460161007.jpg&quot;}
  ;;      {:out-file &quot;/tmp/72177720314024335/53460147147.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53460147147.jpg&quot;}
  ;;      {:out-file &quot;/tmp/72177720314024335/53461214223.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53461214223.jpg&quot;}
  ;;      {:out-file &quot;/tmp/72177720314024335/53461091151.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53461091151.jpg&quot;}
  ;;      {:out-file &quot;/tmp/72177720314024335/53460151727.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53460151727.jpg&quot;}
  ;;      {:out-file &quot;/tmp/72177720314024335/53461088046.jpg&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53461088046.jpg&quot;})}

  )
</code></pre><div class="markdown-heading"><h2 id="tying-it-all-together">Tying it all together</h2><a href="#tying-it-all-together" class="anchor" aria-label="Permalink: Tying it all together"><img src="assets/link.svg" /></a></div><p>All of this looks reasonably reasonable, but our REPL-driven development of the <code>clickr.s3</code> namespace was pretty mocktacular, which fills me with a vague sense of unease. Let&apos;s make sure we can upload an honest to goodness album!</p><p>To make sure we don&apos;t have any cruft lying around in our REPL, let&apos;s create a new namespace and require in the flickr and s3 stuff:</p><pre><code class="language-clojure">(ns user
  (:require [clickr.flickr :as flickr]
            [clickr.s3 :as s3]))
</code></pre><p>We&apos;ll need some config, which we can just copy and paste straight from our experiments in the s3 namespace:</p><pre><code class="language-clojure">(comment

  (def config {:api-key &quot;beefface5678910&quot;
               :secret &quot;facecafe1234&quot;
               :aws-region &quot;eu-west-1&quot;
               :s3-bucket &quot;photos.jmglov.net&quot;
               :s3-prefix &quot;clickr&quot;})
  ;; =&gt; #&apos;user/config

  )
</code></pre><p>With this config firmly in hand, we can create flickr and s3 clients:</p><pre><code class="language-clojure">(comment

  (def ctx (-&gt; config flickr/init-client s3/init-client))
  ;; =&gt; #&apos;user/ctx

  ctx
  ;; =&gt; {:api-key &quot;beefface5678910&quot;,
  ;;     :secret &quot;facecafe1234&quot;,
  ;;     :aws-region &quot;eu-west-1&quot;,
  ;;     :s3-bucket &quot;photos.jmglov.net&quot;,
  ;;     :s3-prefix &quot;clickr&quot;,
  ;;     :flickr
  ;;     {:client
  ;;      #object[com.flickr4java.flickr.Flickr 0x2c4181a2 &quot;com.flickr4java.flickr.Flickr@2c4181a2&quot;],
  ;;      :auth-store
  ;;      #object[com.flickr4java.flickr.util.FileAuthStore 0x5368861c &quot;com.flickr4java.flickr.util.FileAuthStore@5368861c&quot;],
  ;;      :auth
  ;;      #object[com.flickr4java.flickr.auth.Auth 0x7c8ff0d6 &quot;com.flickr4java.flickr.auth.Auth@7c8ff0d6&quot;]},
  ;;     :s3
  ;;     {:client
  ;;      #object[cognitect.aws.client.impl.Client 0x5b35646d &quot;cognitect.aws.client.impl.Client@5b35646d&quot;]}}

  )
</code></pre><p>Download an album:</p><pre><code class="language-clojure">(comment

  (def album (-&gt;&gt; (flickr/get-albums&apos; ctx)
                  first
                  (flickr/download-album!&apos; ctx)))
  ;; =&gt; #&apos;user/album

  (-&gt;&gt; album :photos (map :out-file))
  ;; =&gt; (#object[java.io.File 0x1c2cd5ae &quot;/tmp/72177720314024335/53460147147.jpg&quot;]
  ;;     #object[java.io.File 0x1678a01 &quot;/tmp/72177720314024335/53461405604.jpg&quot;]
  ;;     #object[java.io.File 0x4f708220 &quot;/tmp/72177720314024335/53461091151.jpg&quot;]
  ;;     #object[java.io.File 0x75723234 &quot;/tmp/72177720314024335/53461088046.jpg&quot;]
  ;;     #object[java.io.File 0x6cace2fd &quot;/tmp/72177720314024335/53460163402.jpg&quot;]
  ;;     #object[java.io.File 0x51265aeb &quot;/tmp/72177720314024335/53460161007.jpg&quot;]
  ;;     #object[java.io.File 0x1a0ca36d &quot;/tmp/72177720314024335/53461214223.jpg&quot;]
  ;;     #object[java.io.File 0x7e8bc18a &quot;/tmp/72177720314024335/53460151727.jpg&quot;])

  )
</code></pre><p>And upload it to S3!</p><pre><code class="language-clojure">(comment

  (s3/upload-album! ctx album)
  ;; =&gt; {:id &quot;72177720314024335&quot;,
  ;;     :title &quot;clickr demo&quot;,
  ;;     :description &quot;Photo album demo for my clickr blog post&quot;,
  ;;     :photos
  ;;     ({:description nil,
  ;;       :date-taken nil,
  ;;       :geo-data nil,
  ;;       :rotation -1,
  ;;       :width 0,
  ;;       :title &quot;sean-hargreaves-phoenix-new-5-final-a&quot;,
  ;;       :filename &quot;53460147147.jpg&quot;,
  ;;       :id &quot;53460147147&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53460147147.jpg&quot;,
  ;;       :out-file
  ;;       #object[java.io.File 0x1c2cd5ae &quot;/tmp/72177720314024335/53460147147.jpg&quot;],
  ;;       :object
  ;;       #object[com.flickr4java.flickr.photos.Photo 0x3bbff9e1 &quot;com.flickr4java.flickr.photos.Photo@14ea992b&quot;],
  ;;       :height 0}
  ;; [...]
  ;;      {:description nil,
  ;;       :date-taken nil,
  ;;       :geo-data nil,
  ;;       :rotation -1,
  ;;       :width 0,
  ;;       :title &quot;daniel-jennings-img-7554&quot;,
  ;;       :filename &quot;53460151727.jpg&quot;,
  ;;       :id &quot;53460151727&quot;,
  ;;       :s3-key &quot;clickr/72177720314024335/53460151727.jpg&quot;,
  ;;       :out-file
  ;;       #object[java.io.File 0x7e8bc18a &quot;/tmp/72177720314024335/53460151727.jpg&quot;],
  ;;       :object
  ;;       #object[com.flickr4java.flickr.photos.Photo 0x1e20bd4c &quot;com.flickr4java.flickr.photos.Photo@436e36e8&quot;],
  ;;       :height 0}),
  ;;     :object
  ;;     #object[com.flickr4java.flickr.photosets.Photoset 0x6411aa2d &quot;com.flickr4java.flickr.photosets.Photoset@6411aa2d&quot;],
  ;;     :out-dir #object[java.io.File 0x377eb990 &quot;/tmp/72177720314024335&quot;]}

  )
</code></pre><p>And check that all is right with the world:</p><pre><code class="language-text">: jmglov@laurana; aws s3 ls s3://photos.jmglov.net/clickr/72177720314024335/
2024-01-17 12:48:26     125643 53460147147.jpg
2024-01-17 12:48:29      90743 53460151727.jpg
2024-01-17 12:48:28      88417 53460161007.jpg
2024-01-17 12:48:28     185725 53460163402.jpg
2024-01-17 12:48:27     178392 53461088046.jpg
2024-01-17 12:48:27     106074 53461091151.jpg
2024-01-17 12:48:29      88013 53461214223.jpg
2024-01-17 12:48:26      98035 53461405604.jpg
</code></pre><p>![A woman on a beach at sunrise with her head thrown back, saying &quot;Victory&quot;][victory]</p><p>But wait just a second here...</p><div class="markdown-heading"><h2 id="the-unbearable-lightness-of-being-dissatisfied">The unbearable lightness of being dissatisfied</h2><a href="#the-unbearable-lightness-of-being-dissatisfied" class="anchor" aria-label="Permalink: The unbearable lightness of being dissatisfied"><img src="assets/link.svg" /></a></div><p>![A person sitting alone, holding their face in their hands][sadness] [sadness]:[assets/2024-01-17-sadness.jpg &quot;Sadness!&quot;]</p><p>Much like Angelica Schuyler, I&apos;ll never be satisfied, because having to browse my albums with the S3 console is kind of a let down, not to mention that this:</p><p>![The Flickr site, displaying the photos in the clickr demo album][flickralbum] [flickralbum]:[assets/2024-01-17-album-flickr.png &quot;OMG 🤩&quot;]</p><p>looks way better than this:</p><p>![The AWS S3 console, displaying the files we uploaded as a table of text][s3album] [s3album]:[assets/2024-01-17-s3-console.png &quot;Sadness!&quot;]</p><p>What is a young man to do? Well, you&apos;ll have to stick around for the next instalment of <a href="tags/clickr.html">this exciting series</a>, which I promise I&apos;ll actually write, because I&apos;ve started writing it already and... um... trust me?</p><p>Part 2: <a href="2024-01-22-clickr-goes-fe.html">clickr goes frontend</a></p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2023-11-12-awno-here-we-go.html</id>
    <link href="https://jmglov.net/blog/2023-11-12-awno-here-we-go.html"/>
    <title>Awno! Here we go!</title>
    <updated>2023-11-12T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><div class="markdown-heading"><h2 id="admission-of-guilt">Admission of guilt</h2><a href="#admission-of-guilt" class="anchor" aria-label="Permalink: Admission of guilt"><img src="assets/link.svg" /></a></div><p>Between the writing of the previous post in this series and now, two things happened:</p><ol start="1"><li>I got distracted by other stuff</li><li>grzm <a href="https://github.com/grzm/awyeah-api/issues/8#issuecomment-1820183384">fixed the
   issue</a> properly upstream! 🎉</li></ol><p>I decided to go ahead and post this for the record, just in case there&apos;s anything useful for anyone in there, and also to clear my palate (and my conscience) for some new blogging. 😉</p><p>So here you go:</p><div class="markdown-heading"><h2 id="just-for-the-record">Just for the record</h2><a href="#just-for-the-record" class="anchor" aria-label="Permalink: Just for the record"><img src="assets/link.svg" /></a></div><p>In <a href="2023-11-11-awno-api.html">last week&apos;s exciting instalment of Josh does something
inadvisable</a>, we had finished smooshing <a href="https://github.com/grzm/awyeah-api">awyeah-api</a> into an unholy fork of <a href="https://github.com/cognitect-labs/aws-api">aws-api</a> to make something completely horrific: <a href="https://github.com/jmglov/awno-api">awno-api</a>. And by &quot;finished&quot;, I mean &quot;wrote some code and assumed that it will obviously work&quot;.</p><p>Of course, even at my most hubristic, I realise that assuming something will work just because I wrote it is somewhat... irresponsible. So I guess we&apos;d better actually try it out before committing to main.</p><div class="markdown-heading"><h2 id="testing,-testing...-is-this-thing-on?">Testing, testing... is this thing on?</h2><a href="#testing,-testing...-is-this-thing-on?" class="anchor" aria-label="Permalink: Testing, testing... is this thing on?"><img src="assets/link.svg" /></a></div><p>awyeah-api has an intriguing <a href="https://github.com/grzm/awyeah-api/blob/main/bin/test">bin/tests</a>, which we&apos;ve previously copied, so let&apos;s do a quick replace all of <code>com.grzm.awyeah</code> with <code>net.jmglov.awno</code>:</p><pre><code class="language-clj">#!/usr/bin/env bash

set -euo pipefail

repo_root=&quot;$(git rev-parse --show-toplevel)&quot;

cd &quot;${repo_root}&quot;
if [[ -z ${SKIP_BB+x} ]] ; then
    echo &quot;bb tests&quot;
    bb --main net.jmglov.awno.test/run-tests
else
    echo &quot;skipping bb tests&quot;
fi

echo
echo &quot;clj tests&quot;
clj -X:dev:test:clj
</code></pre><p>Then we&apos;ll need the actual <code>net.jmglov.awno.test</code> namespace, so we&apos;ll grab <a href="https://github.com/grzm/awyeah-api/blob/main/test/src/com/grzm/awyeah/test.cljc">test/src/com/grzm/awyeah/test.cljc</a>:</p><pre><code class="language-text">cp ../awyeah-api/test/src/com/grzm/awyeah/test.cljc test/src/net/jmglov/awno/
</code></pre><p>Then do the usual replace all of <code>com.grzm.awyeah</code> with <code>net.jmglov.awno</code>:</p><pre><code class="language-clojure">(ns net.jmglov.awno.test
  (:require
   [clojure.pprint :as pprint]
   [clojure.test :as test]))

#?(:bb (taoensso.timbre/set-level! :info))

(def test-namespaces
  &apos;[net.jmglov.awno.client.api.localstack-test
    net.jmglov.awno.client.api-test
    net.jmglov.awno.client.impl-test
    net.jmglov.awno.client.test-double-test
    net.jmglov.awno.config-test
    net.jmglov.awno.credentials-test
    net.jmglov.awno.ec2-metadata-utils-test
    net.jmglov.awno.endpoint-test
    net.jmglov.awno.interceptors-test
    net.jmglov.awno.protocols-test
    net.jmglov.awno.protocols.rest-test
    net.jmglov.awno.region-test
    net.jmglov.awno.retry-test
    net.jmglov.awno.shape-test
    ;; omitting net.jmglov.awno.signers-test
    ;; Requires org.apache.commons.io.input.BOMInputStream which I haven&apos;t figured out
    ;; how to port to something compatible with Babashka
    net.jmglov.awno.util-test])

(defn run-tests
  ([]
   (run-tests {:test-namespaces test-namespaces}))
  ([{nses :test-namespaces}]
   (dorun (map require nses))
   (let [res (apply test/run-tests nses)]
     (pprint/pprint res)
     (when (-&gt;&gt; ((juxt :fail :error) res)
                (some #(pos? %)))
       (System/exit 1)))))
</code></pre><p>And then give it a whirl!</p><pre><code class="language-text">: awno-api; bin/test 
bb tests
----- Error --------------------------------------------------------------------
Type:     java.lang.Exception
Message:  Could not find namespace: net.jmglov.awno.client.api.localstack-test.
Location: /home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/test.cljc:32:4
</code></pre><p>Ah yes, another reason to hate <a href="https://localstack.cloud/">LocalStack</a>. 😠</p><p>LocalStack claims to be &quot;A fully functional local cloud stack [which enables you
to] develop and test your cloud and serverless apps offline!&quot; In my experience, it is a somewhat functional local cloud stack which enables me to develop and test my cloud and serverless apps offline—as long as I limit don&apos;t use any services that aren&apos;t supported by LocalStack (to be fair, the <a href="https://docs.localstack.cloud/user-guide/aws/feature-coverage/">list of supported
services</a> is growing), and don&apos;t expect the local service to actually behave like the real one. 😅</p><p>Before continuing with my shit-talking, let me just insert my standard disclaimer here:</p><p>{thing-which-i-hate} is a perfectly serviceable piece of technology, which many people find useful. I&apos;m not any smarter than those people, and their choice to use {thing-which-i-hate} is perfectly valid. All the vitriol I pour on {thing-which-i-hate} is tongue-in-cheek and should be taken with a serious grain of salt, in full knowledge that I often don&apos;t know what I&apos;m talking about, because my experience isn&apos;t representative of all use cases, and so on and so forth.</p><p>OK, having gotten that out of the way, let&apos;s remove all references to the odious LocalStack and move on with our lives!</p><pre><code class="language-clojure">(def test-namespaces
  &apos;[net.jmglov.awno.client.api-test
    net.jmglov.awno.client.impl-test
    net.jmglov.awno.client.test-double-test
    net.jmglov.awno.config-test
    net.jmglov.awno.credentials-test
    net.jmglov.awno.ec2-metadata-utils-test
    net.jmglov.awno.endpoint-test
    net.jmglov.awno.interceptors-test
    net.jmglov.awno.protocols-test
    net.jmglov.awno.protocols.rest-test
    net.jmglov.awno.region-test
    net.jmglov.awno.retry-test
    net.jmglov.awno.shape-test
    ;; omitting net.jmglov.awno.signers-test
    ;; Requires org.apache.commons.io.input.BOMInputStream which I haven&apos;t figured out
    ;; how to port to something compatible with Babashka
    net.jmglov.awno.util-test])
</code></pre><p>If at first you don&apos;t succeed, dust yourself off and try again (you gotta dust it off and try again):</p><pre><code class="language-text">: awno-api; bin/test 
bb tests
----- Error --------------------------------------------------------------------
Type:     java.lang.Exception
Message:  Could not find namespace: net.jmglov.awno.client.api-test.
Location: /home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/test.cljc:32:4
</code></pre><p>Oh come on!</p><p>In all the <code>git mv</code> nonsense, we probably just misplaced a file or two, so let&apos;s see if we can track this test down:</p><pre><code class="language-text">: awno-api; find test/src/ -name api_test.clj
test/src/net/jmglov/awno/api_test.clj
</code></pre><p>Aha! There it is. Before getting too cocky, let&apos;s see which other test files we&apos;re missing:</p><pre><code class="language-text">: awno-api; bb -e &apos;
&gt; (def base-dir &quot;test/src&quot;)
(with-open [r (io/reader (format &quot;%s/net/jmglov/awno/test.cljc&quot; base-dir))]
  (let [namespaces
        (-&gt;
         (-&gt;&gt; (line-seq r)
              (drop-while #(not (str/starts-with? % &quot;(def test-namespaces&quot;)))
              (take-while not-empty)
              (str/join &quot;\n&quot;)
              edn/read-string)
         (nth 3))
        filenames (-&gt;&gt; namespaces
                       (map #(-&gt;&gt; (-&gt; %
                                      (str/replace &quot;.&quot; &quot;/&quot;)
                                      (str/replace &quot;-&quot; &quot;_&quot;))
                                  (format &quot;%s/%s.clj&quot; base-dir))))
        missing (remove fs/exists? filenames)]
    (println (str/join &quot;\n&quot; missing))))
&apos;
</code></pre><p>Babashka helpfully tells us:</p><pre><code class="language-text">test/src/net/jmglov/awno/client/api_test.clj
test/src/net/jmglov/awno/client/impl_test.clj
test/src/net/jmglov/awno/client/test_double_test.clj
</code></pre><p>I bet we can even track down those missing files!</p><pre><code class="language-text">: awno-api; bb -e &apos;
(def base-dir &quot;test/src&quot;)
(with-open [r (io/reader (format &quot;%s/net/jmglov/awno/test.cljc&quot; base-dir))]
  (let [namespaces
        (-&gt;
         (-&gt;&gt; (line-seq r)
              (drop-while #(not (str/starts-with? % &quot;(def test-namespaces&quot;)))
              (take-while not-empty)
              (str/join &quot;\n&quot;)
              edn/read-string)
         (nth 3))
        filenames (-&gt;&gt; namespaces
                       (map #(-&gt;&gt; (-&gt; %
                                      (str/replace &quot;.&quot; &quot;/&quot;)
                                      (str/replace &quot;-&quot; &quot;_&quot;))
                                  (format &quot;%s/%s.clj&quot; base-dir))))
        missing (remove fs/exists? filenames)
        found (-&gt;&gt; missing
                   (map (fn [mf]
                          [mf (-&gt;&gt; (fs/file-name mf)
                                   (format &quot;**/%s&quot;)
                                   (fs/glob base-dir)
                                   first
                                   str)])))]
    (doseq [[missing-file found-file] found]
      (println found-file &quot;-&gt;&quot; missing-file))))
&apos;
</code></pre><p>And look what we have here:</p><pre><code class="language-text">test/src/net/jmglov/awno/api_test.clj -&gt; test/src/net/jmglov/awno/client/api_test.clj
test/src/cognitect/client/impl_test.clj -&gt; test/src/net/jmglov/awno/client/impl_test.clj
test/src/cognitect/client/test_double_test.clj -&gt; test/src/net/jmglov/awno/client/test_double_test.clj
</code></pre><p>Yup, got them all. Now to put them where they go and fix the namespaces:</p><pre><code class="language-text">(def base-dir &quot;test/src&quot;)
(with-open [r (io/reader (format &quot;%s/net/jmglov/awno/test.cljc&quot; base-dir))]
  (let [namespaces
        (-&gt;
         (-&gt;&gt; (line-seq r)
              (drop-while #(not (str/starts-with? % &quot;(def test-namespaces&quot;)))
              (take-while not-empty)
              (str/join &quot;\n&quot;)
              edn/read-string)
         (nth 3))
        filenames (-&gt;&gt; namespaces
                       (map (fn [ns*]
                              [ns*
                               (-&gt;&gt; (-&gt; ns*
                                        (str/replace &quot;.&quot; &quot;/&quot;)
                                        (str/replace &quot;-&quot; &quot;_&quot;))
                                    (format &quot;%s/%s.clj&quot; base-dir))])))
        missing (remove (fn [[_ filename]] (fs/exists? filename)) filenames)
        found (-&gt;&gt; missing
                   (map (fn [[ns* filename]]
                          {:ns* ns*
                           :target filename
                           :source (-&gt;&gt; (fs/file-name filename)
                                        (format &quot;**/%s&quot;)
                                        (fs/glob base-dir)
                                        first
                                        str)})))]
    (doseq [{:keys [ns* source target]} found
            :let [fixed-ns
                  (with-open [r (io/reader source)]
                    (-&gt;&gt; (line-seq r)
                         (map (fn [line]
                                (if (re-matches #&quot;^[(]ns .+$&quot; line)
                                  (str &quot;(ns &quot; ns*)
                                  line)))
                         (str/join &quot;\n&quot;)))]]
      (spit source fixed-ns)
      (println &quot;Moving&quot; source &quot;-&gt;&quot; target)
      (fs/create-dirs (fs/parent target))
      (fs/move source target))))
</code></pre><p>Quoth Babashka:</p><pre><code class="language-text">Moving test/src/net/jmglov/awno/api_test.clj -&gt; test/src/net/jmglov/awno/client/api_test.clj
Moving test/src/cognitect/client/impl_test.clj -&gt; test/src/net/jmglov/awno/client/impl_test.clj
Moving test/src/cognitect/client/test_double_test.clj -&gt; test/src/net/jmglov/awno/client/test_double_test.clj
</code></pre><p>Lets open up <code>test/src/net/jmglov/awno/client/api_test.clj</code> and see what we&apos;ve got:</p><pre><code class="language-clojure">(ns net.jmglov.awno.client.api-test
  (:require [clojure.datafy :as datafy]
            [clojure.test :as t :refer [deftest is testing]]
            [net.jmglov.awno.client.api :as aws]
            [net.jmglov.awno.client.protocol :as client.protocol]
            [net.jmglov.awno.client.shared :as shared]
            [net.jmglov.awno.http :as http]))

;; [...]
</code></pre><p>Wow! Looking good!</p><div class="markdown-heading"><h2 id="testing,-testing,-one-two...">Testing, testing, one two...</h2><a href="#testing,-testing,-one-two..." class="anchor" aria-label="Permalink: Testing, testing, one two..."><img src="assets/link.svg" /></a></div><p>Having moved the furniture around, let&apos;s try running the tests again:</p><pre><code class="language-text">: awno-api; bin/test 
bb tests
----- Error --------------------------------------------------------------------
Type:     java.lang.Exception
Message:  Could not find namespace: net.jmglov.awno.dynaload.
Location: /home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/client/validation.clj:6:3
</code></pre><p>OMG, it looks like there was another dynaload that we missed in our previous babashkafication of aws-api. Let&apos;s open <code>src/net/jmglov/awno/client/validation.clj</code> see what&apos;s going on.</p><p>It looks like dynaload is being used for the following three vars:</p><pre><code class="language-clojure">(def ^:private registry-ref (delay (dynaload/load-var &apos;clojure.spec.alpha/registry)))
(def ^:private valid?-ref (delay (dynaload/load-var &apos;clojure.spec.alpha/valid?)))
(def ^:private explain-data-ref (delay (dynaload/load-var &apos;clojure.spec.alpha/explain-data)))
</code></pre><p>According to <a href="https://github.com/grzm/awyeah-api/blob/main/docs/porting-decisions.markdown">porting-decisions.markdown</a>:</p><blockquote><p>The aws-api library defines the <code>cognitect.dynaload/load-var</code> function to dynamically require and resolve the var referenced by a given symbol. Clojure 1.10 provides the same functionality with the <code>requiring-resolve</code> function. Given that <code>requiring-resolve</code> is compiled into the babashka image, I&apos;ve chosen to replace <code>load-var</code> with <code>requiring-resolve</code> rather than relying on <a href="https://github.com/babashka/sci">sci</a> to interpret <code>load-var</code> at run-time.</p></blockquote><p>Cool, so let&apos;s replace all occurrences of <code>dynaload/load-var</code> with <code>requiring-resolve</code>, then rip dynaload out of the <code>ns</code> form, leaving us with this:</p><pre><code class="language-clojure">;; Copyright (c) Cognitect, Inc.
;; All rights reserved.

(ns ^:skip-wiki net.jmglov.awno.client.validation
  &quot;For internal use. Don&apos;t call directly.&quot;
  (:require [net.jmglov.awno.client.protocol :as client.protocol]
            [net.jmglov.awno.service :as service]))

(set! *warn-on-reflection* true)

(defn validate-requests?
  &quot;For internal use. Don&apos;t call directly.&quot;
  [client]
  (some-&gt; client client.protocol/-get-info :validate-requests? deref))

(def ^:private registry-ref (delay (requiring-resolve &apos;clojure.spec.alpha/registry)))
(defn registry
  &quot;For internal use. Don&apos;t call directly.&quot;
  [&amp; args] (apply @registry-ref args))

(def ^:private valid?-ref (delay (requiring-resolve &apos;clojure.spec.alpha/valid?)))
(defn valid?
  &quot;For internal use. Don&apos;t call directly.&quot;
  [&amp; args] (apply @valid?-ref args))

(def ^:private explain-data-ref (delay (requiring-resolve &apos;clojure.spec.alpha/explain-data)))
(defn explain-data
  &quot;For internal use. Don&apos;t call directly.&quot;
  [&amp; args] (apply @explain-data-ref args))

(defn request-spec
  &quot;For internal use. Don&apos;t call directly.&quot;
  [service op]
  (when-let [spec (service/request-spec-key service op)]
    (when (contains? (-&gt; (registry) keys set) spec)
      spec)))

(defn invalid-request-anomaly
  &quot;For internal use. Don&apos;t call directly.&quot;
  [spec request]
  (assoc (explain-data spec request)
         :cognitect.anomalies/category :cognitect.anomalies/incorrect))

(defn unsupported-op-anomaly
  &quot;For internal use. Don&apos;t call directly.&quot;
  [service op]
  {:cognitect.anomalies/category :cognitect.anomalies/unsupported
   :cognitect.anomalies/message &quot;Operation not supported&quot;
   :service (keyword (service/service-name service))
   :op op})
</code></pre><p>Let&apos;s go ahead and search the project for any other occurrences of dynaload that we may have missed. Ah-hah! <code>net.jmglov.awno.client.api</code> is also dynaloading. We can repeat the dance of replacing <code>dynaload/load-var</code> with <code>requiring-resolve</code>, then removing it from the <code>ns</code> form, then evaluating the buffer:</p><pre><code class="language-text">clojure.lang.ExceptionInfo: defrecord/deftype currently only support protocol implementations, {:file &quot;/home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/client/impl.clj&quot;}
found: clojure.lang.IObj
</code></pre><p>Yikes! Taking a look at <code>impl.clj</code>, this seems to be the problem:</p><pre><code class="language-clojure">(deftype Client [client-meta info]
  clojure.lang.IObj
  (meta [_] @client-meta)
  (withMeta [this m] (swap! client-meta merge m) this)

  ILookup
  (valAt [this k]
    (.valAt this k nil))

  (valAt [this k default]
    (case k
      :api
      (-&gt; info :service :metadata :net.jmglov.awno/service-name)
      :region
      (some-&gt; info :region-provider region/fetch)
      :endpoint
      (some-&gt; info :endpoint-provider (endpoint/fetch (.valAt this :region)))
      :credentials
      (some-&gt; info :credentials-provider credentials/fetch)
      :service
      (some-&gt; info :service (select-keys [:metadata]))
      :http-client
      (:http-client info)
      default))

  client.protocol/Client
  (-get-info [_] info)

  ;; [...]
  )
</code></pre><p><code>Client</code> implements the <code>clojure.lang.IObj</code> and <code>ILookup</code> interfaces, and Babashka only supports implementing protocols.</p><p>Let&apos;s see how awyeah-api handles this by looking at <a href="https://github.com/grzm/awyeah-api/blob/main/src/com/grzm/awyeah/client/impl.clj">src/com/grzm/awyeah/client/impl.clj</a>:</p><pre><code class="language-clojure">(defrecord Client [info]
  client.protocol/Client
  (-get-info [_] info)

  ;; [...]
  )

;; -&gt;Client is intended for internal use
(alter-meta! #&apos;-&gt;Client assoc :skip-wiki true)

(defn client [client-meta info]
  (let [region (some-&gt; info :region-provider region/fetch)]
    (-&gt; (with-meta (-&gt;Client info) @client-meta)
        (assoc :region region
               :endpoint (some-&gt; info :endpoint-provider (endpoint/fetch region))
               :credentials (some-&gt; info :credentials-provider credentials/fetch)
               :service (some-&gt; info :service (select-keys [:metadata]))
               :http-client (:http-client info)))))
</code></pre><p>Interesting. We can do the same thing, transforming <code>deftype</code> into <code>defrecord</code> and removing the <code>clojure.lang.IObj</code> and <code>ILookup</code> interface methods:</p><pre><code class="language-clojure">(defrecord Client [info]
  client.protocol/Client
  (-get-info [_] info)

  (-invoke [client op-map]
    (a/&lt;!! (client.protocol/-invoke-async client op-map)))

  (-invoke-async [client {:keys [op request] :as op-map}]
    (let [result-chan (or (:ch op-map) (a/promise-chan))
          {:keys [service retriable? backoff]} (client.protocol/-get-info client)
          spec (and (validation/validate-requests? client) (validation/request-spec service op))]
      (cond
        (not (contains? (:operations service) (:op op-map)))
        (a/put! result-chan (validation/unsupported-op-anomaly service op))

        (and spec (not (validation/valid? spec request)))
        (a/put! result-chan (validation/invalid-request-anomaly spec request))

        :else
        ;; In case :body is an InputStream, ensure that we only read
        ;; it once by reading it before we send it to with-retry.
        (let [req (-&gt; (aws.protocols/build-http-request service op-map)
                      (update :body util/-&gt;bbuf))]
          (retry/with-retry
            #(send-request client op-map req)
            result-chan
            (or (:retriable? op-map) retriable?)
            (or (:backoff op-map) backoff))))

      result-chan))

  (-stop [aws-client]
    (let [{:keys [http-client]} (client.protocol/-get-info aws-client)]
      (when-not (#&apos;shared/shared-http-client? http-client)
        (http/stop http-client)))))
</code></pre><p>Now we need to add a <code>client</code> function to return a <code>Client</code> record to callers. In the <code>deftype</code> version, fields are implemented like this:</p><pre><code class="language-clojure">  (valAt [this k default]
    (case k
      :api
      (-&gt; info :service :metadata :net.jmglov.awno/service-name)
      :region
      (some-&gt; info :region-provider region/fetch)
      :endpoint
      (some-&gt; info :endpoint-provider (endpoint/fetch (.valAt this :region)))
      :credentials
      (some-&gt; info :credentials-provider credentials/fetch)
      :service
      (some-&gt; info :service (select-keys [:metadata]))
      :http-client
      (:http-client info)
      default))
</code></pre><p>Let&apos;s follow the lead of awyeah-api and use a Clojure map to do the same:</p><pre><code class="language-clojure">(defn client [client-meta info]
  (let [region (some-&gt; info :region-provider region/fetch)]
    (-&gt; (with-meta (-&gt;Client info) @client-meta)
        (assoc :api (-&gt; info :service :metadata :cognitect.aws/service-name)
               :region region
               :endpoint (some-&gt; info :endpoint-provider (endpoint/fetch region))
               :credentials (some-&gt; info :credentials-provider credentials/fetch)
               :service (some-&gt; info :service (select-keys [:metadata]))
               :http-client (:http-client info)))))
</code></pre><p>We also need to update the <code>-invoke</code> method of <code>Client</code> to call <code>-invoke-async</code> as a function, not an instance method:</p><pre><code class="language-clojure">  (-invoke [client op-map]
    (a/&lt;!! (client.protocol/-invoke-async client op-map)))
</code></pre><p>Note the <code>:api</code> key we added to the map, which isn&apos;t present in the awyeah-api version. Taking a look at <a href="https://github.com/cognitect-labs/aws-api/blob/main/src/cognitect/aws/client/impl.clj">src/cognitect/aws/client/impl.clj</a> in aws-api with <code>magit-blame</code>, we can see why:</p><pre><code class="language-text">  (valAt [this k default]
    (case k
David Chelimsky	2022-12-01 20:31 add keyword access to :api key on client
      :api
      (-&gt; info :service :metadata :cognitect.aws/service-name)
Maria Clara Crespo	2022-09-12 11:23 introduce test double client
      :region
      (some-&gt; info :region-provider region/fetch)
</code></pre><p>Since this change is clearly intentional, we ported it over, changing the <code>:net.jmglov.awno/service-name</code> keyword (which resulted from our <code>projectile-replace cognitect.aws -&gt; net.jmglov.awno</code>) back to <code>:cognitect.aws/service-name</code>.</p><p>And now that we&apos;ve replaced the type with a record, we need to make sure it can only be instantiated using our <code>client</code> function. Let&apos;s make <code>-&gt;Client</code> private:</p><pre><code class="language-clojure">;; -&gt;Client is intended for internal use
(alter-meta! #&apos;-&gt;Client assoc :skip-wiki true)
</code></pre><p>Now, we need to track down all callers of <code>-&gt;Client</code> outside this namespace. There only turns out to be one, in <code>net.jmglov.awno.http-client</code>:</p><pre><code class="language-clojure">    (client/-&gt;Client
     (atom {&apos;clojure.core.protocols/datafy (fn [c]
                                             (let [info (client.protocol/-get-info c)
                                                   region (region/fetch (:region-provider info))
                                                   endpoint (endpoint/fetch (:endpoint-provider info) region)]
                                               (-&gt; info
                                                   (select-keys [:service])
                                                   (assoc :api (-&gt; info :service :metadata :cognitect.aws/service-name))
                                                   (assoc :region region :endpoint endpoint)
                                                   (update :endpoint select-keys [:hostname :protocols :signatureVersions])
                                                   (update :service select-keys [:metadata])
                                                   (assoc :ops (ops c)))))})
     {:service              service
      :retriable?           (or retriable? retry/default-retriable?)
      :backoff              (or backoff retry/default-backoff)
      :http-client          http-client
      :endpoint-provider    endpoint-provider
      :region-provider      region-provider
      :credentials-provider credentials-provider
      :validate-requests?   (atom nil)})
</code></pre><p>Making the change is as easy as replacing <code>client/-&gt;Client</code> with <code>client/client</code>! Oh yeah, and replacing that <code>:net.jmglov.awno/service-name</code> with <code>:cognitect.aws/service-name</code>.</p><p>However, when we eval the buffer, we get another nasty dynaload-related surprise:</p><pre><code>clojure.lang.ExceptionInfo: Could not resolve symbol: dynaload/load-ns
{:type :sci/error,
 :file &quot;/home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/client/api.clj&quot;,
 :phase &quot;analysis&quot;}
</code></pre><p>Apparently there&apos;s more to dynaload than just <code>load-var</code>. And strangely enough, <code>com.grzm.awyeah.client.api</code> contains a dynaload require:</p><pre><code class="language-clojure">(ns com.grzm.awyeah.client.api
  &quot;API functions for using a client to interact with AWS services.&quot;
  (:require
   ;; [...]
   [com.grzm.awyeah.dynaload :as dynaload]
   ;; [...]
   [com.grzm.awyeah.signers]))
</code></pre><p>No mention of this was made in <code>porting-decisions.markdown</code>. 😭</p><p>Let&apos;s just copy <code>com.grzm.awyeah.dynaload</code> and jmglov-ify it:</p><pre><code class="language-clojure">;; Copyright (c) Cognitect, Inc.
;; All rights reserved.

(ns ^:skip-wiki net.jmglov.awno.dynaload)

(set! *warn-on-reflection* true)

(defonce ^:private dynalock (Object.))

(defn load-ns [ns]
  (locking dynalock
    (require (symbol ns))))
</code></pre><p>With that done, <code>net.jmglov.awno.client.api</code> evaluates with no errors! 🏆</p><div class="markdown-heading"><h2 id="testing,-testing,-one-two-three...">Testing, testing, one two three...</h2><a href="#testing,-testing,-one-two-three..." class="anchor" aria-label="Permalink: Testing, testing, one two three..."><img src="assets/link.svg" /></a></div><p>Surely our tests will run now! Right?</p><pre><code class="language-text">: awno-api; bin/test
bb tests
----- Error --------------------------------------------------------------------
Type:     java.lang.Exception
Message:  Could not find namespace: clojure.test.check.clojure-test.
Location: /home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/client/impl_test.clj:3:3
</code></pre><p>Urk! Looks like awyeah-api didn&apos;t include property-based tests. Let&apos;s add <a href="https://github.com/clojure/test.check">test.check</a> to our <code>bb.edn</code> and see what happens. And don&apos;t worry, we&apos;re only going to end up with <code>test.check</code> added to our runtime dependencies when running <code>bb</code> directly, not when using <code>awno-api</code> as a dependency, since <code>deps.edn</code> is used in that case, not <code>bb.edn</code>. This is important for me, since my interest in awyeah-api is solely as a way to use AWS stuff from <a href="https://github.com/jmglov/blambda">blambda</a>, I don&apos;t want extra stuff taking up space in my deps layer. Not to mention having test dependencies in your production code is just icky. 😅</p><p>So anyway, whacking</p><pre><code class="language-clojure">org.clojure/test.check {:mvn/version &quot;1.1.1&quot;}
</code></pre><p>into the <code>:deps</code> map then re-running the tests yields the following:</p><pre><code class="language-text">: awno-api; bin/test
bb tests
----- Error --------------------------------------------------------------------
Type:     java.lang.Exception
Message:  Could not find namespace: cognitect.client.impl-test.
Location: /home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/client/test_double_test.clj:3:3
</code></pre><p>Oops. Looks like <code>cognitect.client</code> is in need of some <code>projectile-replace</code>. Replacing it with <code>net.jmglov.awno.client</code> should do the trick.</p><pre><code class="language-text">: awno-api; bin/test
bb tests
----- Error --------------------------------------------------------------------
Type:     clojure.lang.ExceptionInfo
Message:  defrecord/deftype currently only support protocol implementations, found: ILookup
Data:     {:type :sci/error, :line 23, :column 1, :file &quot;/home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/client/test_double.clj&quot;}
Location: /home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/client/test_double.clj:23:1
Phase:    macroexpand
</code></pre><p>Urk! At this point, I&apos;m reminded of a funny Rich Hickey quote:</p><p><img alt="Rich Hickey giving a talk, saying the following: I think we’re in this world I’d like to call Guard Rail Programming... I can make change because I have tests! Who does that? Who drives their car around, banging against the guard rails? Do the guard rails help you get to where you want to go?" src="assets/2023-11-12-guardrails.png" title="Simple made snarky" /></p><p>Opening up <code>net.jmglov.awno.client.test-double</code>, we see something familiar:</p><pre><code class="language-clojure">(deftype Client [info handlers]
  ILookup
  (valAt [this k]
    (.valAt this k nil))

  (valAt [_this k default]
    (case k
      :api
      (-&gt; info :service :metadata :net.jmglov.awno/service-name)
      :service
      (:service info)
      default))

  client.protocol/Client
  (-get-info [_] info)
  
  ;; [...]
  )
</code></pre><p>Why don&apos;t we repeat our tried and tested remedy of replacing <code>deftype</code> with <code>defrecord</code>, then ripping out the <code>ILookup</code> interface and replacing it with a map? That gives us this:</p><pre><code class="language-clojure">(deftype Client [info handlers]
  client.protocol/Client
  (-get-info [_] info)

  (-invoke [this {:keys [op request] :as op-map}]
    ;; [...]
    )

  (-invoke-async [this {:keys [ch] :as op-map}]
    ;; [...]
    )

  (-stop [_aws-client])
  
  TestDoubleClient
  (-instrument [client ops]
    ;; [...]
    ))

;; -&gt;Client is intended for internal use
(alter-meta! #&apos;-&gt;Client assoc :skip-wiki true)
(alter-meta! #&apos;TestDoubleClient assoc :skip-wiki true)

(defn instrument
  &quot;Given a test double client and a `:ops` map of operations to handlers,
   instruments the client with handlers. See `client` for more info about
   `:ops`.&quot;
  [client ops]
  (-instrument client ops))

(defn client
  &quot;Given a map with :api and :ops (optional), returns a test double client that
  [...]
  - will not validate response payloads&quot;
  [{:keys [api ops]}]
  (let [service (service/service-description (name api))]
    (doto (-&gt;Client {:api (-&gt; service :metadata :cognitect.aws/service-name)
                     :service service
                     :validate-requests? (atom true)} (atom {}))
      (instrument ops))))
</code></pre><p>OK, <strong>surely</strong> the tests will run now!</p><pre><code class="language-text">: awno-api; bin/test
bb tests

Testing net.jmglov.awno.client.api-test

ERROR in (test-underlying-http-client) (/home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/client/api_test.clj:9)
defaults to shared client
expected: (= #{(shared/http-client)} (into #{(shared/http-client)} (-&gt;&gt; clients (map (fn [c] (-&gt; c client.protocol/-get-info :http-client))))))
  actual: clojure.lang.ExceptionInfo: Cannot find resource net.jmglov.awno/s3/service.edn.
{}
 at sci.lang.Var.invoke (lang.cljc:202)
    sci.impl.analyzer$return_call$reify__4543.eval (analyzer.cljc:1399)
[...]

Testing net.jmglov.awno.util-test

Ran 48 tests containing 675 assertions.
19 failures, 33 errors.
{:test 48, :pass 623, :fail 19, :error 33, :type :summary}
</code></pre><p><img alt="A woman on a beach at sunrise with her head thrown back, saying &quot;Victory&quot;" src="assets/2023-11-11-victory.jpg" title="Never in doubt" /></p><p>Well, sorta.</p><div class="markdown-heading"><h2 id="what-the-what?">What the what?</h2><a href="#what-the-what?" class="anchor" aria-label="Permalink: What the what?"><img src="assets/link.svg" /></a></div><p><code>bb test</code> produced 6544 lines of output whilst failing those 19 tests and erroring out of a further 33. Let&apos;s strip away all the noise and see if we can see what&apos;s actually happening here.</p><pre><code class="language-text">: awno-api; bin/test 2&gt;&amp;1 &gt;/tmp/err.log
ERROR in (test-underlying-http-client) (/home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/client/api_test.clj:9)
defaults to shared client
expected: (= #{(shared/http-client)} (into #{(shared/http-client)} (-&gt;&gt; clients (map (fn [c] (-&gt; c client.protocol/-get-info :http-client))))))
  actual: clojure.lang.ExceptionInfo: Cannot find resource net.jmglov.awno/s3/service.edn.
--
[...]
--
ERROR in (raw-response-values) (/home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/client/test_double_test.clj:33)
Uncaught exception, not in assertion.
expected: nil
  actual: clojure.lang.ExceptionInfo: null
--
[...]
--
ERROR in (test-parse-date) (/home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/shape_test.clj:5)
iso8601 format handles presence and absence of fractional seconds
expected: (= #inst &quot;2020-07-06T10:59:13.417-00:00&quot; (shape/parse-date {:timestampFormat &quot;iso8601&quot;} &quot;2020-07-06T10:59:13.417Z&quot;))
  actual: java.time.format.DateTimeParseException: Text &apos;2020-07-06T10:59:13.417Z&apos; could not be parsed at index 19
</code></pre><p>OK, not as bad as it could be. There are only three classes of errors here, repeated many times. The first one should be extremely simple to deal with. A quick search in the project for <code>service.edn</code> yields only one hit, in the <code>net.jmglov.awno.service</code> namespace:</p><pre><code class="language-clojure">(def base-ns &quot;net.jmglov.awno&quot;)

(def base-resource-path &quot;net.jmglov.awno&quot;)
```

Looks like my search and replace was a bit excessively exuberant. Let&apos;s try
restoring their Cognitectiness:

``` clojure
(def base-ns &quot;cognitect.aws&quot;)

(def base-resource-path &quot;cognitect/aws&quot;)
```

Before re-running all the tests, it would be quite lovely to give ourselves a
way to run tests for a subset of namespaces, instead of all the ones specified
in `net.jmglov.awno.test`. Actually, looking at `run-tests`, maybe we can!

``` clojure
(defn run-tests
  ([]
   (run-tests {:test-namespaces test-namespaces}))
  ([{nses :test-namespaces}]
   (dorun (map require nses))
   (let [res (apply test/run-tests nses)]
     (pprint/pprint res)
     (when (-&gt;&gt; ((juxt :fail :error) res)
                (some #(pos? %)))
       (System/exit 1)))))
```

The 1-arity version of `run-tests` lets us pass a map with `:test-namespaces`,
and Babashka&apos;s `-x` flag uses [babashka-cli](https://book.babashka.org/#cli) to
let us pass function arguments as command line flags, so we should be able to do
this!

``` text
: awno-api; bb -x net.jmglov.awno.test/run-tests --test-namespaces net.jmglov.awno.client.api-test
----- Error --------------------------------------------------------------------
Type:     java.lang.IllegalArgumentException
Message:  Don&apos;t know how to create ISeq from: java.lang.Character
Location: /home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/test.cljc:32:4
```

Blerg! Looks like the value of the `:test-namespaces` key is a string, rather
than a list of strings. Luckily, babashka-cli lets you add metadata to functions
to [control parsing behaviour](https://github.com/babashka/cli#clojure-cli).
Let&apos;s sprinkle some on `run-tests`:

``` clojure
(defn run-tests
  {:org.babashka/cli {:coerce {:test-namespaces [:symbol]}}}
  ([]
   (run-tests {:test-namespaces test-namespaces}))
  ([{nses :test-namespaces}]
   (dorun (map require nses))
   (let [res (apply test/run-tests nses)]
     (pprint/pprint res)
     (when (-&gt;&gt; ((juxt :fail :error) res)
                (some #(pos? %)))
       (System/exit 1)))))
```

Now babashka-cli will coerce `:test-namespaces` to a list of symbols! 😲

Let&apos;s try it out on a couple of test namespaces that were actually passing:

``` text
: awno-api; bb -x net.jmglov.awno.test/run-tests \
  --test-namespaces net.jmglov.awno.config-test net.jmglov.awno.credentials-test
{:test-namespaces [net.jmglov.awno.config-test net.jmglov.awno.credentials-test]}

Testing net.jmglov.awno.config-test

Testing net.jmglov.awno.credentials-test

Ran 9 tests containing 41 assertions.
0 failures, 0 errors.
{:test 9, :pass 41, :fail 0, :error 0, :type :summary}
```

This looks good, so let&apos;s give api-test another go:

``` text
: awno-api; bb -x net.jmglov.awno.test/run-tests \
  --test-namespaces net.jmglov.awno.client.api-test

Testing net.jmglov.awno.client.api-test

Ran 3 tests containing 11 assertions.
0 failures, 0 errors.
{:test 3, :pass 11, :fail 0, :error 0, :type :summary}
```

OK, so that fix worked! Let&apos;s take a look at the next class of errors.

``` text
ERROR in (raw-response-values) (/home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/client/test_double_test.clj:33)
Uncaught exception, not in assertion.
expected: nil
  actual: clojure.lang.ExceptionInfo: null
```

## Abort!

It was at this point that I ran out of steam. I apologise for my lack of
dedication to the art of self-flagellation and will flagellate myself
accordingly.

![Abort!][abort]

[abort]: assets/2023-11-12-abort.jpg &quot;A supercar driving out of the window of a skyscraper&quot;
</code></pre></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2023-11-11-awno-api.html</id>
    <link href="https://jmglov.net/blog/2023-11-11-awno-api.html"/>
    <title>Awno! Mutilating awyeah-api</title>
    <updated>2023-11-11T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>You remember how I&apos;ve been trying to write a <a href="2023-01-04-blambda-analyses-sites.html">site
analyser</a> for my blog for the last year or so? Well, I was using DynamoDB for storing some metrics, and I realised that would bankrupt me, so I decided to use <a href="https://docs.aws.amazon.com/athena/">Amazon
Athena</a> run SQL queries directly on my access logs instead. That should have been a great idea, but when I fired up my REPL with <a href="https://github.com/grzm/awyeah-api">awyeah-api</a>, I got quite the unpleasant surprise:</p><pre><code class="language-clojure">(comment

  (def athena (aws/client {:api :athena
                           :region (or (System/getenv &quot;AWS_DEFAULT_REGION&quot;) &quot;eu-west-1&quot;)}))
  ;; =&gt; #&apos;user/athena

  (aws/invoke athena {:op :ListWorkGroups
                      :request {}})
  ;; =&gt; {:__type &quot;InvalidSignatureException&quot;,
  ;;     :message
  ;;     &quot;The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\n\nThe Canonical String for this request should have been\n&apos;POST\n/\n\naccept:application/json\ncontent-type:application/x-amz-json-1.1\nhost:athena.eu-west-1.amazonaws.com:443\nx-amz-date:20231105T115515Z\nx-amz-target:AmazonAthena.ListWorkGroups\n\naccept;content-type;host;x-amz-date;x-amz-target\n44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a&apos;\n\nThe String-to-Sign should have been\n&apos;AWS4-HMAC-SHA256\n20231105T115515Z\n20231105/eu-west-1/athena/aws4_request\n4dd8829addcae8b5fe35d78323f484298d478ab9af786b3caa12bac0d2f57a8c&apos;\n&quot;,
  ;;     :cognitect.anomalies/category :cognitect.anomalies/incorrect}
</code></pre><p>What the what?</p><p>Digging into this with some tasty debug <code>prn</code>s, I <a href="https://github.com/grzm/awyeah-api/issues/8#issuecomment-1576607738">found
out</a> that the issue was that Athena was expecting a canonical string like this:</p><pre><code class="language-text">POST
/

accept:application/json
content-type:application/x-amz-json-1.1
host:athena.eu-west-1.amazonaws.com:443
x-amz-date:20230605T111631Z
x-amz-target:AmazonAthena.ListWorkGroups

accept;content-type;host;x-amz-date;x-amz-target
44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a
</code></pre><p>And awyeah-api was generating a canonical string like that:</p><pre><code class="language-text">POST
/

accept:application/json
content-type:application/x-amz-json-1.1
host:athena.eu-west-1.amazonaws.com
x-amz-date:20230605T111631Z
x-amz-target:AmazonAthena.ListWorkGroups

accept;content-type;host;x-amz-date;x-amz-target
44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a
</code></pre><p>I&apos;m sure you&apos;ve already spotted the difference, right? 🙄</p><p>Take a look at the <code>host</code> header. Athena wants this:</p><pre><code class="language-text">host:athena.eu-west-1.amazonaws.com:443
</code></pre><p>And we&apos;re giving it that:</p><pre><code class="language-text">host:athena.eu-west-1.amazonaws.com
</code></pre><p>For want of a <code>:443</code>, the kingdom was lost! 😭</p><div class="markdown-heading"><h2 id="what-is-to-be-done?">What is to be done?</h2><a href="#what-is-to-be-done?" class="anchor" aria-label="Permalink: What is to be done?"><img src="assets/link.svg" /></a></div><p>After filing a <a href="https://github.com/grzm/awyeah-api/issues/8#issuecomment-1576607738">bug
report</a>, I started reading through all the commits to <a href="https://github.com/cognitect-labs/aws-api">aws-api</a> since <code>0.8.603</code>, which is the latest commit that&apos;s been ported over to awyeah-api. These two in particular looked pretty tasty:</p><p><img alt="Commit messages on Github" src="assets/2023-11-11-aws-api-commits.png" title="The sus imposter from Among Us" /></p><p>I ported those two over to a clone of awyeah-api, but my REPL still informed me that I sucked:</p><pre><code class="language-clojure">(comment

  (aws/invoke athena {:op :ListWorkGroups
                      :request {}})
  ;; =&gt; {:__type &quot;InvalidSignatureException&quot;,
  ;;     :message
  ;;     &quot;The request signature we calculated does not match the signature you provided. Haven&apos;t you heard Einstein&apos;s definition of insanity, dude? Try something else already!\n&quot;,
  ;;     :cognitect.anomalies/category :cognitect.anomalies/you-suck}
</code></pre><p>Never one to give up so easily, I continued porting stuff, all the way up to the latest aws-api commits (skipping a few commits that I just couldn&apos;t figure out how to port), and not only did the <code>InvalidSignatureException</code> persist, but now I&apos;d broken the awyeah-api tests. 🤦</p><div class="markdown-heading"><h2 id="what-now-is-to-be-done?">What now is to be done?</h2><p>After sleeping on it, I realised that the root of my problem is that I was just porting code over without really thinking about what the code was doing, and that a better approach would perhaps be to understand the code. Obv.</p><p>But instead of just understanding the code I was porting and why, I decided that I needed to understand how Michael Glaesemann AKA <a href="https://github.com/grzm">grzm</a> had made aws-api work with Babashka in the first place. And how better to do that than to fork aws-api into my own Github repo and start replicating the awyeah-api stuff on top of it? (I&apos;m sure there are much better ways to do that, but if you&apos;ve been reading this blog for more than five minutes, you&apos;ll know that I never take the better way when a worse and more painful way is available. Just call me Gandalf in the Mines of Moria.)</p><p>And what better name to capture the dismay that I&apos;m sure you&apos;re feeling as you read this than <a href="https://github.com/jmglov/awno-api">awno-api</a>? And what better tense to capture the excitement of a fool&apos;s errand than the present?</p><h2 id="let-the-mutilation-begin!">Let the mutilation begin!</h2><a href="#what-now-is-to-be-done?">What now is to be done?</h2><p>After sleeping on it, I realised that the root of my problem is that I was just porting code over without really thinking about what the code was doing, and that a better approach would perhaps be to understand the code. Obv.</p><p>But instead of just understanding the code I was porting and why, I decided that I needed to understand how Michael Glaesemann AKA <a href="https://github.com/grzm">grzm</a> had made aws-api work with Babashka in the first place. And how better to do that than to fork aws-api into my own Github repo and start replicating the awyeah-api stuff on top of it? (I&apos;m sure there are much better ways to do that, but if you&apos;ve been reading this blog for more than five minutes, you&apos;ll know that I never take the better way when a worse and more painful way is available. Just call me Gandalf in the Mines of Moria.)</p><p>And what better name to capture the dismay that I&apos;m sure you&apos;re feeling as you read this than <a href="https://github.com/jmglov/awno-api">awno-api</a>? And what better tense to capture the excitement of a fool&apos;s errand than the present?</p><h2 id="let-the-mutilation-begin!" class="anchor" aria-label="Permalink: Let the mutilation begin!"><img src="assets/link.svg" /></a></div><p>After cloning my new forked repo, let&apos;s get to work making aws-api into something that will work with babashka. The first order of business is purely mechanical:</p><pre><code class="language-text">cd ~/Documents/code/clojure/awyeah-api
cp -r bb.edn bin CHANGES.markdown docs etc ../awno-api/
cd ../awno-api
mkdir -p src/net/jmglov test/src/net/jmglov
git mv src/cognitect/aws src/net/jmglov/awno
git mv test/src/cognitect/aws test/src/net/jmglov/awno
git rm -rf doc latest-releases.edn pom.xml UPGRADE.md README.md CHANGES.md 
rm -rf src/cognitect test/src/cognitect
</code></pre><p>Now let&apos;s update <code>bb.edn</code> to use the latest versions of all the good stuff. We can grab the commit SHA for the latest version of the babashka port of Spec from <a href="https://github.com/babashka/spec.alpha">https://github.com/babashka/spec.alpha</a>, then the various versions of the AWS libraries from <a href="https://github.com/cognitect-labs/aws-api/blob/main/latest-releases.edn">latest-releases.edn</a> in the aws-api repo, resulting in a shiny new <code>bb.edn</code>:</p><pre><code class="language-clojure">{:paths [&quot;resources&quot; &quot;src&quot; &quot;test/resources&quot; &quot;test/src&quot;]
 :deps
 {org.babashka/spec.alpha {:git/url &quot;https://github.com/babashka/spec.alpha&quot;
                           :git/sha &quot;8df0712896f596680da7a32ae44bb000b7e45e68&quot;}
  org.clojure/tools.logging {:mvn/version &quot;1.2.4&quot;}

  com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.307&quot;}

  com.cognitect.aws/ec2
  {:mvn/version &quot;822.2.1122.0&quot;, :aws/serviceFullName &quot;Amazon Elastic Compute Cloud&quot;},
  com.cognitect.aws/lambda
  {:mvn/version &quot;822.2.1122.0&quot;, :aws/serviceFullName &quot;AWS Lambda&quot;},
  com.cognitect.aws/s3
  {:mvn/version &quot;822.2.1145.0&quot;}
  com.cognitect.aws/ssm
  {:mvn/version &quot;822.2.1122.0&quot;, :aws/serviceFullName &quot;Amazon Simple Systems Manager (SSM)&quot;}
  com.cognitect.aws/sts
  {:mvn/version &quot;822.2.1109.0&quot;, :aws/serviceFullName &quot;AWS Security Token Service&quot;}}}
</code></pre><p>Now to open up <code>awno-api/README.markdown</code>, cry havoc, and let slip the dogs of <code>projectile-replace</code> with <code>M-p R</code>! (If you&apos;re not using <a href="https://github.com/doomemacs/">Doom
Emacs</a>, you&apos;ll probably need to smack some different keys; if you don&apos;t know which ones, you can always take the <code>M-x projectile-replace</code> route).</p><p><img alt="Emacs prompting to replace cognitect.aws with net.jmglov.awno" src="assets/2023-11-11-projectile-replace.png" title="Fly, my pretties!"
[noice]: assets/2023-11-11-noice.gif "Toit!" /></p><p>After replacing all of the instances (you&apos;ll be prompted to replace each occurrence, but you hit <code>!</code> at the first prompt if you want to YOLO replace all occurrences), you can use <code>C-x s</code> to invoke <code>save-some-buffers</code>, then hit <code>!</code> at the prompt to save all of the files you just replaced <code>cognitect.aws</code> in.</p><p>Now that all your namespaces are belong to us, it&apos;s time for the moment of truth! Will the REPL start? With baited breath, let&apos;s hit <code>C-c M-j</code> to invoke <code>cider-jack-in-clj</code>, instruct <a href="https://github.com/clojure-emacs/cider">CIDER</a> to use babashka, and hope for the best.</p><pre><code class="language-text">Started nREPL server at 127.0.0.1:35223
For more info visit: https://book.babashka.org/#_nrepl
;; Connected to nREPL server - nrepl://127.0.0.1:35223
;; CIDER 1.7.0-snapshot (package: 1.7.0-snapshot), babashka.nrepl 0.0.6-SNAPSHOT
;; Babashka 1.3.176
;;     Docs: (doc function-name)
;;           (find-doc part-of-name)
;;   Source: (source function-name)
;;  Javadoc: (javadoc java-object-or-class)
;;     Exit: &lt;C-c C-q&gt;
;;  Results: Stored in vars *1, *2, *3, an exception in *e;
;;  Startup: /home/jmglov/.nix-profile/bin/bb nrepl-server localhost:0
WARNING: Can&apos;t determine Clojure version.  The refactor-nrepl middleware requires clojure 1.8.0 (or newer)WARNING: clj-refactor and refactor-nrepl are out of sync.
Their versions are 3.6.0 and n/a, respectively.
You can mute this warning by changing cljr-suppress-middleware-warnings.
user&gt; 
</code></pre><p>![Jake Peralta from Brooklyn 99 saying &quot;Noice&quot;][noice]</p><div class="markdown-heading"><h2 id="what&apos;s-the-big-deal,-anyway?">What&apos;s the big deal, anyway?</h2><a href="#what&apos;s-the-big-deal,-anyway?" class="anchor" aria-label="Permalink: What&apos;s the big deal, anyway?"><img src="assets/link.svg" /></a></div><p>Equipped with our trusty REPL, it&apos;s time to get down to the real work of really making it work. Luckily for us, good ol&apos; grzm has captured the decisions he made whilst porting aws-api in a nice <a href="https://github.com/grzm/awyeah-api/blob/main/docs/porting-decisions.markdown">porting-decisions.markdown</a> doc, so let&apos;s start reading.</p><p>Right at the top of the doc, he mentions a <a href="https://github.com/grzm/awyeah-api/blob/main/docs/porting-decisions.markdown#missing-classes">set of Java
classes</a> that are missing from babashka:</p><ul><li><code>java.lang.Runnable</code></li><li><code>java.lang.ThreadLocal</code></li><li><code>java.util.concurrent.ThreadFactory</code></li><li><code>java.util.concurrent.ScheduledFuture</code></li><li><code>java.util.concurrent.ScheduledExecutorService</code></li></ul><p>Since awyeah-api was originally written, three of those five classes have been added to babashka, according to <a href="https://github.com/babashka/babashka/blob/6353ab9de948679152afb3aa2daa811740d59b0f/src/babashka/impl/classes.clj#L23">babashka.impl.classes</a>:</p><ul><li><code>java.lang.Runnable</code></li><li><code>java.util.concurrent.ThreadFactory</code></li><li><code>java.util.concurrent.ScheduledExecutorService</code></li></ul><p>So now we only have to deal with the other two.</p><p>According to grzm:</p><blockquote><p>These classes are referenced in two namespaces: <code>cognitect.aws.util</code> and <code>cognitect.aws.credentials</code>. <code>ThreadLocal</code> is used in <code>cognitect.aws.util</code> to make <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4228335"><code>java.text.SimpleDateFormat</code>  thread-safe</a>. As I&apos;m not concerned with supporting pre-Java 8 versions, I&apos;ve decided to use the thread-safe <code>java.time.format.DateTimeFormatter</code> rather than drop thread-safety workarounds for <code>SimpleDateFormat</code> or implement them in some other way.</p><p>The <code>cognitect.aws.util</code> namespace is used throughout the aws-api library, either directly or transitively.</p><p>The balance of the unincluded classes are used in <code>cognitect.aws.credentials</code> to provide auto-refreshing of AWS credentials. As babashka is commonly used for short-lived scripts as opposed to long-running server applications, rather than provide an alternate implementation for credential refresh, I&apos;ve chosen to omit this functionality. If credential auto-refresh is something I find <em>is</em> useful in a babashka context some time in the future, a solution can be explored at that time.</p></blockquote><p>Snatching up that tasty breadcrumb, let&apos;s open our shiny new <code>net.jmglov.awno.util</code> namespace.</p><div class="markdown-heading"><h2 id="thread-safety?-we-don&apos;t-need-no-stinkin&apos;-thread-safety!">Thread safety? We don&apos;t need no stinkin&apos; thread safety!</h2><a href="#thread-safety?-we-don&apos;t-need-no-stinkin&apos;-thread-safety!" class="anchor" aria-label="Permalink: Thread safety? We don&apos;t need no stinkin&apos; thread safety!"><img src="assets/link.svg" /></a></div><p>As we have no more appetite than grzm for supporting Java versions older than Java 8, let&apos;s just follow his lead and kick <code>ThreadLocal</code> to the curb. That means replacing this mess from aws-api:</p><pre><code class="language-clojure">
(defn  date-format
  &quot;Return a thread-safe GMT date format that can be used with `format-date` and `parse-date`.

  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4228335&quot;
  ^ThreadLocal [^String fmt]
  (proxy [ThreadLocal] []
    (initialValue []
      (doto (SimpleDateFormat. fmt)
        (.setTimeZone (TimeZone/getTimeZone &quot;GMT&quot;))))))

(defn format-date
  ([fmt]
   (format-date fmt (Date.)))
  ([^ThreadLocal fmt inst]
   (.format ^SimpleDateFormat (.get fmt) inst)))
</code></pre><p>With this lovely stuff from awyeah-api:</p><pre><code class="language-clojure">(defn date-format
  &quot;Return a thread-safe GMT date format that can be used with `format-date` and `parse-date`.&quot;
  [^String fmt]
  (.withZone (DateTimeFormatter/ofPattern fmt) (ZoneId/of &quot;GMT&quot;)))

(defn format-date
  ([formatter]
   (format-date formatter (Date.)))
  ([formatter ^Date inst]
   (.format (ZonedDateTime/ofInstant (.toInstant inst) (ZoneId/of &quot;UTC&quot;))
            ^DateTimeFormatter formatter)))
</code></pre><p>Copy and paste-driven development FTW! 🎉</p><p>The <code>parse-date</code> function from aws-api needed a little love too. This:</p><pre><code class="language-clojure">(defn parse-date
  [^ThreadLocal fmt s]
  (.parse ^SimpleDateFormat (.get fmt) s))
</code></pre><p>Becomes that:</p><pre><code class="language-clojure">(defn parse-date
  [formatter s]
  (Date/from (.toInstant (ZonedDateTime/parse s formatter))))
</code></pre><p>This leaves only five more occurrences of <code>ThreadLocal</code> in the namespace:</p><pre><code class="language-clojure">(def ^ThreadLocal x-amz-date-format
  (date-format &quot;yyyyMMdd&apos;T&apos;HHmmss&apos;Z&apos;&quot;))

(def ^ThreadLocal x-amz-date-only-format
  (date-format &quot;yyyyMMdd&quot;))

(def ^ThreadLocal iso8601-date-format
  (date-format &quot;yyyy-MM-dd&apos;T&apos;HH:mm:ssXXX&quot;))

(def ^ThreadLocal iso8601-msecs-date-format
  (date-format &quot;yyyy-MM-dd&apos;T&apos;HH:mm:ss.SSS&apos;Z&apos;&quot;))

(def ^ThreadLocal rfc822-date-format
  (date-format &quot;EEE, dd MMM yyyy HH:mm:ss z&quot;))
</code></pre><p>For these, all we need to do is remove the <code>^ThreadLocal</code> type hint and we&apos;re golden! Well, almost golden. We&apos;re using a few <code>java.time</code> classes that weren&apos;t in the aws-api version, so we need to add those, and whilst we&apos;re at it, let&apos;s go ahead and remove the classes that aren&apos;t necessary anymore, and alphabetise the requires and imports in the <code>ns</code> form and OMG what are square brackets doing in the <code>:import</code> section? <a href="https://stuartsierra.com/2016/clojure-how-to-ns.html">According to St.
Stuart</a>, thou must always use round brackets with <code>:import</code>, never square!</p><p>Making the sign to ward off evil, we fix the glitch.</p><p><img alt="The Bobs from Office Space saying &quot;So we fixed the glitch&quot;" src="assets/2023-11-11-glitch.jpg" title="I&apos;m gonna need you to go ahead and come in Sunday, too" /></p><p>With all of this done, we should be able to eval the namespace in our REPL, right? <code>C-c C-k</code> (<code>cider-load-buffer</code>) will tell the tale:</p><pre><code class="language-text">clojure.lang.ExceptionInfo: Could not find namespace: clojure.data.json.
{:type :sci/error, :line 9, :column 3, :message &quot;Could not find namespace: clojure.data.json.&quot;, :sci.impl/callstack #object[clojure.lang.Volatile 0xfb2c337 {:status :ready, :val ({:line 9, :column 3, :file &quot;/home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/util.clj&quot;, :ns #object[sci.lang.Namespace 0x2c8684c &quot;net.jmglov.awno.util&quot;]})}], :file &quot;/home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/util.clj&quot;}
 at sci.impl.utils$rethrow_with_location_of_node.invokeStatic (utils.cljc:129)
    sci.impl.analyzer$return_ns_op$reify__4355.eval (analyzer.cljc:1189)
    sci.impl.analyzer$return_do$reify__3968.eval (analyzer.cljc:130)
    sci.impl.interpreter$eval_form.invokeStatic (interpreter.cljc:40)
    sci.core$eval_form.invokeStatic (core.cljc:329)
    babashka.nrepl.impl.server$eval_msg$fn__27295$fn__27296.invoke (server.clj:108)
    [...]
</code></pre><p>Blerg!</p><div class="markdown-heading"><h2 id="json-voorhees">JSON Voorhees</h2><a href="#json-voorhees" class="anchor" aria-label="Permalink: JSON Voorhees"><img src="assets/link.svg" /></a></div><p>No <code>clojure.data.json</code>, eh? Let&apos;s return to <code>porting-decisions.markdown</code> and see is grzm has anything to say about that. <a href="https://github.com/grzm/awyeah-api/blob/main/docs/porting-decisions.markdown#clojuredatajson-and-cheshire">Indeed he
does</a>!</p><blockquote><p>The aws-api library depends on <a href="https://github.com/clojure/data.json"><code>clojure.data.json</code></a> for JSON serialization and deserialization, a pure Clojure library. Babashka includes <a href="https://github.com/dakrone/cheshire">Cheshire</a> for JSON support and not <code>clojure.data.json</code>.</p><p>The Clojure source of <code>clojure.data.json</code> can be interpreted by sci, so I could include <code>clojure.data.json</code> as a dependency and use it as-is. The <code>clojure.data.json</code> usage in aws-api is easily replaced by Cheshire. Replacing <code>clojure.data.json</code> with Cheshire means one less dependency to include, and we can leverage compiled code rather than interpreted. To isolate the library choice, I&apos;ve extracted the library-specific calls in the <code>com.grzm.awyeah.json</code> namespace.</p></blockquote><p>We can copy <code>src/com/grzm/awyeah/json.clj</code> from awyeah-api over to awno-api and fix up the namespace declaration. Let&apos;s also make <code>read-str</code> plug compatible with <code>clojure.data.json</code> by adding a three arity form that allows passing a custom key function and of course supporting the deprecated <code>json-str</code> function (because it&apos;s sometimes used in aws-api instead of <code>write-str</code>):</p><pre><code class="language-clojure">(ns net.jmglov.awno.json
  (:require [cheshire.core :as json]))

(defn write-str [x]
  (json/generate-string x))

;; Implement deprecated function as well
(def json-str write-str)

(defn read-str
  ([s]
   (read-str s :key-fn keyword))
  ([s _ key-fn]
   (json/parse-string s key-fn)))
</code></pre><p>This will handle all the calls like this in the aws-api codebase:</p><pre><code class="language-clj">(json/read-str :key-fn keyword)
</code></pre><p>Having done that, let&apos;s <code>M-p R</code> (like <a href="https://www.npr.org/">NPR</a>, but runs <code>projectile-replace</code> instead of giving you some news with a vaugely progressive yet US-centric slant) to replace <code>clojure.data.json</code> with <code>net.jmglov.awno.json</code> project-wide. Don&apos;t forget to <code>C-x s !</code> again to save all of the files we just modified.</p><p>Now let&apos;s try evaluating the namespace...</p><p><img alt="A woman on a beach at sunrise with her head thrown back, saying &quot;Victory&quot;" src="assets/2023-11-11-victory.jpg" title="Never in doubt" /></p><p>At this point, we should be able to run the <code>net.jmglov.awno.util</code> tests. Popping over to <code>test/src/net/jmglov/awno/util_test.clj</code>, we see that the Cognitect folks have left us a nice little Rich comment at the bottom of the file:</p><pre><code class="language-clojure">(comment
  (t/run-tests))
</code></pre><p>Let&apos;s expand it a bit, put the cursor at the end of the <code>t/run-tests</code> form, and do some <code>C-c C-v f c e</code> to invoke <code>cider-pprint-eval-last-sexp-to-comment</code>:</p><pre><code class="language-clojure">(comment

  (t/run-tests)
  ;; =&gt; {:test 6, :pass 13, :fail 0, :error 0, :type :summary}

  )
</code></pre><p>Boom! Now we&apos;re well underway!</p><div class="markdown-heading"><h2 id="you-don&apos;t-need-to-see-his-credentials">You don&apos;t need to see his credentials</h2><a href="#you-don&apos;t-need-to-see-his-credentials" class="anchor" aria-label="Permalink: You don&apos;t need to see his credentials"><img src="assets/link.svg" /></a></div><p>Back in <code>porting-decisions.markdown</code>, there&apos;s some mention of the other Java classes not included in babashka:</p><blockquote><p>The balance of the unincluded classes are used in <code>cognitect.aws.credentials</code> to provide auto-refreshing of AWS credentials. As babashka is commonly used for short-lived scripts as opposed to long-running server applications, rather than provide an alternate implementation for credential refresh, I&apos;ve chosen to omit this functionality. If credential auto-refresh is something I find <em>is</em> useful in a babashka context some time in the future, a solution can be explored at that time.</p></blockquote><p>Seems like we can also live without credential auto-refresh, so let&apos;s have a quick look at the <code>net.jmglov.awno.credentials</code> and see what we&apos;ll need to do to make it work.</p><p>Looks like we need to rip this bit out, since it uses thready thread stuff that we hate and fear:</p><pre><code class="language-clojure">(defonce ^:private scheduled-executor-service
  (delay
   (Executors/newScheduledThreadPool 1 (reify ThreadFactory
                                         (newThread [_ r]
                                           (doto (Thread. r)
                                             (.setName &quot;net.jmglov.awno-api.credentials-provider&quot;)
                                             (.setDaemon true)))))))
</code></pre><p>Now we can simplify <code>refresh!</code> from this:</p><pre><code class="language-clojure">(defn ^:skip-wiki refresh!
  &quot;For internal use. Don&apos;t call directly.

  Invokes `(fetch provider)`, resets the `credentials-atom` with and
  returns the result.

  If the credentials returned by the provider are not valid, resets
  both atoms to nil and returns nil.&quot;
  [credentials-atom scheduled-refresh-atom provider scheduler]
  (try
    (let [{:keys [::ttl] :as new-creds} (fetch provider)]
      (reset! scheduled-refresh-atom
              (when ttl
                (.schedule ^ScheduledExecutorService scheduler
                           ^Runnable #(refresh! credentials-atom scheduled-refresh-atom provider scheduler)
                           ^long ttl
                           TimeUnit/SECONDS)))
      (reset! credentials-atom new-creds))
    (catch Throwable t
      (reset! scheduled-refresh-atom nil)
      (log/error t &quot;Error fetching credentials.&quot;))))
</code></pre><p>To that:</p><pre><code class="language-clojure">(defn ^:skip-wiki refresh!
  &quot;For internal use. Don&apos;t call directly.

  Invokes `(fetch provider)`, resets the `credentials-atom` with and
  returns the result.

  If the credentials returned by the provider are not valid, resets
  both atoms to nil and returns nil.&quot;
  [credentials-atom provider]
  (try
    (let [new-creds (fetch provider)]
      (reset! credentials-atom new-creds))
    (catch Throwable t
      (log/error t &quot;Error fetching credentials.&quot;))))
</code></pre><p>And then we can rip out this stuff:</p><pre><code class="language-clojure">
(defn cached-credentials-with-auto-refresh
  &quot;Returns a CredentialsProvider which wraps `provider`, caching
  credentials returned by `fetch`, and auto-refreshing the cached
  credentials in a background thread when the credentials include a
  ::ttl.

  Call `stop` to cancel future auto-refreshes.

  The default ScheduledExecutorService uses a ThreadFactory that
  spawns daemon threads. You can override this by providing your own
  ScheduledExecutorService.

  Alpha. Subject to change.&quot;
  ([provider]
   (cached-credentials-with-auto-refresh provider @scheduled-executor-service))
  ([provider scheduler]
   (let [credentials-atom       (atom nil)
         scheduled-refresh-atom (atom nil)]
     (reify
       CredentialsProvider
       (fetch [_]
         (or @credentials-atom
             (refresh! credentials-atom scheduled-refresh-atom provider scheduler)))
       Stoppable
       (-stop [_]
         (-stop provider)
         (when-let [r @scheduled-refresh-atom]
           (.cancel ^ScheduledFuture r true)))))))

(defn ^:deprecated auto-refreshing-credentials
  &quot;Deprecated. Use cached-credentials-with-auto-refresh&quot;
  ([provider] (cached-credentials-with-auto-refresh provider))
  ([provider scheduler] (cached-credentials-with-auto-refresh provider scheduler)))
</code></pre><p>And replace it with a much simpler function:</p><pre><code class="language-clojure">
(defn cached-credentials
  &quot;Returns a CredentialsProvider which wraps `provider`, caching
  credentials returned by `fetch`, and auto-refreshing the cached
  credentials in a background thread when the credentials include a
  ::ttl.

  Call `stop` to cancel future auto-refreshes.

  The default ScheduledExecutorService uses a ThreadFactory that
  spawns daemon threads. You can override this by providing your own
  ScheduledExecutorService.

  Alpha. Subject to change.&quot;
  [provider]
  (let [credentials-atom (atom nil)]
    (reify
      CredentialsProvider
      (fetch [_]
        (or @credentials-atom
            (refresh! credentials-atom provider)))
      Stoppable
      (-stop [_]
        (-stop provider)))))
</code></pre><p>We can now replace all occurrences of <code>cached-credentials-with-auto-refresh</code> in the file with <code>cached-credentials</code>.</p><p>And now the <code>stop</code> function doesn&apos;t actually need to do anything:</p><pre><code class="language-clojure">(defn stop
  &quot;no-op&quot;
  [_credentials])
</code></pre><p>With this, <code>C-c C-k</code> evaluates the namespace without errors, so let&apos;s go over to <code>net.jmglov.awno.credentials-test</code> and see if the tests work. But first, let&apos;s rip out anything to do with auto-refreshing credentials. That means replacing all of the <code>cached-credentials-with-auto-refresh</code> in the file with <code>cached-credentials</code> and removing the explicit test of auto-refreshing:</p><pre><code class="language-clojure">(deftest auto-refresh-test
  (let [cnt (atom 0)
        p (reify credentials/CredentialsProvider
            (credentials/fetch [_]
              (swap! cnt inc)
              {:aws/access-key-id &quot;id&quot;
               :aws/secret-access-key &quot;secret&quot;
               ::credentials/ttl 1}))
        creds (credentials/cached-credentials p)]
    (credentials/fetch creds)
    (Thread/sleep 2500)
    (let [refreshed @cnt]
      (credentials/stop creds)
      (Thread/sleep 1000)
      (is (= 3 refreshed) &quot;The credentials have been refreshed.&quot;)
      (is (= refreshed @cnt) &quot;We stopped the auto-refreshing process.&quot;))))
</code></pre><p>OK, looking good! Let&apos;s give it a <code>C-c C-k</code>:</p><pre><code class="language-text">clojure.lang.ExceptionInfo: Could not find namespace: clojure.tools.logging.test.
{:type :sci/error, :line 5, :column 3, :message &quot;Could not find namespace: clojure.tools.logging.test.&quot;, :sci.impl/callstack #object[clojure.lang.Volatile 0x13387b21 {:status :ready, :val ({:line 5, :column 3, :file &quot;/home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/credentials_test.clj&quot;, :ns #object[sci.lang.Namespace 0x65a7dc8f &quot;net.jmglov.awno.credentials-test&quot;]})}], :file &quot;/home/jmglov/Documents/code/clojure/awno-api/test/src/net/jmglov/awno/credentials_test.clj&quot;}
 at sci.impl.utils$rethrow_with_location_of_node.invokeStatic (utils.cljc:129)
    sci.impl.analyzer$return_ns_op$reify__4355.eval (analyzer.cljc:1189)
    sci.impl.analyzer$return_do$reify__3968.eval (analyzer.cljc:130)
    sci.impl.interpreter$eval_form.invokeStatic (interpreter.cljc:40)
    sci.core$eval_form.invokeStatic (core.cljc:329)
    [...]
</code></pre><p>Oh no! It looks like whatever version of <code>clojure.tools.logging</code> that is included in babashka doesn&apos;t have <code>clojure.tools.logging.test</code>! 😭</p><p>For now, let&apos;s just comment out the stuff that needs <code>clojure.tools.logging.test</code> and get on with our lives:</p><pre><code class="language-clojure">(ns net.jmglov.awno.credentials-test
  (:require [clojure.test :as t :refer [deftest testing use-fixtures is]]
            [clojure.java.io :as io]
            #_[clojure.tools.logging.test :refer [with-log logged?]]
            [net.jmglov.awno.credentials :as credentials]
            [net.jmglov.awno.util :as u]
            [net.jmglov.awno.test.utils :as tu]
            [net.jmglov.awno.ec2-metadata-utils :as ec2-metadata-utils]
            [net.jmglov.awno.ec2-metadata-utils-test :as ec2-metadata-utils-test])
  (:import (java.time Instant)))

;; [...]

#_(deftest valid-credentials-test
  (with-log
    (credentials/valid-credentials nil &quot;x provider&quot;)
    (is (logged? &apos;net.jmglov.awno.credentials :debug (str &quot;Unable to fetch credentials from x provider.&quot;))))
  (with-log
    (credentials/valid-credentials {:aws/access-key-id     &quot;id&quot;
                                    :aws/secret-access-key &quot;secret&quot;}
                                   &quot;x provider&quot;)
    (is (logged? &apos;net.jmglov.awno.credentials :debug (str &quot;Fetched credentials from x provider.&quot;)))))
</code></pre><p>After doing that, the namespace evaluates just fine, so let&apos;s try running the tests:</p><pre><code class="language-clojure">
(comment

  (t/run-tests)
  ;; =&gt; java.lang.RuntimeException: Could not find net.jmglov.awno_http.edn on classpath. user /home/jmglov/Documents/code/clojure/awno-api/src/net/jmglov/awno/http.clj:76:9

  )
</code></pre><p>Oh sweet mother of mercy what now?</p><div class="markdown-heading"><h2 id="http:-horrible-time-to-port">HTTP: Horrible Time To Port</h2><a href="#http:-horrible-time-to-port" class="anchor" aria-label="Permalink: HTTP: Horrible Time To Port"><img src="assets/link.svg" /></a></div><p>Since our error mentioned HTTP by name, let&apos;s look up HTTP in <code>porting-decisions.markdown</code>:</p><blockquote><p>The aws-api library defines a protocol (<code>cognitect.aws.http/HttpClient</code>) to provide an interface between the aws-api data transformation logic and the specific HTTP client implementation. The aws-api includes an implementation for the <code>com.cognitect/http-client</code> library. Interfaces are great: we can provide our own implementations of the <code>cognitect.aws.http/HttpClient</code> interface based on the various HTTP clients included in babashka.</p></blockquote><p>Alrighty, looks like we&apos;re gonna need to implement an HTTP client. Let&apos;s have a look at how this is done in awyeah-api by peeking in <a href="https://github.com/grzm/awyeah-api/blob/main/src/com/grzm/awyeah/http.clj">src/com/grzm/awyeah/http.clj</a>. It seems by and large the same as aws-api&apos;s <a href="https://github.com/cognitect-labs/aws-api/blob/main/src/cognitect/aws/http.clj">src/cognitect/aws/http.clj</a>, with exception of some class loader stuff, which is also mentioned in <code>porting-decisions.markdown</code>:</p><blockquote><p>There are a few other compatiblity issues, such as the use of <code>java.lang.ClassLoader::getResources</code> in <code>cognitect.aws.http/configured-client</code>, and replacing <code>^int x</code> hinting with explicit <code>(int x)</code> casts.</p></blockquote><p>Whilst <code>java.lang.ClassLoader::getResources</code> isn&apos;t mentioned directly, there are some class loader shenanigans happening here:</p><pre><code class="language-clojure">(defn- configured-client
  &quot;If a single net.jmglov.awno_http.edn is found on the classpath,
  returns the symbol bound to :constructor-var.

  Throws if 0 or &gt; 1 net.jmglov.awno_http.edn files are found.
  &quot;
  []
  (let [cl   (.. Thread currentThread getContextClassLoader)
        cfgs (enumeration-seq (.getResources cl &quot;net.jmglov.awno_http.edn&quot;))]
    (case (count cfgs)
      0 (throw (RuntimeException. &quot;Could not find net.jmglov.awno_http.edn on classpath.&quot;))
      1 (-&gt; cfgs first read-config :constructor-var)

      (throw (ex-info &quot;Found too many http-client cfgs. Pick one.&quot; {:config cfgs})))))
</code></pre><p>Let&apos;s just follow grzm&apos;s lead and rip it out:</p><pre><code class="language-clojure">(defn- configured-client
  &quot;If a single com_grzm_awyeah_http.edn is found on the classpath,
  returns the symbol bound to :constructor-var.

  Throws if 0 or &gt; 1 com_grzm_awyeah_http.edn files are found.
  &quot;
  []
  (try
    (-&gt; (io/resource &quot;net_jmglov_awno_http.edn&quot;) read-config :constructor-var)
    (catch Throwable _
      (throw (RuntimeException. &quot;Could not find com_grzm_awyeah_http.edn on classpath.&quot;)))))
</code></pre><p>This <code>dynaload</code> stuff also looks a bit unnecessary, so let&apos;s flush it as well by turning this:</p><pre><code class="language-clojure">(defn resolve-http-client
  [http-client-or-sym]
  (let [c (or (when (symbol? http-client-or-sym)
                (let [ctor @(dynaload/load-var http-client-or-sym)]
                  (ctor)))
              http-client-or-sym
              (let [ctor @(dynaload/load-var (configured-client))]
                (ctor)))]
    (when-not (client? c)
      (throw (ex-info &quot;not an http client&quot; {:provided http-client-or-sym
                                            :resolved c})))
    c))
</code></pre><p>Into that:</p><pre><code class="language-clojure">(defn resolve-http-client
  [http-client-or-sym]
  (let [c (or (when (symbol? http-client-or-sym)
                (let [ctor (requiring-resolve http-client-or-sym)]
                  (ctor)))
              http-client-or-sym
              (let [ctor (requiring-resolve (configured-client))]
                (ctor)))]
    (when-not (client? c)
      (throw (ex-info &quot;not an http client&quot; {:provided http-client-or-sym
                                            :resolved c})))
    c))
</code></pre><p>This now means that we&apos;re gonna need <code>clojure.java.io</code>, so let&apos;s pop up to the <code>ns</code> form and require it. And whilst we&apos;re at it, we can get rid of this suspicious <code>net.jmglov.awno.dynaload</code> require, and kill the associated source file with fire! That leaves us with an <code>ns</code> form like this:</p><pre><code class="language-clojure">(ns ^:skip-wiki net.jmglov.awno.http
  &quot;Impl, don&apos;t call directly.&quot;
  (:require [clojure.edn :as edn]
            [clojure.core.async :as a]
            [clojure.java.io :as io]))
</code></pre><p>We&apos;re also going to need the <code>net_jmglov_awno_http.edn</code> file mentioned above. We can just modify the original <code>cognitect_aws_http.edn</code>, so this:</p><pre><code class="language-clojure">{:constructor-var net.jmglov.awno.http.cognitect/create}
</code></pre><p>Becomes that:</p><pre><code class="language-clojure">{:constructor-var net.jmglov.awno.http.awno/create}
</code></pre><p>Once this is done, we just need to rename the file to <code>net_jmglov_awno_http.edn</code> and Robert should be one of our parents&apos; brother. Oh yeah, and since we changed some stuff in resources, a <code>C-c M-r</code> to invoke <code>cider-restart</code> is sadly required. 😢</p><p>Continuing on our mission to civilise HTTP, let&apos;s turn our roving eye to the <code>net.jmglov.awno.http.awno</code> namespace, which is sadly not there, because our original <code>projectile-replace</code> of <code>cognitect.aws</code> with <code>net.jmglov.awno</code> left us with a file called <code>src/net/jmglov/awno/http/cognitect.clj</code> with a namespace of <code>net.jmglov.awno.http.cognitect</code>. We can fix the name easily enough, but looking at awyeah-api&apos;s <code>src/com/grzm/awyeah/http/awyeah.clj</code>, we see that he&apos;s replaced <code>cognitect.http-client</code> with a custom <code>com.grzm.awyeah.http-client</code>. Let&apos;s follow the same pattern:</p><pre><code class="language-clojure">(ns ^:skip-wiki net.jmglov.awno.http.awno
  (:require [net.jmglov.awno.http :as aws]
            [net.jmglov.awno.http-client :as impl]))

(set! *warn-on-reflection* true)

(defn create
  []
  (let [c (impl/create nil)]
    (reify aws/HttpClient
      (-submit [_ request channel]
        (impl/submit c request channel))
      (-stop [_]
        (impl/stop c)))))
</code></pre><p>We&apos;ll also need to rename the file from <code>cognitect.clj</code> to <code>awno.clj</code>. Having done this, it&apos;s time to write <code>net.jmglov.awno.http-client</code>.</p><div class="markdown-heading"><h2 id="what&apos;s-in-a-client,-anyway?">What&apos;s in a client, anyway?</h2><a href="#what&apos;s-in-a-client,-anyway?" class="anchor" aria-label="Permalink: What&apos;s in a client, anyway?"><img src="assets/link.svg" /></a></div><p>Let&apos;s start by straight up copying awyeah-api&apos;s <a href="https://github.com/grzm/awyeah-api/blob/main/src/com/grzm/awyeah/http_client.clj">com/grzm/awyeah/http_client.clj</a> and replacing all the occurrences of <code>com.grzm.awyeah</code> with <code>net.jmglov.awno</code> to jmglovify it:</p><pre><code class="language-clojure">(ns net.jmglov.awno.http-client
  (:require
   [clojure.core.async :refer [put!] :as a]
   [clojure.spec.alpha :as s]
   [net.jmglov.awno.http-client.client :as client]
   [net.jmglov.awno.http-client.specs])
  (:import
   (clojure.lang ExceptionInfo)
   (java.net URI)
   (java.net.http HttpClient
                  HttpClient$Redirect
                  HttpHeaders
                  HttpRequest
                  HttpRequest$Builder
                  HttpRequest$BodyPublishers
                  HttpResponse
                  HttpResponse$BodyHandlers)
   (java.nio ByteBuffer)
   (java.time Duration)
   (java.util.function Function)))

(set! *warn-on-reflection* true)

(defn submit
  &quot;Submit an http request, channel will be filled with response. Returns ch.

  Request map:

  :server-name        string
  :server-port         integer
  :uri                string
  :query-string       string, optional
  :request-method     :get/:post/:put/:head
  :scheme             :http or :https
  :headers            map from downcased string to string
  :body               ByteBuffer, optional
  :net.jmglov.awno.http-client/timeout-msec   opt, total request send/receive timeout
  :net.jmglov.awno.http-client/meta           opt, data to be added to the response map

  content-type must be specified in the headers map
  content-length is derived from the ByteBuffer passed to body

  Response map:

  :status              integer HTTP status code
  :body                ByteBuffer, optional
  :header              map from downcased string to string
  :net.jmglov.awno.http-client/meta           opt, data from the request

  On error, response map is per cognitect.anomalies&quot;
  ([client request]
   (submit client request (a/chan 1)))
  ([client request ch]
   (s/assert ::submit-request request)
   (client/submit client request ch)))

(def method-string
  {:get &quot;GET&quot;
   :post &quot;POST&quot;
   :put &quot;PUT&quot;
   :head &quot;HEAD&quot;
   :delete &quot;DELETE&quot;
   :patch &quot;PATCH&quot;})

(defn byte-buffer-&gt;byte-array
  [^ByteBuffer bbuf]
  (.rewind bbuf)
  (let [arr (byte-array (.remaining bbuf))]
    (.get bbuf arr)
    arr))

(defn flatten-headers [headers]
  (-&gt;&gt; headers
       (mapcat (fn [[nom val]]
                 (if (coll? val)
                   (map (fn [v] [(name nom) v]) val)
                   [[(name nom) val]])))))

;; &quot;host&quot; is a restricted header.
;; The host header is part of the AWS signed headers signature,
;; so it&apos;s included in the list of headers for request processing,
;; but we let the java.net.http HttpRequest assign the host header
;; from the URI rather than setting it directly.
(def restricted-headers #{&quot;host&quot;})

(defn add-headers
  [^HttpRequest$Builder builder headers]
  (doseq [[nom val] (-&gt;&gt; (flatten-headers headers)
                         (remove (fn [[nom _]] (restricted-headers nom))))]
    (.header builder nom val))
  builder)

(defn map-&gt;http-request
  [{:keys [scheme server-name server-port uri query-string
           request-method headers body]
    :or {scheme &quot;https&quot;}
    :as m}]
  (let [uri (URI. (str (name scheme)
                       &quot;://&quot;
                       server-name
                       (some-&gt;&gt; server-port (str &quot;:&quot;))
                       uri
                       (some-&gt;&gt; query-string (str &quot;?&quot;))))
        method (method-string request-method)
        bp (if body
             (HttpRequest$BodyPublishers/ofByteArray (byte-buffer-&gt;byte-array body))
             (HttpRequest$BodyPublishers/noBody))
        builder (-&gt; (HttpRequest/newBuilder uri)
                    (.method ^String method bp))]
    (when (seq headers)
      (add-headers builder headers))
    (when (::timeout-msec m)
      (.timeout builder (Duration/ofMillis (::timeout-msec m))))
    (.build builder)))

(defn error-&gt;anomaly [^Throwable t]
  {:cognitect.anomalies/category :cognitect.anomalies/fault
   :cognitect.anomalies/message (.getMessage t)
   ::throwable t})

(defn header-map [^HttpHeaders headers]
  (-&gt;&gt; headers
       (.map)
       (map (fn [[k v]] [k (if (&lt; 1 (count v))
                             (into [] v)
                             (first v))]))
       (into {})))

(defn response-body?
  [^HttpRequest http-request]
  ((complement #{&quot;HEAD&quot;}) (.method http-request)))

(defn response-map
  [^HttpRequest http-request ^HttpResponse http-response]
  (let [body (when (response-body? http-request)
               (.body http-response))]
    (cond-&gt; {:status (.statusCode http-response)
             :headers (header-map (.headers http-response))}
      body (assoc :body (ByteBuffer/wrap body)))))

(defrecord Client
    [^HttpClient http-client pending-ops pending-ops-limit]
  client/Client
  (-submit [_ request ch]
    (if (&lt; pending-ops-limit (swap! pending-ops inc))
      (do
        (put! ch (merge {:cognitect.anomalies/category :cognitect.anomalies/busy
                         :cognitect.anomalies/message (str &quot;Ops limit reached: &quot; pending-ops-limit)
                         :pending-ops-limit pending-ops-limit}
                        (select-keys request [::meta])))
        (swap! pending-ops dec))
      (try
        (let [http-request (map-&gt;http-request request)]
          (-&gt; (.sendAsync http-client http-request (HttpResponse$BodyHandlers/ofByteArray))
              (.thenApply
                (reify Function
                  (apply [_ http-response]
                    (put! ch (merge (response-map http-request http-response)
                                    (select-keys request [::meta]))))))
              (.exceptionally
                (reify Function
                  (apply [_ e]
                    (let [cause (.getCause ^Exception e)
                          t (if (instance? ExceptionInfo cause) cause e)]
                      (put! ch (merge (error-&gt;anomaly t) (select-keys request [::meta]))))))))
          (swap! pending-ops dec))
        (catch Throwable t
          (put! ch (merge (error-&gt;anomaly t) (select-keys request [::meta])))
          (swap! pending-ops dec))))
    ch))

(defn create
  [{:keys [connect-timeout-msecs
           pending-ops-limit]
    :or {connect-timeout-msecs 5000
         pending-ops-limit 64}
    :as _config}]
  (let [http-client (.build (-&gt; (HttpClient/newBuilder)
                                (.connectTimeout (Duration/ofMillis connect-timeout-msecs))
                                (.followRedirects HttpClient$Redirect/NORMAL)))]
    (-&gt;Client http-client (atom 0) pending-ops-limit)))

(defn stop
  &quot;no-op. Implemented for compatibility&quot;
  [^Client _client])
</code></pre><p>Now we need to create those <code>net.jmglov.awno.http-client.client</code> and <code>net.jmglov.awno.http-client.specs</code> namespaces, so we can make copies of <a href="https://github.com/grzm/awyeah-api/blob/main/src/com/grzm/awyeah/http_client/client.clj">com/grzm/awyeah/http_client/client.clj</a> and <a href="https://github.com/grzm/awyeah-api/blob/main/src/com/grzm/awyeah/http_client/specs.clj">com/grzm/awyeah/http_client/specs.clj</a> and replace all the occurrences of <code>com.grzm.awyeah</code> with <code>net.jmglov.awno</code>, giving us this:</p><pre><code class="language-clojure">(ns net.jmglov.awno.http-client.client)

(defprotocol Client
  (-submit [_ request ch]))

(defn submit [client request ch]
  (-submit client request ch))
</code></pre><p>And this:</p><pre><code class="language-clojure">(ns net.jmglov.awno.http-client.specs
  (:require
   [clojure.spec.alpha :as s])
  (:import
   (java.nio ByteBuffer)))

(defn- keyword-or-non-empty-string? [x]
  (or (keyword? x)
      (and (string? x) (not-empty x))))

(s/def :net.jmglov.awno.http-client/server-name string?)
(s/def :net.jmglov.awno.http-client/server-port int?)
(s/def :net.jmglov.awno.http-client/uri string?)
(s/def :net.jmglov.awno.http-client/request-method keyword?)
(s/def :net.jmglov.awno.http-client/scheme keyword-or-non-empty-string?)
(s/def :net.jmglov.awno.http-client/timeout-msec int?)
(s/def :net.jmglov.awno.http-client/meta map?)
(s/def :net.jmglov.awno.http-client/body (s/nilable #(instance? ByteBuffer %)))
(s/def :net.jmglov.awno.http-client/query-string string?)
(s/def :net.jmglov.awno.http-client/headers map?)

(s/def :net.jmglov.awno.http-client/submit-request
  (s/keys :req-un [:net.jmglov.awno.http-client/server-name
                   :net.jmglov.awno.http-client/server-port
                   :net.jmglov.awno.http-client/uri
                   :net.jmglov.awno.http-client/request-method
                   :net.jmglov.awno.http-client/scheme]
          :opt [:net.jmglov.awno.http-client/timeout-msec
                :net.jmglov.awno.http-client/meta]
          :opt-un [:net.jmglov.awno.http-client/body
                   :net.jmglov.awno.http-client/query-string
                   :net.jmglov.awno.http-client/headers]))

(s/def :net.jmglov.awno.http-client/status int?)

(s/def :net.jmglov.awno.http-client/submit-http-response
  (s/keys :req-un [:net.jmglov.awno.http-client/status]
          :opt [:net.jmglov.awno.http-client/meta]
          :opt-un [:net.jmglov.awno.http-client/body
                   :net.jmglov.awno.http-client/headers]))

(s/def :net.jmglov.awno.http-client/error keyword?)
(s/def :net.jmglov.awno.http-client/throwable #(instance? Throwable %))

(s/def :net.jmglov.awno.http-client/submit-error-response
  (s/keys :req [:net.jmglov.awno.http-client/error]
          :opt [:net.jmglov.awno.http-client/throwable
                :net.jmglov.awno.http-client/meta]))

(s/def :net.jmglov.awno.http-client/submit-response
  (s/or :http-response :net.jmglov.awno.http-client/submit-http-response
        :error-response :net.jmglov.awno.http-client/submit-error-response))
</code></pre><div class="markdown-heading"><h2 id="taking-stock-of-the-situation">Taking stock of the situation</h2><a href="#taking-stock-of-the-situation" class="anchor" aria-label="Permalink: Taking stock of the situation"><img src="assets/link.svg" /></a></div><p>Having done everything that&apos;s obvious from <code>porting-decisions.markdown</code>, we might as well just see if it works. But before we do that, how about a...</p><p><img alt="Sylvester Stallone hangs from a cliff" src="assets/2023-11-11-cliffhanger.jpg" title="borkdude at work" /></p><p>See you next week for the thrilling conclusion of the trainwreck that is me attempting to replace an oil filter by completely disassembling the car and making my own oil filter out of paper towels and a coathanger I found lying around. What could possibly go wrong?</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2023-01-04-blambda-analyses-sites.html</id>
    <link href="https://jmglov.net/blog/2023-01-04-blambda-analyses-sites.html"/>
    <title>Blambda analyses sites</title>
    <updated>2023-01-04T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>I&apos;m giving a talk on <a href="https://github.com/jmglov/blambda">Blambda</a> later this month at a local meetup group or two, and since I&apos;m an experienced speaker, the talk is completely prepared, so now I have three weeks to rehearse it... in an alternate reality where I&apos;m not a huge procrastinator, that is.</p><p>In this reality, I haven&apos;t even written an outline for the talk, despite convincing myself that I was going to do that over the holiday break. I was able to convince myself that before I write the outline, I should just hack on Blambda a little more to make sure it actually works. 😅</p><p>A while back, I read a post on Cyprien Pannier&apos;s blog called <a href="https://www.loop-code-recur.io/simple-site-analytics-with-serverless-clojure/">Serverless site
analytics with Clojure nbb and
AWS</a>. It was a fantastic post, except for one thing: it was based on the hated <a href="https://github.com/babashka/nbb">nbb</a>, surely borkdude&apos;s greatest sin!</p><p>I decided I could make the world a better place by doing the same thing, but using Babashka instead of the unholy nbb. Now that Blambda is all grown up and has a <a href="https://github.com/jmglov/blambda/releases/tag/v0.1.0">v0.1.0 release</a>, it was the work of but a moment (for a definition of &quot;moment&quot; that spans several days) to implement a site analyser!</p><p><img alt="Movie poster for Analyze This" src="assets/2023-01-04-preview.png" title="Analyse this!" /></p><p>If you&apos;re the impatient sort, you can just take a look at <a href="https://github.com/jmglov/blambda/tree/v0.1.0/examples/site-analyser">examples/site-analyser</a> in the Blambda repo, but if you wanna see how the sausage is made, buckle up, &apos;cause Kansas is going bye-bye!</p><div class="markdown-heading"><h2 id="getting-started">Getting started</h2><a href="#getting-started" class="anchor" aria-label="Permalink: Getting started"><img src="assets/link.svg" /></a></div><p>Any great Babashka project starts with an empty directory, so let&apos;s make one!</p><pre><code class="language-text">$ mkdir site-analyser
$ cd site-analyser
</code></pre><p>We&apos;ll now add a <code>bb.edn</code> so we can start playing with Blambda:</p><pre><code class="language-clojure">{:deps {net.jmglov/blambda
        {:git/url &quot;https://github.com/jmglov/blambda.git&quot;
         :git/tag &quot;v0.1.0&quot;
         :git/sha &quot;b80ac1d&quot;}}
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {}))

  blambda {:doc &quot;Controls Blambda runtime and layers&quot;
           :task (blambda/dispatch config)}}}
</code></pre><p>This is enough to get us up and running with Blambda! Let&apos;s ask for help to see how to get going:</p><pre><code class="language-text">$ bb blambda help
Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

All subcommands support the options:
                                                                                                   --work-dir   &lt;dir&gt; .work  Working directory
  --target-dir &lt;dir&gt; target Build output directory

Subcommands:

build-runtime-layer: Builds Blambda custom runtime layer
  --bb-arch            &lt;arch&gt;    amd64   Architecture to target (use amd64 if you don&apos;t care)
  --runtime-layer-name &lt;name&gt;    blambda Name of custom runtime layer in AWS
  --bb-version         &lt;version&gt; 1.0.168 Babashka version

...
</code></pre><p>Might as well try to build the custom runtime layer, which is what allows lambdas to be written in Babashka in the first place:</p><pre><code class="language-text">$ bb blambda build-runtime-layer

Building custom runtime layer: /tmp/site-analyser/target/blambda.zip
Downloading https://github.com/babashka/babashka/releases/download/v1.0.168/babashka-1.0.168-linux-amd64-static.tar.gz
Decompressing .work/babashka-1.0.168-linux-amd64-static.tar.gz to .work
Adding file: bootstrap
Adding file: bootstrap.clj
Compressing custom runtime layer: /tmp/site-analyser/target/blambda.zip
  adding: bb (deflated 70%)
  adding: bootstrap (deflated 53%)
  adding: bootstrap.clj (deflated 62%)

$ ls -sh target/
total 21M
21M blambda.zip
</code></pre><p>Cool, looks legit!</p><div class="markdown-heading"><h2 id="blasting-off-with-graviton2">Blasting off with Graviton2</h2><a href="#blasting-off-with-graviton2" class="anchor" aria-label="Permalink: Blasting off with Graviton2"><img src="assets/link.svg" /></a></div><p>AWS being AWS, of course they had to go and design their own CPU. 🙄</p><p>It&apos;s called <a href="https://aws.amazon.com/ec2/graviton/">Graviton</a>, and it&apos;s based on the ARM architecture. A little over a year ago, it became possible to <a href="https://aws.amazon.com/blogs/aws/aws-lambda-functions-powered-by-aws-graviton2-processor-run-your-functions-on-arm-and-get-up-to-34-better-price-performance/">run
lambda functions on
Graviton</a>, which AWS claims delivers &quot;up to 19 percent better performance at 20 percent lower cost&quot;. That&apos;s party I definitely wanna go to, and luckily for me, it just so happens that Babashka runs on ARM! 🎉 I love borkdude so much that I can almost forgive him for the dark alchemy that wrought nbb! Almost.</p><p>We can instruct Blambda to use the ARM version of Babashka by adding a key to the <code>config</code> map in <code>bb.edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;}))
  ...
</code></pre><p>Let&apos;s rebuild the runtime layer and see what&apos;s up:</p><pre><code class="language-text">$ bb blambda build-runtime-layer

Building custom runtime layer: /tmp/site-analyser/target/blambda.zip
Downloading https://github.com/babashka/babashka/releases/download/v1.0.168/babashka-1.0.168-linux-aarch64-static.tar.gz
Decompressing .work/babashka-1.0.168-linux-aarch64-static.tar.gz to .work
Adding file: bootstrap
Adding file: bootstrap.clj
Compressing custom runtime layer: /tmp/site-analyser/target/blambda.zip
updating: bb (deflated 73%)
updating: bootstrap (deflated 53%)
updating: bootstrap.clj (deflated 62%)
</code></pre><p>That <code>babashka-1.0.168-linux-aarch64-static.tar.gz</code> looks promising!</p><div class="markdown-heading"><h2 id="say-hello-to-my-little-friend">Say hello to my little friend</h2><a href="#say-hello-to-my-little-friend" class="anchor" aria-label="Permalink: Say hello to my little friend"><img src="assets/link.svg" /></a></div><p>OK, so we have a custom runtime. That&apos;s awesome and all, but without a lambda function, a runtime is a bit passé, don&apos;t you think? Let&apos;s remedy this with the simplest of lambdas, the infamous Hello World. Except let&apos;s make it say &quot;Hello Blambda&quot; instead to make it more amazing!</p><p>All we need to accomplish this is a simple handler. Let&apos;s create a <code>src/handler.clj</code> and drop the following into it:</p><pre><code class="language-clojure">(ns handler)

(defn handler [{:keys [name] :or {name &quot;Blambda&quot;} :as event} context]
  (prn {:msg &quot;Invoked with event&quot;,
        :data {:event event}})
  {:greeting (str &quot;Hello &quot; name &quot;!&quot;)})
</code></pre><p>Now we&apos;ll need to tell Blambda what our lambda function should be called, where to find the sources, and what handler function to use. Back in <code>bb.edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;
                       :lambda-name &quot;site-analyser&quot;
                       :lambda-handler &quot;handler/handler&quot;
                       :source-files [&quot;handler.clj&quot;]}))
  ...
</code></pre><p>Now that we&apos;ve done this, we can build the lambda:</p><pre><code class="language-text">$ bb blambda build-lambda

Building lambda artifact: /tmp/site-analyser/target/site-analyser.zip
Adding file: handler.clj
Compressing lambda: /tmp/site-analyser/target/site-analyser.zip
  adding: handler.clj (deflated 25%)

$ ls -sh target/
total 22M
 22M blambda.zip  4.0K site-analyser.zip
</code></pre><p>Amazing! I love the fact that the entire lambda artifact is only 4 KB!</p><div class="markdown-heading"><h2 id="changing-the-world-with-terraform">Changing the world with Terraform</h2><a href="#changing-the-world-with-terraform" class="anchor" aria-label="Permalink: Changing the world with Terraform"><img src="assets/link.svg" /></a></div><p>Of course, this is still academic until we deploy the function to the world, so let&apos;s stop messing about and do it! For the rest of this post, I am going to assume that one of the following applies to you:</p><ol start="1"><li>You have a 1.x version of <a href="https://www.terraform.io/">Terraform</a> installed, or</li><li>You have Nix installed (or are running on NixOS) and have run <code>nix-shell -p terraform</code> in your site-analyser directory</li></ol><p>Since one of those two options is true, let&apos;s generate ourselves some Terraform config!</p><pre><code class="language-text">$ bb blambda terraform write-config
Writing lambda layer config: /tmp/site-analyser/target/blambda.tf
Writing lambda layer vars: /tmp/site-analyser/target/blambda.auto.tfvars
Writing lambda layers module: /tmp/site-analyser/target/modules/lambda_layer.tf

$ find target/
target/
target/site-analyser.zip
target/blambda.zip
target/modules
target/modules/lambda_layer.tf
target/blambda.auto.tfvars
target/blambda.tf
</code></pre><p>Note the <code>blambda.tf</code>, <code>blambda.auto.tfvars</code>, and <code>modules/lambda_layer.tf</code> files there. If you&apos;re a Terraform aficionado, feel free to take a look at these; I&apos;ll just give you the highlights here.</p><p><code>blambda.tf</code> defines the following resources:</p><ul><li><code>aws_lambda_function.lambda</code> - the lambda function itself</li><li><code>aws_cloudwatch_log_group.lambda</code> - a CloudWatch log group for the lambda function to log to</li><li><code>aws_iam_role.lambda</code> - the IAM role that the lambda function will assume</li><li><code>aws_iam_policy.lambda</code> - an IAM policy describing what the lambda function is allowed to do (in this case, just write logs to its own log group)</li><li><code>aws_iam_role_policy_attachment.lambda</code> - a virtual Terraform resource that represents the attachment of the policy to the role</li><li><code>module.runtime.aws_lambda_layer_version.layer</code> - the custom runtime layer</li></ul><p><code>blambda.auto.tfvars</code> sets various Terraform variables. The details are too boring to relate, but you are welcome to look at the file if your curiosity overwhelms you. 😉</p><p><code>modules/lambda_layer.tf</code> defines a Terraform module that creates a lambda layer. The reason it&apos;s in a module and not just inline in the <code>blambda.tf</code> will become apparent later.</p><div class="markdown-heading"><h2 id="just-deploy-the-thing-already!">Just deploy the thing already!</h2><a href="#just-deploy-the-thing-already!" class="anchor" aria-label="Permalink: Just deploy the thing already!"><img src="assets/link.svg" /></a></div><p>OK, now that I&apos;ve gone into what is almost certainly too much detail on stuff that you almost certainly don&apos;t care about, let&apos;s just deploy the function!</p><pre><code class="language-text">$ bb blambda terraform apply
Initializing modules...
- runtime in modules

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v4.48.0...
- Installed hashicorp/aws v4.48.0 (signed by HashiCorp)

[...]

Terraform has been successfully initialized!

[...]

Terraform will perform the following actions:

  # aws_cloudwatch_log_group.lambda will be created
  + resource &quot;aws_cloudwatch_log_group&quot; &quot;lambda&quot; {

  # aws_iam_policy.lambda will be created
  + resource &quot;aws_iam_policy&quot; &quot;lambda&quot; {

  # aws_iam_role.lambda will be created
  + resource &quot;aws_iam_role&quot; &quot;lambda&quot; {
                                                                                                   # aws_iam_role_policy_attachment.lambda will be created
  + resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda&quot; {

  # aws_lambda_function.lambda will be created
  + resource &quot;aws_lambda_function&quot; &quot;lambda&quot; {

  # module.runtime.aws_lambda_layer_version.layer will be created
  + resource &quot;aws_lambda_layer_version&quot; &quot;layer&quot; {

[...]

Plan: 6 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only &apos;yes&apos; will be accepted to approve.

  Enter a value:
</code></pre><p>Let&apos;s be brave and type &quot;yes&quot; and then give the Enter key a resounding smackaroo! We should see something along the lines of this:</p><pre><code class="language-text">aws_cloudwatch_log_group.lambda: Creating...
aws_iam_role.lambda: Creating...
module.runtime.aws_lambda_layer_version.layer: Creating...
aws_cloudwatch_log_group.lambda: Creation complete after 1s [id=/aws/lambda/site-analyser]
aws_iam_policy.lambda: Creating...
aws_iam_policy.lambda: Creation complete after 1s [id=arn:aws:iam::123456789100:policy/site-analyser]
aws_iam_role.lambda: Creation complete after 2s [id=site-analyser]
aws_iam_role_policy_attachment.lambda: Creating...
aws_iam_role_policy_attachment.lambda: Creation complete after 1s [id=site-analyser-20230103173233475200000001]
module.runtime.aws_lambda_layer_version.layer: Still creating... [10s elapsed]
module.runtime.aws_lambda_layer_version.layer: Still creating... [20s elapsed]
module.runtime.aws_lambda_layer_version.layer: Still creating... [30s elapsed]
module.runtime.aws_lambda_layer_version.layer: Creation complete after 31s [id=arn:aws:lambda:eu-west-1:123456789100:layer:blambda:30]
aws_lambda_function.lambda: Creating...
aws_lambda_function.lambda: Still creating... [10s elapsed]
aws_lambda_function.lambda: Creation complete after 11s [id=site-analyser]

Apply complete! Resources: 6 added, 0 changed, 0 destroyed.
</code></pre><p>OK, let&apos;s try invoking the function:</p><pre><code class="language-text">$ aws lambda invoke --function-name site-analyser /tmp/response.json
{
    &quot;StatusCode&quot;: 200,
    &quot;ExecutedVersion&quot;: &quot;$LATEST&quot;
}

$ cat /tmp/response.json
{&quot;greeting&quot;:&quot;Hello Blambda!&quot;}
</code></pre><p>According to the handler, we can also pass a name in:</p><pre><code class="language-text">$ aws lambda invoke --function-name site-analyser --payload &apos;{&quot;name&quot;: &quot;Dear Reader&quot;}&apos; /tmp/response.json
{
    &quot;StatusCode&quot;: 200,
    &quot;ExecutedVersion&quot;: &quot;$LATEST&quot;
}

$ cat /tmp/response.json 
{&quot;greeting&quot;:&quot;Hello Dear Reader!&quot;}
</code></pre><p>Looks like we&apos;re live in the cloud!</p><div class="markdown-heading"><h2 id="http-ftw!">HTTP FTW!</h2><a href="#http-ftw!" class="anchor" aria-label="Permalink: HTTP FTW!"><img src="assets/link.svg" /></a></div><p>It&apos;s pretty annoying to have to use the AWS CLI to invoke our function, what with all of the writing the response to a file and all that jazz. Luckily, <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html">Lambda function
URLs</a> offer us a way out of this never-ending agony. All we need to do is add one simple Terraform resource.</p><p>Let&apos;s create a <code>tf/main.tf</code> and define our function URL:</p><pre><code class="language-terraform">resource &quot;aws_lambda_function_url&quot; &quot;lambda&quot; {
  function_name = aws_lambda_function.lambda.function_name
  authorization_type = &quot;NONE&quot;
}

output &quot;function_url&quot; {
  value = aws_lambda_function_url.lambda.function_url
}
</code></pre><p>When using a function URL, the event passed to the lambda function looks a little different. Referring to the <a href="https://docs.aws.amazon.com/lambda/latest/dg/urls-invocation.html#urls-payloads">Request and response
payloads</a> page in the AWS Lambda developer guide, we hone in on the important bits:</p><p><strong>Request</strong></p><pre><code class="language-json">{
  &quot;queryStringParameters&quot;: {
    &quot;parameter1&quot;: &quot;value1,value2&quot;,
    &quot;parameter2&quot;: &quot;value&quot;
  },
  &quot;requestContext&quot;: {
    &quot;http&quot;: {
      &quot;method&quot;: &quot;POST&quot;,
      &quot;path&quot;: &quot;/my/path&quot;,
    }
  }
}
</code></pre><p><strong>Response</strong></p><pre><code class="language-json">{
  &quot;statusCode&quot;: 201,
  &quot;headers&quot;: {
    &quot;Content-Type&quot;: &quot;application/json&quot;,
    &quot;My-Custom-Header&quot;: &quot;Custom Value&quot;
  },
  &quot;body&quot;: &quot;{ \&quot;message\&quot;: \&quot;Hello, world!\&quot; }&quot;
}
</code></pre><p>Let&apos;s update our handler to log the method and path and grab the optional <code>name</code> from the query params. Our new <code>src/handler.clj</code> now looks like this:</p><pre><code class="language-clojure">(ns handler
  (:require [cheshire.core :as json]))

(defn log [msg data]
  (prn (assoc data :msg msg)))

(defn handler [{:keys [queryStringParameters requestContext] :as event} _context]
  (log &quot;Invoked with event&quot; {:event event})
  (let [{:keys [method path]} (:http requestContext)
        {:keys [name] :or {name &quot;Blambda&quot;}} queryStringParameters]
    (log (format &quot;Request: %s %s&quot; method path)
         {:method method, :path path, :name name})
    {:statusCode 200
     :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
     :body (json/generate-string {:greeting (str &quot;Hello &quot; name &quot;!&quot;)})}))
</code></pre><p>The final step before we can deploy this gem is letting Blambda know that we want to include some extra Terraform config. For this, we set the <code>:extra-tf-config</code> key in <code>bb.edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;
                       :lambda-name &quot;site-analyser&quot;
                       :lambda-handler &quot;handler/handler&quot;
                       :source-files [&quot;handler.clj&quot;]
                       :extra-tf-config [&quot;tf/main.tf&quot;]}))
  ...
</code></pre><p>Now that all of this is done, let&apos;s rebuild our lambda, regenerate our Terraform config, and deploy away!</p><pre><code class="language-text">$ bb blambda build-lambda

Building lambda artifact: /tmp/site-analyser/target/site-analyser.zip
Adding file: handler.clj
Compressing lambda: /tmp/site-analyser/target/site-analyser.zip
updating: handler.clj (deflated 43%)

$ bb blambda terraform write-config
Copying Terraform config tf/main.tf
Writing lambda layer config: /tmp/site-analyser/target/blambda.tf
Writing lambda layer vars: /tmp/site-analyser/target/blambda.auto.tfvars
Writing lambda layers module: /tmp/site-analyser/target/modules/lambda_layer.tf

$ bb blambda terraform apply
                                                                                                 
Terraform will perform the following actions:

  # aws_lambda_function.lambda will be updated in-place
  ~ resource &quot;aws_lambda_function&quot; &quot;lambda&quot; {

  # aws_lambda_function_url.lambda will be created
  + resource &quot;aws_lambda_function_url&quot; &quot;lambda&quot; {

Plan: 1 to add, 1 to change, 0 to destroy.

Changes to Outputs:
  + function_url = (known after apply)

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only &apos;yes&apos; will be accepted to approve.

  Enter a value: yes

aws_lambda_function.lambda: Modifying... [id=site-analyser]
aws_lambda_function.lambda: Modifications complete after 7s [id=site-analyser]
aws_lambda_function_url.lambda: Creating...
aws_lambda_function_url.lambda: Creation complete after 1s [id=site-analyser]

Apply complete! Resources: 1 added, 1 changed, 0 destroyed.

Outputs:

function_url = &quot;https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/&quot;
</code></pre><p>Looks great! The <code>function_url</code> is the base URL we&apos;ll use to make HTTP requests to our lambda. We can try it out with curl:</p><pre><code class="language-text">$ export BASE_URL=https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/

$ curl $BASE_URL
{&quot;greeting&quot;:&quot;Hello Blambda!&quot;}

$ curl $BASE_URL?name=&apos;Dear%20Reader&apos;
{&quot;greeting&quot;:&quot;Hello Dear Reader!&quot;}
</code></pre><div class="markdown-heading"><h2 id="logging-isn&apos;t-just-for-lumberjacks">Logging isn&apos;t just for lumberjacks</h2><a href="#logging-isn&apos;t-just-for-lumberjacks" class="anchor" aria-label="Permalink: Logging isn&apos;t just for lumberjacks"><img src="assets/link.svg" /></a></div><p>Before we move on, let&apos;s take a quick look at our logs. Lambda functions automatically log anything printed to standard output to a log stream in a log group named <code>/aws/lambda/{function_name}</code> (as long as they have permission to do so, which Blambda takes care of for us in the default IAM policy). Let&apos;s see what log streams we have in our <code>/aws/lambda/site-analyser</code> group:</p><pre><code class="language-text">$ aws logs describe-log-streams --log-group /aws/lambda/site-analyser \
    | jq &apos;.logStreams | .[].log[18/1807]e&apos;
&quot;2023/01/03/[$LATEST]f8a5d5be9e0c4d34bcf6c8bb55e9c577&quot;
&quot;2023/01/04/[$LATEST]98a0ab46e2994cdda668124ccae610fc&quot;
</code></pre><p>We have two streams since we&apos;ve tested our lambda twice (requests around the same time are batched into a single log stream). Let&apos;s pick the most recent one and see what it says:</p><pre><code class="language-text">$ aws logs get-log-events \
  --log-group /aws/lambda/site-analyser \
  --log-stream &apos;2023/01/04/[$LATEST]98a0ab46e2994cdda668124ccae610fc&apos; \
  | jq -r &apos;.events|.[].message&apos;
Starting Babashka:
/opt/bb -cp /var/task /opt/bootstrap.clj
Loading babashka lambda handler: handler/handler

Starting babashka lambda event loop

START RequestId: 09a33775-0151-4d83-9a9b-b21b8add2b3a Version: $LATEST

{:event {:version &quot;2.0&quot;, :routeKey &quot;$default&quot;, :rawPath &quot;/&quot;, ...}

{:method &quot;GET&quot;, :path &quot;/&quot;, :name &quot;Blambda&quot;, :msg &quot;Request: GET /&quot;}

END RequestId: 09a33775-0151-4d83-9a9b-b21b8add2b3a

REPORT RequestId: 09a33775-0151-4d83-9a9b-b21b8add2b3a  Duration: 56.87 ms      Billed Duration: 507 ms Memory Size: 512 MB     Max Memory Used: 125 MB Init Duration: 450.02 ms

START RequestId: 0fca5efe-2644-4ebd-80ce-ebb390ffcaf4 Version: $LATEST

{:event {:version &quot;2.0&quot;, :routeKey &quot;$default&quot;, :rawPath &quot;/&quot;, ...}

{:method &quot;GET&quot;, :path &quot;/&quot;, :name &quot;Dear Reader&quot;, :msg &quot;Request: GET /&quot;}

END RequestId: 0fca5efe-2644-4ebd-80ce-ebb390ffcaf4

REPORT RequestId: 0fca5efe-2644-4ebd-80ce-ebb390ffcaf4  Duration: 2.23 ms       Billed Duration: 3 ms   Memory Size: 512 MB     Max Memory Used: 125 MB
</code></pre><p>There are a few things of interest here. First of all, we can see the Blambda custom runtime starting up:</p><pre><code class="language-text">Starting Babashka:
/opt/bb -cp /var/task /opt/bootstrap.clj
Loading babashka lambda handler: handler/handler

Starting babashka lambda event loop
</code></pre><p>This only happens on a so-called &quot;cold start&quot;, which is when there is no lambda instance available to serve an invocation request. We always have a cold start on the first invocation of a lambda after it&apos;s deployed (i.e. on every code change), and then the lambda will stay warm for about 15 minutes after each invocation.</p><p>Next in our logs, we see the first test request we made:</p><pre><code class="language-text">START RequestId: 09a33775-0151-4d83-9a9b-b21b8add2b3a Version: $LATEST

{:event {:version &quot;2.0&quot;, :routeKey &quot;$default&quot;, :rawPath &quot;/&quot;, ...}

{:method &quot;GET&quot;, :path &quot;/&quot;, :name &quot;Blambda&quot;, :msg &quot;Request: GET /&quot;}

END RequestId: 09a33775-0151-4d83-9a9b-b21b8add2b3a

REPORT RequestId: 09a33775-0151-4d83-9a9b-b21b8add2b3a  Duration: 56.87 ms      Billed Duration: 507 ms Memory Size: 512 MB     Max Memory Used: 125 MB Init Duration: 450.02 ms
</code></pre><p>We can see the full event that is passed to the lambda by the function URL in the first EDN log line (which we should probably switch to JSON for compatibility will common log aggregation tools), then the log statement we added for the method, path, and name parameter. Finally, we get a report on the lambda invocation. We can see that it took 450 ms to initialise the runtime (seems a bit long; maybe increasing the memory size of our function would help), then 56.87 ms for the function invocation itself.</p><p>Let&apos;s compare that to the second invocation, the one where we added <code>name</code> to the query parameters:</p><pre><code class="language-text">START RequestId: 0fca5efe-2644-4ebd-80ce-ebb390ffcaf4 Version: $LATEST

{:event {:version &quot;2.0&quot;, :routeKey &quot;$default&quot;, :rawPath &quot;/&quot;, ...}

{:method &quot;GET&quot;, :path &quot;/&quot;, :name &quot;Dear Reader&quot;, :msg &quot;Request: GET /&quot;}

END RequestId: 0fca5efe-2644-4ebd-80ce-ebb390ffcaf4

REPORT RequestId: 0fca5efe-2644-4ebd-80ce-ebb390ffcaf4  Duration: 2.23 ms       Billed Duration: 3 ms   Memory Size: 512 MB     Max Memory Used: 125 MB
</code></pre><p>Note that we don&apos;t even have an init duration in this invocation, since the lambda was warm. Note also that the request duration was 2.23 ms!</p><p>Just for fun, let&apos;s make a few more requests and look at the durations.</p><pre><code class="language-text">$ for i in $(seq 0 9); do curl $BASE_URL?name=&quot;request%20$i&quot;; echo; done
{&quot;greeting&quot;:&quot;Hello request 0!&quot;}
{&quot;greeting&quot;:&quot;Hello request 1!&quot;}
{&quot;greeting&quot;:&quot;Hello request 2!&quot;}
{&quot;greeting&quot;:&quot;Hello request 3!&quot;}
{&quot;greeting&quot;:&quot;Hello request 4!&quot;}
{&quot;greeting&quot;:&quot;Hello request 5!&quot;}
{&quot;greeting&quot;:&quot;Hello request 6!&quot;}
{&quot;greeting&quot;:&quot;Hello request 7!&quot;}
{&quot;greeting&quot;:&quot;Hello request 8!&quot;}
{&quot;greeting&quot;:&quot;Hello request 9!&quot;}

$ aws logs describe-log-streams \
  --log-group /aws/lambda/site-analyser \
  | jq &apos;.logStreams | .[].logStreamName&apos;
&quot;2023/01/03/[$LATEST]f8a5d5be9e0c4d34bcf6c8bb55e9c577&quot;
&quot;2023/01/04/[$LATEST]6532afd4465240dcb3f105abe2bcc250&quot;
&quot;2023/01/04/[$LATEST]98a0ab46e2994cdda668124ccae610fc&quot;
</code></pre><p>Hrm, <code>2023/01/04/[$LATEST]98a0ab46e2994cdda668124ccae610fc</code> was the stream we looked at last time, so let&apos;s assume that <code>2023/01/04/[$LATEST]6532afd4465240dcb3f105abe2bcc250</code> has our latest requests:</p><pre><code class="language-text">$ aws logs get-log-events \
  --log-group /aws/lambda/site-analyser \
  --log-stream &apos;2023/01/04/[$LATEST][7/1936]465240dcb3f105abe2bcc250&apos; \
  | jq -r &apos;.events | .[].message&apos; \
  | grep &apos;^REPORT&apos;
REPORT RequestId: 4ee5993e-6d21-45cd-9b05-b31ea34d993f  Duration: 54.32 ms      Billed Duration: 505 ms Memory Size: 512 MB     Max Memory Used: 125 MB Init Duration: 450.45 ms
REPORT RequestId: 490b82c7-bca1-4427-8d07-ece41444ce2c  Duration: 1.81 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 125 MB
REPORT RequestId: ca243a59-75b9-4192-aa91-76569765956a  Duration: 3.94 ms       Billed Duration: 4 ms   Memory Size: 512 MB     Max Memory Used: 126 MB
REPORT RequestId: 9d0981f8-3c48-45a5-bf8b-c37ed57e0f95  Duration: 1.77 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 126 MB
REPORT RequestId: 2d5cca3f-752d-4407-99cd-bbb89ca74983  Duration: 1.73 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 126 MB
REPORT RequestId: 674912af-b9e0-4308-b303-e5891a459ad1  Duration: 1.65 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 126 MB
REPORT RequestId: d8efbec2-de6e-491d-b4c6-ce58d02225f1  Duration: 1.67 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 126 MB
REPORT RequestId: c2a9246d-e3c4-40fa-9eb9-82fc200e6425  Duration: 1.64 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 127 MB
REPORT RequestId: cbc2f1cd-23cf-4b26-87d4-0272c097956c  Duration: 1.72 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 127 MB
REPORT RequestId: bae2e73b-4b21-4427-b0bd-359301722086  Duration: 1.73 ms       Billed Duration: 2 ms   Memory Size: 512 MB     Max Memory Used: 127 MB
</code></pre><p>Again, we see a cold start (because it apparently took me more than 15 minutes to write the part of the post since my first two test requests), then 9 more requests with durations mostly under 2 ms—dunno why there&apos;s a 3.94 ms outlier, but this is hardly a scientific benchmark. 😉</p><div class="markdown-heading"><h2 id="getting-down-to-brass-tracks">Getting down to brass tracks</h2><a href="#getting-down-to-brass-tracks" class="anchor" aria-label="Permalink: Getting down to brass tracks"><img src="assets/link.svg" /></a></div><p>OK, we&apos;ve now got a lambda that can listen to HTTP requests. To turn it into the site analyser that was promised at the beginning of this blog post, we&apos;ll define a simple HTTP API:</p><ul><li><code>POST /track?url={url}</code> - increment the number of views for the specified URL</li><li><code>GET /dashboard</code> - display a simple HTML dashboard showing the number of views of each URL for the past 7 days</li></ul><p>In order to implement the <code>/track</code> endpoint, we&apos;ll need somewhere to store the counters, and what better place than DynamoDB? We&apos;ll create a simple table with the date as the partition key and the url as the range key, which we can add to our <code>tf/main.tf</code> like so:</p><pre><code class="language-terraform">resource &quot;aws_dynamodb_table&quot; &quot;site_analyser&quot; {
  name = &quot;site-analyser&quot;
  billing_mode = &quot;PAY_PER_REQUEST&quot;
  hash_key = &quot;date&quot;
  range_key = &quot;url&quot;

  attribute {
    name = &quot;date&quot;
    type = &quot;S&quot;
  }

  attribute {
    name = &quot;url&quot;
    type = &quot;S&quot;
  }
}
</code></pre><p>We&apos;ll also need to give the lambda permissions to update and query this table, which means we&apos;ll need to define a custom IAM policy. 😭</p><p>Oh well, let&apos;s bite the bullet and add it to <code>tf/main.tf</code>:</p><pre><code class="language-terraform">resource &quot;aws_iam_role&quot; &quot;lambda&quot; {
  name = &quot;site-analyser-lambda&quot;

  assume_role_policy = jsonencode({
    Version = &quot;2012-10-17&quot;
    Statement = [
      {
        Action = &quot;sts:AssumeRole&quot;
        Effect = &quot;Allow&quot;
        Principal = {
          Service = &quot;lambda.amazonaws.com&quot;
        }
      }
    ]
  })
}

resource &quot;aws_iam_policy&quot; &quot;lambda&quot; {
  name = &quot;site-analyser-lambda&quot;

  policy = jsonencode({
    Version = &quot;2012-10-17&quot;
    Statement = [
      {
        Effect = &quot;Allow&quot;
        Action = [
          &quot;logs:CreateLogStream&quot;,
          &quot;logs:PutLogEvents&quot;
        ]
        Resource = &quot;${aws_cloudwatch_log_group.lambda.arn}:*&quot;
      },
      {
        Effect = &quot;Allow&quot;
        Action = [
          &quot;dynamodb:Query&quot;,
          &quot;dynamodb:UpdateItem&quot;,
        ]
        Resource = aws_dynamodb_table.site_analyser.arn
      }
    ]
  })
}

resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda&quot; {
  role = aws_iam_role.lambda.name
  policy_arn = aws_iam_policy.lambda.arn
}
</code></pre><p>Since Blambda won&apos;t be automatically generating a policy for us, we&apos;ll need to add a statement to the policy giving the lambda permission to write to CloudWatch Logs:</p><pre><code class="language-terraform">    Statement = [
      {
        Effect = &quot;Allow&quot;
        Action = [
          &quot;logs:CreateLogStream&quot;,
          &quot;logs:PutLogEvents&quot;
        ]
        Resource = &quot;${aws_cloudwatch_log_group.lambda.arn}:*&quot;
      },
      ...
</code></pre><p>and another one giving the lambda permissions to use the DynamoDB table:</p><pre><code class="language-terraform">    Statement = [
      ...
      {
        Effect = &quot;Allow&quot;
        Action = [
          &quot;dynamodb:Query&quot;,
          &quot;dynamodb:UpdateItem&quot;,
        ]
        Resource = aws_dynamodb_table.site_analyser.arn
      }
    ]
</code></pre><p>Finally, we need to instruct Blambda that we&apos;ll be providing our own IAM role by adding the <code>:lambda-iam-role</code> key to <code>bb.edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;
                       :lambda-name &quot;site-analyser&quot;
                       :lambda-handler &quot;handler/handler&quot;
                       :lambda-iam-role &quot;${aws_iam_role.lambda.arn}&quot;
                       :source-files [&quot;handler.clj&quot;]
                       :extra-tf-config [&quot;tf/main.tf&quot;]}))
  ...
</code></pre><p>Before we implement the tracker, let&apos;s make sure that the new Terraform stuff we did all works:</p><pre><code class="language-text">$ bb blambda terraform write-config
Copying Terraform config tf/main.tf
Writing lambda layer config: /tmp/site-analyser/target/blambda.tf
Writing lambda layer vars: /tmp/site-analyser/target/blambda.auto.tfvars
Writing lambda layers module: /tmp/site-analyser/target/modules/lambda_layer.tf

$ bb blambda terraform apply
[...]
Terraform will perform the following actions:

  # aws_dynamodb_table.site_analyser will be created
  + resource &quot;aws_dynamodb_table&quot; &quot;site_analyser&quot; {

  # aws_iam_policy.lambda must be replaced
-/+ resource &quot;aws_iam_policy&quot; &quot;lambda&quot; {

  # aws_iam_role.lambda must be replaced
-/+ resource &quot;aws_iam_role&quot; &quot;lambda&quot; {

  # aws_iam_role_policy_attachment.lambda must be replaced
-/+ resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda&quot; {

  # aws_lambda_function.lambda will be updated in-place
  ~ resource &quot;aws_lambda_function&quot; &quot;lambda&quot; {

Plan: 4 to add, 1 to change, 3 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only &apos;yes&apos; will be accepted to approve.

  Enter a value: yes

aws_iam_role.lambda: Creating...
aws_dynamodb_table.site_analyser: Creating...
aws_iam_role.lambda: Creation complete after 2s [id=site-analyser-lambda]
aws_lambda_function.lambda: Modifying... [id=site-analyser]
aws_dynamodb_table.site_analyser: Creation complete after 7s [id=site-analyser]
aws_iam_policy.lambda: Creating...
aws_iam_policy.lambda: Creation complete after 1s [id=arn:aws:iam::289341159200:policy/site-analyser-lambda]
aws_iam_role_policy_attachment.lambda: Creating...
aws_iam_role_policy_attachment.lambda: Creation complete after 0s [id=site-analyser-lambda-20230104115714236700000001]
aws_lambda_function.lambda: Still modifying... [id=site-analyser, 10s elapsed]
aws_lambda_function.lambda: Still modifying... [id=site-analyser, 20s elapsed]
aws_lambda_function.lambda: Modifications complete after 22s [id=site-analyser]

Apply complete! Resources: 4 added, 1 changed, 0 destroyed.

Outputs:

function_url = &quot;https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/&quot;
</code></pre><p>Lookin&apos; good!</p><div class="markdown-heading"><h2 id="getting-down-to-brass-tracks-for-real-this-time">Getting down to brass tracks for real this time</h2><a href="#getting-down-to-brass-tracks-for-real-this-time" class="anchor" aria-label="Permalink: Getting down to brass tracks for real this time"><img src="assets/link.svg" /></a></div><p>OK, now that we have a DynamoDB table and permissions to update it, let&apos;s implement the <code>/track</code> endpoint. The first thing we&apos;ll need to do is add <a href="https://github.com/grzm/awyeah-api">awyeah-api</a> (a library which makes Cognitect&apos;s <a href="https://github.com/cognitect-labs/aws-api">aws-api</a> work with Babashka) to talk to DynamoDB. We&apos;ll create a <code>src/bb.edn</code> and add the following:</p><pre><code class="language-clojure">{:paths [&quot;.&quot;]
 :deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.373&quot;}
        com.cognitect.aws/dynamodb {:mvn/version &quot;825.2.1262.0&quot;}
        com.grzm/awyeah-api {:git/url &quot;https://github.com/grzm/awyeah-api&quot;
                             :git/sha &quot;0fa7dd51f801dba615e317651efda8c597465af6&quot;}
        org.babashka/spec.alpha {:git/url &quot;https://github.com/babashka/spec.alpha&quot;
                                 :git/sha &quot;433b0778e2c32f4bb5d0b48e5a33520bee28b906&quot;}}}
</code></pre><p>To let Blambda know that it should build a lambda layer for the dependencies, we need to add a <code>:deps-layer-name</code> key to the config in our top-level <code>bb.edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;
                       :deps-layer-name &quot;site-analyser-deps&quot;
                       :lambda-name &quot;site-analyser&quot;
                       :lambda-handler &quot;handler/handler&quot;
                       :lambda-iam-role &quot;${aws_iam_role.lambda.arn}&quot;
                       :source-files [&quot;handler.clj&quot;]
                       :extra-tf-config [&quot;tf/main.tf&quot;]}))
  ...
</code></pre><p>Blambda will automatically look in <code>src/bb.edn</code> to find the dependencies to include in the layer. Let&apos;s test this out by building the deps layer:</p><pre><code class="language-text">$ bb blambda build-deps-layer

Building dependencies layer: /tmp/site-analyser/target/site-analyser-deps.zip
Classpath before transforming: src:/tmp/site-analyser/.work/m2-repo/com/cognitect/aws/dynamodb/825.2.1262.0/...

Classpath after transforming: src:/opt/m2-repo/com/cognitect/aws/dynamodb/825.2.1262.0/dynamodb-825.2.1262.0.jar:...

Compressing dependencies layer: /tmp/site-analyser/target/site-analyser-deps.zip
  adding: gitlibs/ (stored 0%)
  adding: gitlibs/_repos/ (stored 0%)
[...]
  adding: m2-repo/com/cognitect/aws/dynamodb/825.2.1262.0/dynamodb-825.2.1262.0.pom.sha1 (deflated 3%)
  adding: deps-classpath (deflated 67%)
</code></pre><p>And since we have a new layer, we&apos;ll need to generate new Terraform config:</p><pre><code class="language-text">$ bb blambda terraform write-config
Copying Terraform config tf/main.tf
Writing lambda layer config: /tmp/site-analyser/target/blambda.tf
Writing lambda layer vars: /tmp/site-analyser/target/blambda.auto.tfvars
Writing lambda layers module: /tmp/site-analyser/target/modules/lambda_layer.tf
</code></pre><p>Let&apos;s now whip up a <code>src/page_views.clj</code>:</p><pre><code class="language-clojure">(ns page-views
  (:require [com.grzm.awyeah.client.api :as aws]))

(defn log [msg data]
  (prn (assoc data :msg msg)))

(defmacro -&gt;map [&amp; ks]
  (assert (every? symbol? ks))
  (zipmap (map keyword ks)
          ks))

(defn -&gt;int [s]
  (Integer/parseUnsignedInt s))

(defn client [{:keys [aws-region] :as config}]
  (assoc config :dynamodb (aws/client {:api :dynamodb, :region aws-region})))

(defn validate-response [res]
  (when (:cognitect.anomalies/category res)
    (let [data (merge (select-keys res [:cognitect.anomalies/category])
                      {:err-msg (:Message res)
                       :err-type (:__type res)})]
      (log &quot;DynamoDB request failed&quot; data)
      (throw (ex-info &quot;DynamoDB request failed&quot; data))))
  res)

(defn increment! [{:keys [dynamodb views-table] :as client} date url]
  (let [req {:TableName views-table
             :Key {:date {:S date}
                   :url {:S url}}
             :UpdateExpression &quot;ADD #views :increment&quot;
             :ExpressionAttributeNames {&quot;#views&quot; &quot;views&quot;}
             :ExpressionAttributeValues {&quot;:increment&quot; {:N &quot;1&quot;}}
             :ReturnValues &quot;ALL_NEW&quot;}
        _ (log &quot;Incrementing page view counter&quot;
               (-&gt;map date url req))
        res (-&gt; (aws/invoke dynamodb {:op :UpdateItem
                                      :request req})
                validate-response)
        new-counter (-&gt; res
                        (get-in [:Attributes :views :N])
                        -&gt;int)
        ret (-&gt;map date url new-counter)]
    (log &quot;Page view counter incremented&quot;
         ret)
    ret))
</code></pre><div class="markdown-heading"><h2 id="repl-driven-development,-naturally">REPL-driven development, naturally</h2><a href="#repl-driven-development,-naturally" class="anchor" aria-label="Permalink: REPL-driven development, naturally"><img src="assets/link.svg" /></a></div><p>That&apos;s a bunch of code to have written without knowing it works, so let&apos;s act like real Clojure developers and fire up a REPL:</p><pre><code class="language-text">$ cd src/

$ bb nrepl-server 0
Started nREPL server at 127.0.0.1:42733
For more info visit: https://book.babashka.org/#_nrepl
</code></pre><p>Once this is done, we can connect from our text editor (Emacs, I hope) and test things out in a <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a>:</p><pre><code class="language-clojure">(comment

  (def c (client {:aws-region &quot;eu-west-1&quot;, :views-table &quot;site-analyser&quot;}))

  (increment! c &quot;2023-01-04&quot; &quot;https://example.com/test.html&quot;)
  ;; =&gt; {:date &quot;2023-01-04&quot;, :url &quot;https://example.com/test.html&quot;, :new-counter 1}

  (increment! c &quot;2023-01-04&quot; &quot;https://example.com/test.html&quot;)
  ;; =&gt; {:date &quot;2023-01-04&quot;, :url &quot;https://example.com/test.html&quot;, :new-counter 2}

  )
</code></pre><p>Lookin&apos; good! 😀</p><p>Let&apos;s populate the table with a bunch of data (this will take a little while):</p><pre><code class="language-clojure">(comment

  (doseq [date (map (partial format &quot;2022-12-%02d&quot;) (range 1 32))
          url (map (partial format &quot;https://example.com/page-%02d&quot;) (range 1 11))]
    (dotimes [_ (rand-int 5)]
      (increment! c date url)))
  ;; nil

  )
</code></pre><p>Just for fun, we can take a quick peek at what the data looks like in DynamoDB:</p><pre><code class="language-clojure">(comment

  (let [{:keys [dynamodb views-table]} c]
    (aws/invoke dynamodb {:op :Scan
                          :request {:TableName views-table
                                    :Limit 5}}))
  ;; =&gt; {:Items
  ;;     [{:views {:N &quot;7&quot;},
  ;;       :date {:S &quot;2022-12-12&quot;},
  ;;       :url {:S &quot;https://example.com/page-01&quot;}}
  ;;      {:views {:N &quot;16&quot;},
  ;;       :date {:S &quot;2022-12-12&quot;},
  ;;       :url {:S &quot;https://example.com/page-02&quot;}}
  ;;      {:views {:N &quot;14&quot;},
  ;;       :date {:S &quot;2022-12-12&quot;},
  ;;       :url {:S &quot;https://example.com/page-03&quot;}}
  ;;      {:views {:N &quot;8&quot;},
  ;;       :date {:S &quot;2022-12-12&quot;},
  ;;       :url {:S &quot;https://example.com/page-05&quot;}}
  ;;      {:views {:N &quot;6&quot;},
  ;;       :date {:S &quot;2022-12-12&quot;},
  ;;       :url {:S &quot;https://example.com/page-06&quot;}}],
  ;;     :Count 5,
  ;;     :ScannedCount 5,
  ;;     :LastEvaluatedKey
  ;;     {:url {:S &quot;https://example.com/page-06&quot;}, :date {:S &quot;2022-12-12&quot;}}}

  )
</code></pre><div class="markdown-heading"><h2 id="you-can&apos;t-handle-the-track!">You can&apos;t handle the track!</h2><a href="#you-can&apos;t-handle-the-track!" class="anchor" aria-label="Permalink: You can&apos;t handle the track!"><img src="assets/link.svg" /></a></div><p>Now that we have the DynamoDB machinery in place, let&apos;s connect it to our handler. But first, let&apos;s do a quick bit of refactoring so that we don&apos;t have to duplicate the <code>log</code> function in both our <code>handler</code> and <code>page-views</code> namespaces. We&apos;ll create a <code>src/util.clj</code> and add the following:</p><pre><code class="language-clojure">(ns util
  (:import (java.net URLDecoder)
           (java.nio.charset StandardCharsets)))

(defmacro -&gt;map [&amp; ks]
  (assert (every? symbol? ks))
  (zipmap (map keyword ks)
          ks))

(defn -&gt;int [s]
  (Integer/parseUnsignedInt s))

(defn log
  ([msg]
   (log msg {}))
  ([msg data]
   (prn (assoc data :msg msg))))
</code></pre><p>We need to update <code>page_views.clj</code> to use this namespace:</p><pre><code class="language-clojure">(ns page-views
  (:require [com.grzm.awyeah.client.api :as aws]
            [util :refer [-&gt;map]]))

(defn client [{:keys [aws-region] :as config}]
  (assoc config :dynamodb (aws/client {:api :dynamodb, :region aws-region})))

(defn validate-response [res]
  (when (:cognitect.anomalies/category res)
    (let [data (merge (select-keys res [:cognitect.anomalies/category])
                      {:err-msg (:Message res)
                       :err-type (:__type res)})]
      (util/log &quot;DynamoDB request failed&quot; data)
      (throw (ex-info &quot;DynamoDB request failed&quot; data))))
  res)

(defn increment! [{:keys [dynamodb views-table] :as client} date url]
  (let [req {:TableName views-table
             :Key {:date {:S date}
                   :url {:S url}}
             :UpdateExpression &quot;ADD #views :increment&quot;
             :ExpressionAttributeNames {&quot;#views&quot; &quot;views&quot;}
             :ExpressionAttributeValues {&quot;:increment&quot; {:N &quot;1&quot;}}
             :ReturnValues &quot;ALL_NEW&quot;}
        _ (util/log &quot;Incrementing page view counter&quot;
                    (-&gt;map date url req))
        res (-&gt; (aws/invoke dynamodb {:op :UpdateItem
                                      :request req})
                validate-response)
        new-counter (-&gt; res
                        (get-in [:Attributes :views :N])
                        util/-&gt;int)
        ret (-&gt;map date url new-counter)]
    (util/log &quot;Page view counter incremented&quot;
              ret)
    ret))
</code></pre><p>Now we can turn our eye to <code>handler.clj</code>. First, we pull in the <code>util</code> namespace and use its <code>log</code> function:</p><pre><code class="language-clojure">(ns handler
  (:require [cheshire.core :as json]
            [util :refer [-&gt;map]]))

(defn handler [{:keys [queryStringParameters requestContext] :as event} _context]
  (util/log &quot;Invoked with event&quot; {:event event})
  (let [{:keys [method path]} (:http requestContext)
        {:keys [name] :or {name &quot;Blambda&quot;}} queryStringParameters]
    (util/log (format &quot;Request: %s %s&quot; method path)
              {:method method, :path path, :name name})
    {:statusCode 200
     :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
     :body (json/generate-string {:greeting (str &quot;Hello &quot; name &quot;!&quot;)})}))
</code></pre><p>Now, let&apos;s remove the hello world stuff and add a <code>/track</code> endpoint. We expect our clients to make an HTTP <code>POST</code> request to the <code>/track</code> path, so we can use a simple pattern match in the handler for this:</p><pre><code class="language-clojure">(defn handler [{:keys [queryStringParameters requestContext] :as event} _context]
  (util/log &quot;Invoked with event&quot; {:event event})
  (let [{:keys [method path]} (:http requestContext)]
    (util/log (format &quot;Request: %s %s&quot; method path)
              {:method method, :path path, :name name})
    (case [method path]
      [&quot;POST&quot; &quot;/track&quot;]
      (let [{:keys [url]} queryStringParameters]
        (if url
          (do
            (util/log &quot;Should be tracking a page view here&quot; (-&gt;map url))
            {:statusCode 204})
          {:statusCode 400
           :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
           :body (json/generate-string {:msg &quot;Missing required param: url&quot;})}))

      {:statusCode 404
       :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
       :body (json/generate-string {:msg (format &quot;Resource not found: %s&quot; path)})})))
</code></pre><p>We can test this out in the REPL:</p><pre><code class="language-clojure">(comment

  (handler {:requestContext {:http {:method &quot;POST&quot; :path &quot;/nope&quot;}}} nil)
  ;; =&gt; {:statusCode 404,
  ;;     :headers {&quot;Content-Type&quot; &quot;application/json&quot;},
  ;;     :body &quot;{\&quot;msg\&quot;:\&quot;Resource not found: /nope\&quot;}&quot;}

  (handler {:requestContext {:http {:method &quot;GET&quot; :path &quot;/track&quot;}}} nil)
  ;; =&gt; {:statusCode 404,
  ;;     :headers {&quot;Content-Type&quot; &quot;application/json&quot;},
  ;;     :body &quot;{\&quot;msg\&quot;:\&quot;Resource not found: /track\&quot;}&quot;}

  (handler {:requestContext {:http {:method &quot;POST&quot; :path &quot;/track&quot;}}} nil)
  ;; =&gt; {:statusCode 400,
  ;;     :headers {&quot;Content-Type&quot; &quot;application/json&quot;},
  ;;     :body &quot;{\&quot;msg\&quot;:\&quot;Missing required param: url\&quot;}&quot;}

  (handler {:requestContext {:http {:method &quot;POST&quot; :path &quot;/track&quot;}}
            :queryStringParameters {:url &quot;https://example.com/test.html&quot;}} nil)
  ;; =&gt; {:statusCode 204}

  )
</code></pre><p>Now we need to connect this to <code>page-views/increment!</code>, which in addition to the URL, also requires a date. Before figuring out how to provide that, let&apos;s extract the tracking code into a separate function so we don&apos;t keep adding stuff to the <code>handler</code> function:</p><pre><code class="language-clojure">(defn track-visit! [{:keys [queryStringParameters] :as event}]
  (let [{:keys [url]} queryStringParameters]
    (if url
      (do
        (util/log &quot;Should be tracking a page view here&quot; (-&gt;map url))
        {:statusCode 204})
      {:statusCode 400
       :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
       :body (json/generate-string {:msg &quot;Missing required param: url&quot;})})))
</code></pre><p>Now we can simplify the <code>case</code> statement:</p><pre><code class="language-clojure">    (case [method path]
      [&quot;POST&quot; &quot;/track&quot;] (track-visit! event)

      {:statusCode 404
       :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
       :body (json/generate-string {:msg (format &quot;Resource not found: %s&quot; path)})})
</code></pre><p>Babashka provides the <code>java.time</code> classes, so we can get the current date using <code>java.time.LocalDate</code>. Let&apos;s import it into our namespace then use it in our shiny new <code>track-visit!</code> function:</p><pre><code class="language-clojure">(ns handler
  (:require [cheshire.core :as json]
            [util :refer [-&gt;map]])
  (:import (java.time LocalDate)))

(defn track-visit! [{:keys [queryStringParameters] :as event}]
  (let [{:keys [url]} queryStringParameters]
    (if url
      (let [date (str (LocalDate/now))]
        (util/log &quot;Should be tracking a page view here&quot; (-&gt;map date url))
        {:statusCode 204})
      (do
        (util/log &quot;Missing required query param&quot; {:param &quot;url&quot;})
        {:statusCode 400
         :body &quot;Missing required query param: url&quot;}))))
</code></pre><p>Let&apos;s test this out in the REPL:</p><pre><code class="language-clojure">(comment

  (handler {:requestContext {:http {:method &quot;POST&quot; :path &quot;/track&quot;}}
            :queryStringParameters {:url &quot;https://example.com/test.html&quot;}} nil)
  ;; =&gt; {:statusCode 201}

  )
</code></pre><p>You should see something like this printed to your REPL&apos;s output buffer:</p><pre><code class="language-clojure">{:event {:requestContext {:http {:method &quot;POST&quot;, :path &quot;/track&quot;}}, :queryStringParameters {:url &quot;https://example.com/test.html&quot;}}, :msg &quot;Invoked with event&quot;}
{:method &quot;POST&quot;, :path &quot;/track&quot;, :msg &quot;Request: POST /track&quot;}
{:url &quot;https://example.com/test.html&quot;, :msg &quot;Should be tracking a page view here&quot;}
</code></pre><div class="markdown-heading"><h2 id="wiring-it-all-up">Wiring it all up</h2><a href="#wiring-it-all-up" class="anchor" aria-label="Permalink: Wiring it all up"><img src="assets/link.svg" /></a></div><p>Finally, we need to connect the handler to <code>page-views/increment!</code>. <code>increment!</code> expects us to pass it a page views client, which contains a DynamoDB client, which will establish an HTTP connection when first used, which will take a couple of milliseconds. We would like this HTTP connection to be shared across invocations of our lambda so that we only need to establish it on a cold start (or whenever the DynamoDB API feels like the connection has been idle too long and decides to close it), so we&apos;ll use the trick of defining it outside our handler function:</p><pre><code class="language-clojure">(ns handler
  (:require [cheshire.core :as json]
            [page-views]
            [util :refer [-&gt;map]])
  (:import (java.time LocalDate)))

(def client (page-views/client {:aws-region &quot;eu-west-1&quot;
                                :views-table &quot;site-analyser&quot;}))
</code></pre><p>Now we have everything we need! We&apos;ll replace our placeholder log line:</p><pre><code class="language-clojure">        (util/log &quot;Should be tracking a page view here&quot; (-&gt;map url))
</code></pre><p>with an actual call to <code>page-views/increment!</code>:</p><pre><code class="language-clojure">        (page-views/increment! client date url)
</code></pre><p>Let&apos;s test this one more time in the REPL before deploying it:</p><pre><code class="language-clojure">(comment

  (handler {:requestContext {:http {:method &quot;POST&quot; :path &quot;/track&quot;}}
            :queryStringParameters {:url &quot;https://example.com/test.html&quot;}} nil)
  ;; =&gt; {:statusCode 201}

  )
</code></pre><p>This time, we should see an actual DynamoDB query logged:</p><pre><code class="language-clojure">{:event {:requestContext {:http {:method &quot;POST&quot;, :path &quot;/track&quot;}}, :queryStringParameters {:url &quot;https://example.com/test.html&quot;}}, :msg &quot;Invoked with event&quot;}
{:method &quot;POST&quot;, :path &quot;/track&quot;, :msg &quot;Request: POST /track&quot;}
{:date &quot;2023-01-04&quot;, :url &quot;https://example.com/test.html&quot;, :req {:TableName &quot;site-analyser&quot;, :Key {:date {:S &quot;2023-01-04&quot;}, :url {:S &quot;https://example.com/test.html&quot;}}, :UpdateExpression &quot;ADD #views :increment&quot;, :ExpressionAttributeNames {&quot;#views&quot; &quot;views&quot;}, :ExpressionAttributeValues {&quot;:increment&quot; {:N &quot;1&quot;}}, :ReturnValues &quot;ALL_NEW&quot;}, :msg &quot;Incrementing page view counter&quot;}
{:date &quot;2023-01-04&quot;, :url &quot;https://example.com/test.html&quot;, :new-counter 3, :msg &quot;Page view counter incremented&quot;}
</code></pre><div class="markdown-heading"><h2 id="deploying-the-real-deal">Deploying the real deal</h2><a href="#deploying-the-real-deal" class="anchor" aria-label="Permalink: Deploying the real deal"><img src="assets/link.svg" /></a></div><p>Let&apos;s recap what we&apos;ve done:</p><ol start="1"><li>Added awyeah-api as a dependency</li><li>Add two new namespaces: <code>page-views</code> and <code>util</code></li><li>Updated our handler to actually use DynamoDB</li></ol><p>Since we added more source files, we need to add them to the <code>:source-files</code> list in the top-level <code>bb-edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;
                       :deps-layer-name &quot;site-analyser-deps&quot;
                       :lambda-name &quot;site-analyser&quot;
                       :lambda-handler &quot;handler/handler&quot;
                       :lambda-iam-role &quot;${aws_iam_role.lambda.arn}&quot;
                       :source-files [&quot;handler.clj&quot; &quot;page_views.clj&quot; &quot;util.clj&quot;]
                       :extra-tf-config [&quot;tf/main.tf&quot;]}))
  ...
</code></pre><p>Once this is done, we can rebuild our lambda and reploy:</p><pre><code class="language-text">$ bb blambda build-lambda

Building lambda artifact: /tmp/site-analyser/target/site-analyser.zip
Adding file: handler.clj
Adding file: page_views.clj
Adding file: util.clj
Compressing lambda: /tmp/site-analyser/target/site-analyser.zip
updating: handler.clj (deflated 66%)
  adding: page_views.clj (deflated 59%)
  adding: util.clj (deflated 35%)

[nix-shell:/tmp/site-analyser]$ bb blambda terraform apply

Terraform will perform the following actions:

  # aws_lambda_function.lambda will be updated in-place
  ~ resource &quot;aws_lambda_function&quot; &quot;lambda&quot; {

  # module.deps.aws_lambda_layer_version.layer will be created
  + resource &quot;aws_lambda_layer_version&quot; &quot;layer&quot; {

Plan: 1 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only &apos;yes&apos; will be accepted to approve.

  Enter a value: yes

module.deps.aws_lambda_layer_version.layer: Creating...
module.deps.aws_lambda_layer_version.layer: Still creating... [10s elapsed]
module.deps.aws_lambda_layer_version.layer: Creation complete after 10s [id=arn:aws:lambda:eu-west-1:289341159200:layer:site-analyser-de
ps:1]
aws_lambda_function.lambda: Modifying... [id=site-analyser]
aws_lambda_function.lambda: Still modifying... [id=site-analyser, 10s elapsed]
aws_lambda_function.lambda: Modifications complete after 11s [id=site-analyser]

Apply complete! Resources: 1 added, 1 changed, 0 destroyed.

Outputs:

function_url = &quot;https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/&quot;
</code></pre><p>Now that this is deployed, we can test it by tracking a view:</p><pre><code class="language-text"> curl -v -X POST $BASE_URL/track?url=https%3A%2F%2Fexample.com%2Ftest.html
*   Trying 54.220.150.207:443...
* Connected to kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws (54.220.150.207) port 443 (#0)
[...]
&lt; HTTP/1.1 204 No Content
&lt; Date: Wed, 04 Jan 2023 16:01:24 GMT
&lt; Content-Type: application/json
&lt; Connection: keep-alive
&lt; x-amzn-RequestId: 2d5c6a9d-d3a4-4abb-9a57-c956ca3030f3
&lt; X-Amzn-Trace-Id: root=1-63b5a2d4-58cb681c06672bb410efe80f;sampled=0
&lt;
* Connection #0 to host kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws left intact
</code></pre><p>Looks like it worked!</p><div class="markdown-heading"><h2 id="configuration-station">Configuration station</h2><a href="#configuration-station" class="anchor" aria-label="Permalink: Configuration station"><img src="assets/link.svg" /></a></div><p>Before we forge on, let&apos;s deal with the annoying hardcoding of our client config:</p><pre><code class="language-clojure">(def client (page-views/client {:aws-region &quot;eu-west-1&quot;
                                :views-table &quot;site-analyser&quot;}))
</code></pre><p>The normal way of configuring lamdbas is to set environment variables, so let&apos;s do that:</p><pre><code class="language-clojure">(defn get-env
  ([k]
   (or (System/getenv k)
       (let [msg (format &quot;Missing env var: %s&quot; k)]
         (throw (ex-info msg {:msg msg, :env-var k})))))
  ([k default]
   (or (System/getenv k) default)))

(def config {:aws-region (get-env &quot;AWS_REGION&quot; &quot;eu-west-1&quot;)
             :views-table (get-env &quot;VIEWS_TABLE&quot;)})

(def client (page-views/client config))
</code></pre><p>Now if we set the <code>VIEWS_TABLE</code> environment variable in our lambda config (<code>AWS_REGION</code> is set by the lambda runtime itself), we&apos;re good to go. We can tell Blambda to do this for us by adding a <code>:lambda-env-vars</code> to our top-level <code>bb.edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;
                       :deps-layer-name &quot;site-analyser-deps&quot;
                       :lambda-name &quot;site-analyser&quot;
                       :lambda-handler &quot;handler/handler&quot;
                       :lambda-iam-role &quot;${aws_iam_role.lambda.arn}&quot;
                       :lambda-env-vars [&quot;VIEWS_TABLE=${aws_dynamodb_table.site_analyser.name}&quot;]
                       :source-files [&quot;handler.clj&quot; &quot;page_views.clj&quot; &quot;util.clj&quot;]
                       :extra-tf-config [&quot;tf/main.tf&quot;]}))
  ...
</code></pre><p>We&apos;ll set the name using the Terraform resource that we defined (<code>aws_dynamodb_table.site_analyser</code>), so that if we decide to change the table name, we&apos;ll only need to change it in <code>tf/main.tf</code>. The odd format for <code>:lambda-env-vars</code> is to support specifying it from the command line, so just hold your nose and move on.</p><p>Let&apos;s rebuild our lambda, regenerate our Terraform config, and redeploy:</p><pre><code class="language-text">$ bb blambda build-lambda                                                                        [54/1822]

Building lambda artifact: /tmp/site-analyser/target/site-analyser.zip
Adding file: handler.clj
Adding file: page_views.clj
Adding file: util.clj
Compressing lambda: /tmp/site-analyser/target/site-analyser.zip
updating: handler.clj (deflated 64%)
updating: page_views.clj (deflated 59%)
updating: util.clj (deflated 35%)

$ bb blambda terraform write-config
Copying Terraform config tf/main.tf
Writing lambda layer config: /tmp/site-analyser/target/blambda.tf
Writing lambda layer vars: /tmp/site-analyser/target/blambda.auto.tfvars
Writing lambda layers module: /tmp/site-analyser/target/modules/lambda_layer.tf

$ bb blambda terraform apply

Terraform will perform the following actions:

  # aws_lambda_function.lambda will be updated in-place
  ~ resource &quot;aws_lambda_function&quot; &quot;lambda&quot; {
        # (19 unchanged attributes hidden)

      + environment {
          + variables = {
              + &quot;VIEWS_TABLE&quot; = &quot;site-analyser&quot;
            }
        }
    }

Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only &apos;yes&apos; will be accepted to approve.

  Enter a value: yes

aws_lambda_function.lambda: Modifying... [id=site-analyser]
aws_lambda_function.lambda: Still modifying... [id=site-analyser, 10s elapsed]
aws_lambda_function.lambda: Modifications complete after 15s [id=site-analyser]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Outputs:

function_url = &quot;https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/&quot;
</code></pre><div class="markdown-heading"><h2 id="a-dashing-dashboard">A dashing dashboard</h2><a href="#a-dashing-dashboard" class="anchor" aria-label="Permalink: A dashing dashboard"><img src="assets/link.svg" /></a></div><p>The final piece of the puzzle is displaying the site analytics. We said that <code>GET /dashboard</code> should serve up a nice HTML page, so let&apos;s add a route for this to our handler:</p><pre><code class="language-clojure">    (case [method path]
      [&quot;GET&quot; &quot;/dashboard&quot;] (serve-dashboard event)
      [&quot;POST&quot; &quot;/track&quot;] (track-visit! event)

      {:statusCode 404
       :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
       :body (json/generate-string {:msg (format &quot;Resource not found: %s&quot; path)})})
</code></pre><p>Before we write the <code>serve-dashboard</code> function, let&apos;s think about how this should work. Babashka ships with <a href="https://github.com/yogthos/Selmer">Selmer</a>, a nice template system, so let&apos;s add a <code>src/index.html</code> template, copying liberally from Cyprien Pannier&apos;s blog post:</p><pre><code class="language-html">&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;

    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css&quot; integrity=&quot;sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==&quot; crossorigin=&quot;anonymous&quot; referrerpolicy=&quot;no-referrer&quot; /&gt;

    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vega@5.21.0&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vega-lite@5.2.0&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/vega-embed@6.20.2&quot;&gt;&lt;/script&gt;

    &lt;title&gt;Site Analytics - Powered by Blambda!&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;section class=&quot;hero is-link block&quot;&gt;
      &lt;div class=&quot;hero-body has-text-centered&quot;&gt;
        &lt;p class=&quot;title&quot; style=&quot;vertical-align:baseline&quot;&gt;
          &lt;span class=&quot;icon&quot;&gt;
            &lt;i class=&quot;fas fa-chart-pie&quot;&gt;&lt;/i&gt;
          &lt;/span&gt;
          &amp;nbsp;Site Analytics - Powered by Blambda!
        &lt;/p&gt;
        &lt;p class=&quot;subtitle&quot;&gt;{{date-label}}&lt;/p&gt;
      &lt;/div&gt;
    &lt;/section&gt;
    &lt;div class=&quot;container is-max-desktop&quot;&gt;
      &lt;div class=&quot;box&quot;&gt;
        &lt;nav class=&quot;level is-mobile&quot;&gt;
          &lt;div class=&quot;level-item has-text-centered&quot;&gt;
            &lt;div&gt;
              &lt;p class=&quot;heading&quot;&gt;Total views&lt;/p&gt;
              &lt;p class=&quot;title&quot;&gt;{{total-views}}&lt;/p&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/nav&gt;
        &lt;div&gt;
          &lt;div id=&quot;{{chart-id}}&quot; style=&quot;width:100%; height:300px&quot;&gt;&lt;/div&gt;
          &lt;script type=&quot;text/javascript&quot;&gt;
           vegaEmbed (&apos;#{{chart-id}}&apos;, JSON.parse({{chart-spec|json|safe}}));
          &lt;/script&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=&quot;box&quot;&gt;
        &lt;h1 class=&quot;title is-3&quot;&gt;Top URLs&lt;/h1&gt;
        &lt;table class=&quot;table is-fullwidth is-hoverable is-striped&quot;&gt;
          &lt;thead&gt;
            &lt;tr&gt;
              &lt;th&gt;Rank&lt;/th&gt;
              &lt;th&gt;URL&lt;/th&gt;
              &lt;th&gt;Views&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/thead&gt;
          &lt;tbody&gt;
            {% for i in top-urls %}
            &lt;tr&gt;
              &lt;td style=&quot;width: 20px&quot;&gt;{{i.rank}}&lt;/td&gt;
              &lt;td&gt;&lt;a href=&quot;{{i.url}}&quot;&gt;{{i.url}}&lt;/a&gt;&lt;/td&gt;
              &lt;td style=&quot;width: 20px&quot;&gt;{{i.views}}&lt;/td&gt;
            &lt;/tr&gt;
            {% endfor %}
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre><p>Just consider this stuff an incantation if you don&apos;t feel like reading it. 😅</p><p>Once we have the template in place, we can write the <code>serve-dashboard</code> that renders it. First, we need to require Selmer in <code>src/handler.clj</code>:</p><pre><code class="language-clojure">(ns handler
  (:require [cheshire.core :as json]
            [selmer.parser :as selmer]
            [page-views]
            [util :refer [-&gt;map]])
  (:import (java.time LocalDate)))
</code></pre><p>Now, we can just load and render the template in <code>serve-dashboard</code>:</p><pre><code class="language-clojure">(defn serve-dashboard [_event]
  (util/log &quot;Rendering dashboard&quot;)
  {:statusCode 200
   :headers {&quot;Content-Type&quot; &quot;text/html&quot;}
   :body (selmer/render (slurp &quot;index.html&quot;) {})})
</code></pre><p>Since we&apos;ve added <code>index.html</code> as a source file, we need to add it to the <code>:source-files</code> list in the top-level <code>bb-edn</code>:</p><pre><code class="language-clojure">{:deps { ... }
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (do
          (def config {:bb-arch &quot;arm64&quot;
                       :deps-layer-name &quot;site-analyser-deps&quot;
                       :lambda-name &quot;site-analyser&quot;
                       :lambda-handler &quot;handler/handler&quot;
                       :lambda-iam-role &quot;${aws_iam_role.lambda.arn}&quot;
                       :source-files [;; Clojure sources
                                      &quot;handler.clj&quot;
                                      &quot;page_views.clj&quot;
                                      &quot;util.clj&quot;

                                      ;; HTML templates
                                      &quot;index.html&quot;
                                      ]
                       :extra-tf-config [&quot;tf/main.tf&quot;]}))
  ...
</code></pre><p>Let&apos;s rebuild and redeploy:</p><pre><code class="language-text">$ bb blambda build-lambda

Building lambda artifact: /tmp/site-analyser/target/site-analyser.zip
Adding file: handler.clj
Adding file: page_views.clj
Adding file: util.clj
Adding file: index.html
Compressing lambda: /tmp/site-analyser/target/site-analyser.zip
updating: handler.clj (deflated 66%)
updating: page_views.clj (deflated 59%)
updating: util.clj (deflated 35%)
  adding: index.html (deflated 59%)

[nix-shell:/tmp/site-analyser]$ bb blambda terraform apply

Terraform will perform the following actions:

  # aws_lambda_function.lambda will be updated in-place
  ~ resource &quot;aws_lambda_function&quot; &quot;lambda&quot; {
Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only &apos;yes&apos; will be accepted to approve.

  Enter a value: yes

aws_lambda_function.lambda: Modifying... [id=site-analyser]
aws_lambda_function.lambda: Modifications complete after 7s [id=site-analyser]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Outputs:

function_url = &quot;https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/&quot;
</code></pre><p>Now we can visit <a href="https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/dashboard">https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/dashboard</a> in a web browser and see something like this:</p><p><img alt="Site analytics dashboard showing no data" src="assets/2023-01-04-dashboard-empty.png" title="Boring dashboard" /></p><p>This is definitely a bit on the boring side, so let&apos;s write some code to query DynamoDB and supply the data to make the dashboard dashing!</p><div class="markdown-heading"><h2 id="paging-doctor-aws-again">Paging Doctor AWS again</h2><a href="#paging-doctor-aws-again" class="anchor" aria-label="Permalink: Paging Doctor AWS again"><img src="assets/link.svg" /></a></div><p>Whenever we fetch data from an AWS API, we need to handle pagination. Luckily, I have already <a href="2022-10-02-page-2.html">blogged about this extensively</a>, so we can just copy and paste from my S3 paging example to accomplish the same with DynamoDB. Let&apos;s start by adding the handy <code>lazy-concat</code> helper function to <code>src/util.clj</code>:</p><pre><code class="language-clojure">(defn lazy-concat [colls]
  (lazy-seq
   (when-first [c colls]
     (lazy-cat c (lazy-concat (rest colls))))))
</code></pre><p>Now, we can add some code to <code>src/page_views.clj</code> to query DynamoDB in a page-friendly way:</p><pre><code class="language-clojure">(defn get-query-page [{:keys [dynamodb views-table] :as client}
                      date
                      {:keys [page-num LastEvaluatedKey] :as prev}]
  (when prev
    (util/log &quot;Got page&quot; prev))
  (when (or (nil? prev)
            LastEvaluatedKey)
    (let [page-num (inc (or page-num 0))
          req (merge
               {:TableName views-table
                :KeyConditionExpression &quot;#date = :date&quot;
                :ExpressionAttributeNames {&quot;#date&quot; &quot;date&quot;}
                :ExpressionAttributeValues {&quot;:date&quot; {:S date}}}
               (when LastEvaluatedKey
                 {:ExclusiveStartKey LastEvaluatedKey}))
          _ (util/log &quot;Querying page views&quot; (-&gt;map date page-num req))
          res (-&gt; (aws/invoke dynamodb {:op :Query
                                        :request req})
                  validate-response)
          _ (util/log &quot;Got response&quot; (-&gt;map res))]
      (assoc res :page-num page-num))))

(defn get-views [client date]
  (-&gt;&gt; (iteration (partial get-query-page client date)
                  :vf :Items)
       util/lazy-concat
       (map (fn [{:keys [views date url]}]
              {:date (:S date)
               :url (:S url)
               :views (util/-&gt;int (:N views))}))))
</code></pre><p>We might as well test this out in our REPL whilst we&apos;re here:</p><pre><code class="language-clojure">(comment

  (def c (client {:aws-region &quot;eu-west-1&quot;, :views-table &quot;site-analyser&quot;}))

  (get-views c &quot;2022-12-25&quot;)
  ;; =&gt; ({:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-01&quot;, :views 5}
  ;;     {:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-03&quot;, :views 8}
  ;;     {:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-04&quot;, :views 15}
  ;;     {:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-05&quot;, :views 3}
  ;;     {:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-06&quot;, :views 12}
  ;;     {:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-07&quot;, :views 11}
  ;;     {:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-08&quot;, :views 15}
  ;;     {:date &quot;2022-12-25&quot;, :url &quot;https://example.com/page-09&quot;, :views 8})

  )
</code></pre><p>Looks good!</p><p>Now let&apos;s plug this into <code>src/handler.clj</code>! The Vega library we&apos;re using to render our data will attach to a <code>&lt;div&gt;</code> in our HTML page, to which we&apos;ll give a random ID. In order to facilitate this, let&apos;s import <code>java.util.UUID</code>:</p><pre><code class="language-clojure">(ns handler
  (:require [cheshire.core :as json]
            [selmer.parser :as selmer]
            [page-views]
            [util :refer [-&gt;map]])
  (:import (java.time LocalDate)
           (java.util UUID)))
</code></pre><p>And whilst we&apos;re at it, let&apos;s add a little more config to control how many days of data and how many top URLs to show:</p><pre><code class="language-clojure">(def config {:aws-region (get-env &quot;AWS_REGION&quot; &quot;eu-west-1&quot;)
             :views-table (get-env &quot;VIEWS_TABLE&quot;)
             :num-days (util/-&gt;int (get-env &quot;NUM_DAYS&quot; &quot;7&quot;))
             :num-top-urls (util/-&gt;int (get-env &quot;NUM_TOP_URLS&quot; &quot;10&quot;))})
</code></pre><p>Now we&apos;re ready to write the <code>serve-dashboard</code> function:</p><pre><code class="language-clojure">(defn serve-dashboard [{:keys [queryStringParameters] :as event}]
  (let [date (:date queryStringParameters)
        dates (if date
                [date]
                (-&gt;&gt; (range (:num-days config))
                     (map #(str (.minusDays (LocalDate/now) %)))))
        date-label (or date (format &quot;last %d days&quot; (:num-days config)))
        all-views (mapcat #(page-views/get-views client %) dates)
        total-views (reduce + (map :views all-views))
        top-urls (-&gt;&gt; all-views
                      (group-by :url)
                      (map (fn [[url views]]
                             [url (reduce + (map :views views))]))
                      (sort-by second)
                      reverse
                      (take (:num-top-urls config))
                      (map-indexed (fn [i [url views]]
                                     (assoc (-&gt;map url views) :rank (inc i)))))
        chart-id (str &quot;div-&quot; (UUID/randomUUID))
        chart-data (-&gt;&gt; all-views
                        (group-by :date)
                        (map (fn [[date rows]]
                               {:date date
                                :views (reduce + (map :views rows))}))
                        (sort-by :date))
        chart-spec (json/generate-string
                    {:$schema &quot;https://vega.github.io/schema/vega-lite/v5.json&quot;
                     :data {:values chart-data}
                     :mark {:type &quot;bar&quot;}
                     :width &quot;container&quot;
                     :height 300
                     :encoding {:x {:field &quot;date&quot;
                                    :type &quot;nominal&quot;
                                    :axis {:labelAngle -45}}
                                :y {:field &quot;views&quot;
                                    :type &quot;quantitative&quot;}}})
        tmpl-vars (-&gt;map date-label
                         total-views
                         top-urls
                         chart-id
                         chart-spec)]
    (util/log &quot;Rendering dashboard&quot; tmpl-vars)
    {:statusCode 200
     :headers {&quot;Content-Type&quot; &quot;text/html&quot;}
     :body (selmer/render (slurp &quot;index.html&quot;)
                          tmpl-vars)}))
</code></pre><p>A quick build and deploy and now we&apos;ll be able to see some exciting data!</p><pre><code class="language-test">$ bb blambda build-lambda

Building lambda artifact: /tmp/site-analyser/target/site-analyser.zip
Adding file: handler.clj
Adding file: page_views.clj
Adding file: util.clj
Adding file: index.html
Compressing lambda: /tmp/site-analyser/target/site-analyser.zip
updating: handler.clj (deflated 66%)
updating: page_views.clj (deflated 65%)
updating: util.clj (deflated 42%)
updating: index.html (deflated 59%)

[nix-shell:/tmp/site-analyser]$ bb blambda terraform apply
Terraform will perform the following actions:

  # aws_lambda_function.lambda will be updated in-place
  ~ resource &quot;aws_lambda_function&quot; &quot;lambda&quot; {

Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only &apos;yes&apos; will be accepted to approve.

  Enter a value: yes

aws_lambda_function.lambda: Modifying... [id=site-analyser]
aws_lambda_function.lambda: Still modifying... [id=site-analyser, 10s elapsed]
aws_lambda_function.lambda: Modifications complete after 11s [id=site-analyser]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Outputs:

function_url = &quot;https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/&quot;
</code></pre><p>Visiting <a href="https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/dashboard">https://kuceaiz55k7soeki4u5oy4w6uy0ntbky.lambda-url.eu-west-1.on.aws/dashboard</a> again tells a tale of joy!</p><p><img alt="Site analytics dashboard lots of data" src="assets/2023-01-04-dashboard-full.png" title="Dashing dashboard" /></p><p>With this, let&apos;s declare our site analysed and all agree that Babashka is way better than nbb. Hurrah! 🎉</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-10-02-page-2.html</id>
    <link href="https://jmglov.net/blog/2022-10-02-page-2.html"/>
    <title>Page 2</title>
    <updated>2022-10-02T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p><a href="2022-09-22-aws-paging.html">Last time out</a>, I was desperately trying to understand why my beautifully crafted page-aware lazy loading S3 list objects function was fetching more pages than it actually needed to fulfil my requirements (doesn&apos;t sound very lazy to me!), but to no avail. If you cast your mind back, I had set my page size to 50, and was taking 105 objects:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (list-objects logs-client prefix)
       (take 105))
  ;; =&gt; (&quot;logs/E1HJS54CQLFQU4.2022-09-15-00.0125de6e.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-00.3b36a099.gz&quot;
  ;;     ...
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-10.ae86e512.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-10.b4a720f9.gz&quot;)

)
</code></pre><p>But sadly seeing the following in my REPL buffer:</p><pre><code class="language-text">Fetching page 1
Fetching page 2
Fetching page 3
Fetching page 4
</code></pre><p>I know that some lazy sequences in Clojure realise in chunks, but those chunks are usually realised 32 at a time in my experience. It is actually absurdly hard to find any documentation that explains exactly how chunking works, but one can gather hints here and there from the dusty corners of the web&apos;s ancient past:</p><ul><li><a href="http://www.tianxiangxiong.com/2016/11/05/chunking-and-laziness-in-clojure.html">Laziness and chunking in
  Clojure</a> - 2016</li><li><a href="https://www.markhneedham.com/blog/2014/04/06/clojure-not-so-lazy-sequences-a-k-a-chunking-behaviour/">Clojure: Not so lazy sequences a.k.a chunking
  behaviour</a> - 2014</li><li><a href="http://blog.fogus.me/2010/01/22/de-chunkifying-sequences-in-clojure/">De-chunkifying Sequences in
  Clojure</a> - 2010</li></ul><p>They all mention the number 32 (holiest of all powers of 2, clearly), and the first one even suggests looking at the implementation of <a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L2727">clojure.core/map</a> and seeing that <code>map</code> calls the magic <code>chunk-first</code>, which &quot;takes 32 elements for performance reasons&quot;. Spelunking deeper into the source for the <a href="https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L701">definition
of
<code>chunk-first</code></a> leads one to the following lines:</p><pre><code class="language-clojure">(defn ^:static  ^clojure.lang.IChunk chunk-first ^clojure.lang.IChunk [^clojure.lang.IChunkedSeq s]
  (.chunkedFirst s))
</code></pre><p>Which leads to Clojure&apos;s <a href="https://github.com/clojure/clojure/tree/clojure-1.10.1/src/jvm/clojure/lang">Java
implementation</a>, which leads to me reading a couple of the classes that implement the <code>IChunk</code> interface, looking for some mention of the chunk size, and running away in tears.</p><p>The funny thing about all of this is that I know that one is <a href="https://stuartsierra.com/2015/08/25/clojure-donts-lazy-effects">not supposed to
use functions with side effects when processing lazy
sequences</a>. In fact, it says exactly that in the docstring for <a href="https://clojuredocs.org/clojure.core/iterate">clojure.core/iterate</a>:</p><pre><code class="language-text">(iterate f x)

Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of
side-effects.
</code></pre><p>But I figured that it would &quot;probably be fine for this use case.&quot; 😂</p><p>Having received my well-deserved comeuppance—albeit not completely understanding the form said comeuppance is taking—it&apos;s time to figure out how to lazily page without chunking. As luck would have it, right after I published my previous post, I opened up <a href="http://planet.clojure.in/">Planet Clojure</a> in my RSS reader and saw a post by Abhinav Omprakash on &quot;<a href="https://www.abhinavomprakash.com/posts/clojure-iteration/">Clojure&apos;s Iteration function
</a>&quot;. According to the post, Clojure has a function called <code>iteration</code>, and:</p><blockquote><p>One of the most common use cases for iteration is making paginated api calls.</p></blockquote><p>OK, this looks interesting. Why in the world didn&apos;t I know about this? Well, Abhinav&apos;s post links to a post on the JUXT blog called &quot;<a href="https://www.juxt.pro/blog/new-clojure-iteration">The new Clojure
iteration function</a>&quot; (written by the irrepressible Renzo Borgatti!) wherein it is revealed that <code>iteration</code> is new in Clojure 1.11. In the post&apos;s introduction, Renzo mentions:</p><blockquote><p>the problem of dealing with batched API calls, those requiring the consumer a &quot;token&quot; from the previous invocation to be able to proceed to the next. This behaviour is very popular in API interfaces such as AWS S3, where the API needs to protect against the case of a client requesting the content of a bucket with millions of objects in it.</p></blockquote><p>He goes on to make a bold claim:</p><blockquote><p>In the past, Clojure developers dealing with paginated APIs have been solving the same problem over and over. The problem is to create some layer that hides away the need of knowing about the presence of pagination and provides the seqable or reducible abstraction we are all familiar with. It is then up to the user of such abstractions to decide if they want to eagerly load many objects or consume them lazily, without any need to know how many requests are necessary or how the pagination mechanism works.</p></blockquote><p>OK, I buy this, having solved this problem in many sub-optimal ways over the years. So <code>iteration</code> really sounds like what I want here. Let&apos;s see if I can modify my code based on the <code>iterate</code> function to use <code>iteration</code> instead. Here&apos;s what I ended up with last time:</p><pre><code class="language-clojure">(defn get-s3-page [{:keys [s3-client s3-bucket s3-page-size]}
                   prefix prev]
  (let [{token :NextContinuationToken
         truncated? :IsTruncated
         page-num :page-num} prev
        page-num (if page-num (inc page-num) 1)
        done? (false? truncated?)
        res (when-not done?
              (println &quot;Fetching page&quot; page-num)
              (-&gt; (aws/invoke s3-client
                              {:op :ListObjectsV2
                               :request (mk-s3-req s3-bucket prefix s3-page-size token)})
                  (assoc :page-num page-num)))]
    res))

(defn s3-page-iterator [logs-client prefix]
  (partial get-s3-page logs-client prefix))

(defn list-objects [logs-client prefix]
  (-&gt;&gt; (iterate (s3-page-iterator logs-client prefix) nil)
       (drop 1)
       (take-while :Contents)
       (mapcat (comp (partial map :Key) :Contents))))
</code></pre><p>The JUXT post helpfully walks through <a href="https://www.juxt.pro/blog/new-clojure-iteration#_example_iterating_paginated_objects_using_the_new_function">an example of listing objects in an S3
bucket</a>, which is exactly what I&apos;m doing, but unhelpfully bases the example on <a href="https://github.com/mcohen01/amazonica">Amazonica</a> (an excellent Clojure wrapper around the AWS Java SDK that I used for years until some cool kids from Nubank told me that all the cool kids were now using Cognitect&apos;s <a href="https://github.com/cognitect-labs/aws-api">aws-api</a>, and I wanted to be cool like them, so I decided to use it for my next thing, which turned out to be a great decision since my next thing was <a href="https://github.com/jmglov/blambda">Blambda</a>, which runs on <a href="https://github.com/babashka/babashka">Babashka</a>, which can&apos;t use the AWS Java SDK anyway).</p><p>Where was I? Oh yeah, the JUXT blog. So it breaks down the arguments to <code>iteration</code>:</p><pre><code class="language-clojure">(iteration step &amp; {:keys [somef vf kf initk]
                   :or {vf identity
                        kf identity
                        somef some?
                        initk nil}})
</code></pre><ul><li><code>step</code> is a function of the next marker token. This function should contain the logic for making a request to the S3 API (or other relevant paginated API) passing the given token.</li><li><code>somef</code> is a function that applied to the return of <code>(step token)</code> returns <code>true</code> or <code>false</code> based on the fact that the response contains results or not, respectively.</li><li><code>vf</code> is a function that applied to the return of <code>(step token)</code> returns the items from the current response page.</li><li><code>kf</code> is a function that applied to the return of <code>(step token)</code> returns the next marker token if one is available.</li><li><code>initk</code> is an initial value for the marker.</li></ul><p>Looking at this, my <code>get-s3-page</code> function sounds a lot like <code>step</code>, in that it contains the logic for making a request to S3. However, <code>step</code> is a function taking one argument, and <code>get-s3-page</code> takes three, so clearly it can&apos;t be used it as is. But the same was actually true for my previous attempt at paging that used <code>iterate</code>, and in fact I wrote a function to take care of this:</p><pre><code class="language-clojure">(defn s3-page-iterator [logs-client prefix]
  (partial get-s3-page logs-client prefix))
</code></pre><p><code>s3-page-iterator</code> closes over the client and the prefix and returns a function that takes only one argument: <code>prev</code>, which is the previous page of results from S3. So that&apos;s <code>step</code> sorted!</p><p>In order to figure out what functions I need for <code>somef</code>, <code>vf</code>, and <code>kf</code> (gotta love the terse names of variables in <code>clojure.core</code>!), I need to look at what <code>get-s3-page</code> returns, since all three of those functions operate on the return value of <code>(step token)</code>:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (get-s3-page logs-client &quot;logs/A1BCD23EFGHIJ4.2022-09-26-&quot; nil)
       keys)
  ;; =&gt; (:Prefix
  ;;     :NextContinuationToken
  ;;     :Contents
  ;;     :MaxKeys
  ;;     :IsTruncated
  ;;     :Name
  ;;     :KeyCount
  ;;     :page-num)

)
</code></pre><p>I&apos;ll tackle <code>vf</code> and <code>kf</code> first, since they are pretty straightforward. <code>vf</code> needs to return the items from the current response page. Those items live in the map returned by <code>get-s3-page</code> under the <code>:Contents</code> key, and since keywords are functions that when called with a map, look themselves up in the map, I can use the <code>:Contents</code> keyword as my <code>vf</code>! 🎉</p><p><code>kf</code> returns the next token, which I have in the response as <code>:NextContinuationToken</code>, so it sounds like I should use that for <code>kf</code>. The only problem is that the second invocation of my <code>step</code> function will look like this:</p><pre><code class="language-clojure">(step (:NextContinuationToken response))
</code></pre><p>and <code>get-s3-page</code> expects <code>prev</code> to be the response itself, from which it knows how to extract the token all by itself. So I want to just pass the response to my function as-is, and luckily, Clojure has a function for that: <code>identity</code>, which returns its argument unchanged.</p><p>Now it&apos;s time to look at <code>somef</code>, a function that returns <code>true</code> if the response contains results and <code>false</code> otherwise. In my case, <code>get-s3-page</code> makes a request to the S3 API and returns the response <strong>unless</strong> the previous response wasn&apos;t truncated, in which case it returns <code>nil</code>. So what I want for <code>somef</code> is a function that returns true for any non-<code>nil</code> value, which is exactly what <a href="https://clojuredocs.org/clojure.core/some_q">clojure.core/some?</a> does (not to be confused with <a href="https://clojuredocs.org/clojure.core/some">clojure.core/some</a>).</p><p>Now that <code>somef</code>, <code>vf</code>, and <code>kf</code> are sorted, I&apos;ll turn my roving eye to <code>initk</code>, which is the initial value for the token passed to my <code>step</code> function. Just like in my previous attempt, I can use <code>nil</code> as the initial argument.</p><p>So putting this all together, my new <code>list-objects</code> function would look like this:</p><pre><code class="language-clojure">(defn list-objects [logs-client prefix]
  (-&gt;&gt; (iteration (s3-page-iterator logs-client prefix)
                  :vf :Contents
                  :kf identity
                  :somef some?
                  :initk nil)
       (mapcat (partial map :Key))))
</code></pre><p>Looks good, lemme test it out!</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (list-objects logs-client prefix)
       (take 5))
  ;; =&gt; (&quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.0187bda9.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.0e46ca54.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.348fa655.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.4345d6ea.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.63005d64.gz&quot;)

)
</code></pre><p>Nice! Except for one thing. My REPL buffer reveals that I actually haven&apos;t fixed the problem I set out to fix:</p><pre><code class="language-text">Fetching page 1
Fetching page 2
Fetching page 3
Fetching page 4
</code></pre><p>Looks like I should have read a little further in the JUXT blog article, because Renzo explains exactly what&apos;s happening here:</p><blockquote><p>The results of calling [<code>get-s3-page</code>] are batched items as a collection of collections. In general, we need to collapse the batches into a single sequence and process them one by one [...]</p><p>Surprisingly, accessing the [first 5 items from] the first page produces additional network calls for pages well ahead of what we currently need. This is an effect of using [<code>mapcat</code>, which always evaluates the first 4
&gt; arguments]!</p><p>The reader should understand that this is not a problem of iteration itself, but more about the need to concatenate the results back for processing maintaining laziness in place.</p></blockquote><p>Renzo being Renzo, of course he has a solution to this:</p><pre><code class="language-clojure">(defn lazy-concat [colls]
  (lazy-seq
   (when-first [c colls]
     (lazy-cat c (lazy-concat (rest colls))))))
</code></pre><p>I can fold this into my <code>list-objects</code> function:</p><pre><code class="language-clojure">(defn list-objects [logs-client prefix]
  (-&gt;&gt; (iteration (s3-page-iterator logs-client prefix)
                  :vf :Contents
                  :kf identity
                  :somef some?
                  :initk nil)
       lazy-concat
       (map :Key)))
</code></pre><p>Since <code>lazy-concat</code> is sewing the lists returned by <code>iteration</code> together, I don&apos;t need the chunktacular <code>mapcat</code> anymore; I can just use regular old <code>map</code>. Let&apos;s see if this works:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (list-objects logs-client prefix)
       (take 5))
  ;; =&gt; (&quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.0187bda9.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.0e46ca54.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.348fa655.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.4345d6ea.gz&quot;
  ;;     &quot;logs/A1BCD23EFGHIJ4.2022-09-25-00.63005d64.gz&quot;)

)
</code></pre><p>And the REPL buffer?</p><pre><code class="language-text">Fetching page 1
</code></pre><p>Amazing!</p><p>There&apos;s one last thing that&apos;s bugging me, though. If I look back at the docs for <code>iteration</code>, I see that it has some default arguments:</p><pre><code class="language-clojure">(iteration step &amp; {:keys [somef vf kf initk]
                   :or {vf identity
                        kf identity
                        somef some?
                        initk nil}})
</code></pre><p>So <code>vf</code> and <code>kf</code> default to <code>identity</code>, <code>somef</code> defaults to <code>some?</code>, and <code>initk</code> defaults to <code>nil</code>. Taking a look at how I call <code>iteration</code>, things look quite familiar:</p><pre><code class="language-clojure">(iteration (s3-page-iterator logs-client prefix)
           :vf :Contents
           :kf identity
           :somef some?
           :initk nil)
</code></pre><p>My <code>kf</code>, <code>somef</code>, and <code>initk</code> all match the defaults! Looks like the Clojure core team kinda knows what they&apos;re doing. 😉</p><p>With this knowledge under my belt, I can simplify <code>list-objects</code> even further:</p><pre><code class="language-clojure">(defn list-objects [logs-client prefix]
  (-&gt;&gt; (iteration (s3-page-iterator logs-client prefix)
                  :vf :Contents)
       lazy-concat
       (map :Key)))
</code></pre><p>The cool thing about all of this is that I could use the exact same <code>get-s3-page</code> function I had before, as well as the same <code>s3-page-iterator</code> function, and only needed to change <code>list-objects</code> and sprinkle in the magic <code>lazy-concat</code> function from Renzo&apos;s box o&apos; fun!</p><p>Before you try this at home, be sure to read the JUXT blog post carefully enough not to miss this sentence, which probably should have been bold and inside the dearly departed HTML <code>&lt;blink&gt;</code> tag:</p><blockquote><p>You need to remember to avoid using sequence with transducers for processing items even after the initial concatenation, because as soon as you do, chunking will hunt you down.</p></blockquote></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-09-22-aws-paging.html</id>
    <link href="https://jmglov.net/blog/2022-09-22-aws-paging.html"/>
    <title>Paging Doctor AWS</title>
    <updated>2022-09-22T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>I&apos;ve been using AWS for quite a while now, and one thing that is as inevitable as death and taxes is dealing with paging. All of the APIs that return multiple items support pagination in some way, and anytime you write code that needs to act on all items, you need to handle fetching pages. My quest to <a href="2022-09-02-dogfooding-blambda-logs.html">parse my own
access logs</a>, is no exception, since my logs are stored in S3 and my API needs to list all of the logs for a specific date, of which there could be thousands. The way I&apos;ve typically handled paging in Clojure with with a <code>loop</code> / <code>recur</code> similar to this:</p><pre><code class="language-clojure">(defn get-items [{:keys [s3-client s3-bucket s3-page-size] :as logs-client}
                 prefix]
  (loop [items []
         token nil]
    (let [_ (println &quot;Fetching page&quot;)
          res (aws/invoke s3-client
                          {:op :ListObjectsV2
                           :request (mk-s3-req s3-bucket prefix s3-page-size token)})
          items (concat items (:Contents res))]
      (if (:IsTruncated res)
        (recur items (:NextContinuationToken res))
        items))))
</code></pre><p><code>logs-client</code> is a data structure containing the stuff I need to talk to S3:</p><pre><code class="language-clojure">{:aws-region &quot;eu-west-1&quot;,
 :s3-client ; Cognitect aws-api client here
 :s3-bucket &quot;logs.jmglov.net&quot;,
 :s3-prefix &quot;logs/&quot;,
 :s3-page-size 25}
</code></pre><p>And <code>prefix</code> is the start of S3 keys for CloudFront access logs for a specific date, for example: <code>logs/A1BCD23EFGHIJ4.2022-09-15-</code></p><p>Finally, <code>mk-s3-req</code> is a function that constructs a <code>ListObjectsV2</code> request, adding the continuation token if it&apos;s non-nil:</p><pre><code class="language-clojure">(defn mk-s3-req [s3-bucket prefix s3-page-size continuation-token]
  (merge {:Bucket s3-bucket
          :Prefix prefix}
         (when s3-page-size
           {:MaxKeys s3-page-size})
         (when continuation-token
           {:ContinuationToken continuation-token})))
</code></pre><p>The <code>loop</code> / <code>recur</code> approach has the benefit of being fairly simple, but the drawback of <a href="https://stuartsierra.com/2015/04/26/clojure-donts-concat">being a lazily-ticking time
bomb</a>, as Stuart Sierra explains. It also has the drawback of fetching all of the items, regardless of how many I need. For example, if I need the first two items for some reason:</p><pre><code class="language-clojure">(take 2 (get-items))
</code></pre><p>I&apos;ll see something like this in my REPL buffer:</p><pre><code class="language-text">Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
</code></pre><p>Now imagine instead of nine pages of items, I have hundreds. Yikes!</p><p>In practice, this hasn&apos;t been a problem for me, as I&apos;ve seldom had enough pages for this to really matter, but it does feel yucky, to use a technical term. Surely we can do better, right?</p><p>Right. In fact, Clojure has an entire abstraction built around the concept of taking just what you need: the <a href="https://clojure.org/reference/sequences">sequence
abstraction</a>. A sequence (often called a &quot;seq&quot; in the Clojure literature) is a logical list that is usually lazily realised, and many of the sequence library functions in <code>clojure.core</code> are lazy, such as <code>map</code>, <code>filter</code>, <code>take</code>, <code>drop</code>, etc. If we can find a way to generate a lazy sequence, the code above that takes the first two items in the sequence should only fetch the first page.</p><p>And where there&apos;s a will, Clojure has a way: the <a href="https://clojuredocs.org/clojure.core/iterate">iterate</a> function. According to the docs, it returns a lazy sequence generated by a function that is repeatedly called with the previous value returned by the function. This is easier to see than it is to explain:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (iterate inc 5)
       (take 5))
  ;; =&gt; (5 6 7 8 9)

)
</code></pre><p>If we unroll this in our heads, this is what&apos;s going on:</p><pre><code class="language-clojure">(comment

  (cons
   5
   (cons
    (inc 5)
    (cons
     (inc (inc 5))
     (cons
      (inc (inc (inc 5)))
      (cons
       (inc (inc (inc (inc 5))))
       nil)))))
  ;; =&gt; (5 6 7 8 9)

)
</code></pre><p>The cool thing about <code>iterate</code> is that our generator function <code>f</code> can do whatever it wants, as long as it takes one argument. So what if we write an <code>f</code> that fetches a page of results from S3? We have something similar to that in the body of the <code>loop</code> we wrote above, so let&apos;s adapt that a bit:</p><pre><code class="language-clojure">(defn get-s3-page [{:keys [s3-client s3-bucket s3-page-size]}
                   prefix
                   token]
  (let [_ (println &quot;Fetching page&quot;)
        res (aws/invoke s3-client
                        {:op :ListObjectsV2
                         :request (mk-s3-req s3-bucket prefix s3-page-size token)})]
    :???))
</code></pre><p>Then we can do stuff like this:</p><pre><code class="language-clojure">(defn s3-page-iterator [logs-client prefix]
  (partial get-s3-page logs-client prefix))

(-&gt;&gt; (iterate (s3-page-iterator logs-client prefix) nil)
     (take 2))
</code></pre><p>The <code>s3-page-iterator</code> function transforms our <code>get-s3-page</code> function, which takes three parameters, into a function that takes one parameter so we can use it with <code>iterate</code>. It does this through the magic of <code>partial</code>, which takes a function and some arguments, and returns a new function with those arguments applied. For example, we can create a partial function from <code>+</code>, which takes two (or more) arguments, that adds 1 to its argument:</p><pre><code class="language-clojure">(comment

  (def plus1 (partial + 1))

  (plus1 2)
  ;; =&gt; 3

)
</code></pre><p>There&apos;s an open question here, though. What in the world should <code>get-s3-page</code> return? Since it&apos;s currently called with a continuation token, and the definition of <code>iterate</code> is that it calls the function with the return value of its previous invocation, we have no choice but to return the continuation token from the result of the <code>ListObjectsV2</code> call:</p><pre><code class="language-clojure">(:NextContinuationToken res)
</code></pre><p>The only problem with this is that now we&apos;re throwing away the actual items, so what we&apos;ll get is something like this:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (iterate (s3-page-iterator logs-client prefix) nil)
       (take 2))
  ;; =&gt; (nil
  ;;     &quot;1wfyyUjO9xuARj07VdnGBHFPmwEwTyDn7VTywaAH6L417g/fWqfeVJRrCV+nFPFHwLVJ3+CWT6BXTdzyKIPsmZm4U0VpZRffW&quot;)

)
</code></pre><p>That&apos;s not all that interesting, to be honest. The one piece of good news is that our REPL buffer looks like this:</p><pre><code class="language-text">Fetching page
</code></pre><p>We have at least succeeded in being lazy! 🏆</p><p>As things stand, our function takes the token as its argument, meaning have what we need in order to do the pagination, but not what we need in order to build up the sequence of items to return. If we think about where the token comes from, it&apos;s actually the same place as the items: the response of the <code>ListObjectsV2</code> call. So what if we return the API response from the function, meaning that the function would then be called with that response on the next iteration? That could look something like this:</p><pre><code class="language-clojure">(defn get-s3-page [{:keys [s3-client s3-bucket s3-page-size]}
                   prefix prev]
  (let [{token :NextContinuationToken} prev
        _ (println &quot;Fetching page&quot;)
        res (aws/invoke s3-client
                        {:op :ListObjectsV2
                         :request (mk-s3-req s3-bucket prefix s3-page-size token)})]
    res))

(comment

  (-&gt;&gt; (iterate (s3-page-iterator logs-client prefix) nil)
       (take 2))
  ;; =&gt; (nil
  ;;     {:Prefix &quot;logs/A1BCD23EFGHIJ4.2022-09-15-&quot;,
  ;;      :NextContinuationToken
  ;;      &quot;1s4mtjEeNyCwY1wu7URgZz/kHpfSH3HhaG26VfcL8sgSNXZF/iYdAjSNQQpTiLF+TRoIB/tD93dC/QmqcmFYo+ZgxX0oZg7+v&quot;,
  ;;      :Contents
  ;;      [{:Key &quot;logs/A1BCD23EFGHIJ4.2022-09-15-00.0125de6e.gz&quot;,
  ;;        :LastModified #inst &quot;2022-09-15T00:39:56.000-00:00&quot;,
  ;;        :ETag &quot;\&quot;0fc8a817d4f9b742b6ae83292a181385\&quot;&quot;,
  ;;        :Size 1496,
  ;;        :StorageClass &quot;STANDARD&quot;}
  ;;       ...
  ;;       {:Key &quot;logs/A1BCD23EFGHIJ4.2022-09-15-02.95762404.gz&quot;,
  ;;        :LastModified #inst &quot;2022-09-15T02:49:56.000-00:00&quot;,
  ;;        :ETag &quot;\&quot;617e1235db32c79c37f5776abc5ff3ec\&quot;&quot;,
  ;;        :Size 800,
  ;;        :StorageClass &quot;STANDARD&quot;}],
  ;;      :MaxKeys 25,
  ;;      :IsTruncated true,
  ;;      :Name &quot;logs.jmglov.net&quot;,
  ;;      :KeyCount 25})

)
</code></pre><p>This is definitely moving in the right direction, but there are a couple of issues. First things first, the first thing is <code>nil</code>, since that&apos;s the initial argument we gave to <code>iterate</code>. Second, the second thing is not a list of items, but rather a data structure containing a list of items under the <code>:Contents</code> key. We can address both of these issues by wrapping <code>get-s3-page</code> in a new function that handles turning a list of pages into a list of items:</p><pre><code class="language-clojure">(defn list-objects [logs-client prefix]
  (-&gt;&gt; (iterate (s3-page-iterator logs-client prefix) nil)
       (drop 1)
       (mapcat (comp (partial map :Key) :Contents))))

(comment

  (-&gt;&gt; (list-objects logs-client prefix)
       (take 2))
  ;; ...
  ;; ...
  ;; OMG what is going on here??? My REPL hasn&apos;t printed the result yet,
  ;; and I&apos;ve been waiting several minutes! 😱

)
</code></pre><p>Something is deeply wrong here, clearly. Looking at our REPL buffer, we find a clue:</p><pre><code class="language-text">Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
Fetching page
...
</code></pre><p>This looks like an infinite loop, and given that we&apos;re looping on the continuation token, that is probably the issue. Let&apos;s have a look at the AWS documentation for <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html">ListObjectsV2</a> and see what we can learn about the continuation token. In the response:</p><blockquote><p><strong>NextContinuationToken</strong></p><p>NextContinuationToken is sent when IsTruncated is true, which means there are more keys in the bucket that can be listed. The next list requests to Amazon S3 can be continued with this NextContinuationToken.</p><p>Type: string</p></blockquote><p>Aha! What is this <code>IsTruncated</code> of which they speak?</p><blockquote><p><strong>IsTruncated</strong></p><p>Set to false if all of the results were returned. Set to true if more keys are available to return.</p><p>Type: Boolean</p></blockquote><p>Let&apos;s think about what our <code>get-s3-page</code> function is doing when called by <code>iterate</code>. Assuming we have five pages of objects with the prefix <code>logs/A1BCD23EFGHIJ4.2022-09-15-</code>, here&apos;s what our requests will look like:</p><pre><code class="language-text"> -&gt; NextContinuationToken nil
&lt;- IsTruncated true, NextContinuationToken &quot;t1&quot;
 -&gt; NextContinuationToken &quot;t1&quot;
&lt;- IsTruncated true, NextContinuationToken &quot;t2&quot;
 -&gt; NextContinuationToken &quot;t2&quot;
&lt;- IsTruncated true, NextContinuationToken &quot;t3&quot;
 -&gt; NextContinuationToken &quot;t3&quot;
&lt;- IsTruncated true, NextContinuationToken &quot;t4&quot;
 -&gt; NextContinuationToken &quot;t4&quot;
&lt;- IsTruncated false
 -&gt; NextContinuationToken nil
&lt;- IsTruncated true, NextContinuationToken &quot;t1&quot;
...
</code></pre><p>Right, so we&apos;ll just cycle through the pages until the heat death of the universe (assuming the universe continues expanding forever and thus atoms get too far apart to bang against each other and generate thermodynamic energy, an assumption which is frankly outside the scope of this blog post which is supposed to be about making S3 requests and not theoretical astrophysics). This is clearly A Bad Thing™ (cycling through pages, I mean, not the heat death of the universe, though that would also be A Bad Thing™), so let&apos;s see if we can&apos;t reason our way out of this with a little <a href="https://youtu.be/f84n5oFoZBc">hammock
time</a> (this is actually an excuse for me to go walk Rover, since the poor fellow has been waiting 20 minutes for me to get to a good stopping point).</p><p><img alt="A dog walks in a grassy field" src="assets/2022-09-22-rover.png" title="Thanks, Dad!" /></p><p>OK, speaking of stopping points, it seems like what we need in this function is a stopping point. We know that when <code>IsTruncated</code> is false, there is no next page, so we should stop right there. Let&apos;s see how we can do that in code:</p><pre><code class="language-clojure">(defn get-s3-page [{:keys [s3-client s3-bucket s3-page-size]}
                   prefix prev]
  (let [{token :NextContinuationToken
         truncated? :IsTruncated
         page-num :page-num} prev
        page-num (if page-num (inc page-num) 1)
        done? (false? truncated?)
        res (when-not done?
              (println &quot;Fetching page&quot; page-num)
              (-&gt; (aws/invoke s3-client
                              {:op :ListObjectsV2
                               :request (mk-s3-req s3-bucket prefix s3-page-size token)})
                  (assoc :page-num page-num)))]
    res))

(comment

  (-&gt;&gt; (iterate (partial get-s3-page
                         (assoc logs-client :s3-page-size 100) prefix)
                nil)
       (take 6))
  ;; =&gt; (nil
  ;;     {:Prefix &quot;logs/E1HJS54CQLFQU4.2022-09-15-&quot;,
  ;;      :page-num 1,
  ;;      :Contents [...],
  ;;      :NextContinuationToken &quot;1kkaMk4RnoZHxnSRa5TBnVMb9NECfmmq...&quot;,
  ;;      :MaxKeys 100,
  ;;      :IsTruncated true,
  ;;      :Name &quot;logs.jmglov.net&quot;,
  ;;      :KeyCount 100}
  ;;     {:Prefix &quot;logs/E1HJS54CQLFQU4.2022-09-15-&quot;,
  ;;      :page-num 2,
  ;;      :Contents [...],
  ;;      :NextContinuationToken
  ;;      &quot;1Jz5W+GkccdkP6Jc7tDsdqqrHFlgThRSt2ZhgHh1uYPA1gIzR4aer2l...&quot;,
  ;;      :ContinuationToken
  ;;      &quot;1kkaMk4RnoZHxnSRa5TBnVMb9NECfmmqFfDLlcxdn6GdCiMc8ZzNQRj...&quot;,
  ;;      :MaxKeys 100,
  ;;      :IsTruncated true,
  ;;      :Name &quot;logs.jmglov.net&quot;,
  ;;      :KeyCount 100}
  ;;     {:Prefix &quot;logs/E1HJS54CQLFQU4.2022-09-15-&quot;,
  ;;      :page-num 3,
  ;;      :Contents [...],
  ;;      :ContinuationToken
  ;;      &quot;1Jz5W+GkccdkP6Jc7tDsdqqrHFlgThRSt2ZhgHh1uYPA1gIzR4aer2l...&quot;,
  ;;      :MaxKeys 100,
  ;;      :IsTruncated false,
  ;;      :Name &quot;logs.jmglov.net&quot;,
  ;;      :KeyCount 36}
  ;;     nil
  ;;     {:Prefix &quot;logs/E1HJS54CQLFQU4.2022-09-15-&quot;,
  ;;      :page-num 1,
  ;;      :Contents [...],
  ;;      :NextContinuationToken
  ;;      &quot;1EPegB1wcwtgRoGRiJpM4YYjiTvLHYYVjKr+ghX30LhowHoHMAepdcR...&quot;,
  ;;      :MaxKeys 100,
  ;;      :IsTruncated true,
  ;;      :Name &quot;logs.jmglov.net&quot;,
  ;;      :KeyCount 100})
       
)
</code></pre><p>This is much better! Now we can see that we fetch page 1, which contains 100 items (<code>:KeyCount</code>); page 2, which also contains 100 items; page 3, which is the last page and contains only 36 items; then since <code>:IsTruncated</code> is false the next time <code>iterate</code> calls <code>get-s3-page</code>, we don&apos;t fetch the page and just return <code>nil</code>; then we start over again with page 1, and would continue cycling forever if it hadn&apos;t been for the <code>(take 6)</code>.</p><p>This experiment has accomplished something very important, however. Now we have a marker for when we&apos;ve reached the last page and should therefore break the cycle! We can update our <code>list-objects</code> wrapper function to look for this marker:</p><pre><code class="language-clojure">(defn list-objects [logs-client prefix]
  (-&gt;&gt; (iterate (s3-page-iterator logs-client prefix) nil)
       (drop 1)
       (take-while :Contents)
       (mapcat (comp (partial map :Key) :Contents))))

(comment

  (-&gt;&gt; (list-objects logs-client prefix)
       (take 5))
  ;; =&gt; (&quot;logs/E1HJS54CQLFQU4.2022-09-15-00.0125de6e.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-00.3b36a099.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-00.54775acb.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-00.6c612378.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-00.73072440.gz&quot;)

)
</code></pre><p>Victory!</p><p>We can test out our laziness by taking 105 items, which should require fetching the first two pages of results but nothing more:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (list-objects logs-client prefix)
       (take 105))
  ;; =&gt; (&quot;logs/E1HJS54CQLFQU4.2022-09-15-00.0125de6e.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-00.3b36a099.gz&quot;
  ;;     ...
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-10.ae86e512.gz&quot;
  ;;     &quot;logs/E1HJS54CQLFQU4.2022-09-15-10.b4a720f9.gz&quot;)

)
</code></pre><p>Strangely, our REPL buffer reports that we fetched three pages:</p><pre><code class="language-text">Fetching page 1
Fetching page 2
Fetching page 3
</code></pre><p>In fact, we see the same thing even when we took just 5 items. What in the world is going on here?</p><p>Well, it turns out that Clojure realises lazy sequences in chunks; in other words, it optimistically calls the function producing the lazy sequence a few times to ensure that you have enough items in the sequence. In our case, our sequence seems to be realised in chunks of 3?</p><p>I have to admit that my knowledge of Clojure internals doesn&apos;t go this deep, and I hope someone reading this can explain things to me <a href="https://twitter.com/jmglov">on
Twitter</a>.</p><p>In any case, at least we&apos;ve accomplished our original goal of not fetching all the things when we only need some of the things. So that&apos;s something. 🤷</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-09-02-dogfooding-blambda-logs.html</id>
    <link href="https://jmglov.net/blog/2022-09-02-dogfooding-blambda-logs.html"/>
    <title>Dogfooding Blambda 5: To parse—perchance to dream</title>
    <updated>2022-09-01T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>In the last instalment of <a href="tags/blambda.html">Dogfooding Blambda</a>, we dove into <a href="2022-08-11-dogfooding-blambda-cli-ier.html">the details of how the new command line interface
works</a>. This is all well and good, but it doesn&apos;t directly help us along in our lofty goal of parsing access logs for my blog. Let&apos;s stop yak shaving and get back into it!</p><div class="markdown-heading"><h2 id="talking-to-s3">Talking to S3</h2><a href="#talking-to-s3" class="anchor" aria-label="Permalink: Talking to S3"><img src="assets/link.svg" /></a></div><p>The first order of business is figuring out how to grab the access logs from S3. As previously noted, I decided to use <a href="https://github.com/grzm/awyeah-api">awyeah-api</a>, so let&apos;s add it to our <code>bb.edn</code>:</p><pre><code class="language-clojure">{:paths [&quot;.&quot;]
 :deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.206&quot;}
        com.cognitect.aws/s3 {:mvn/version &quot;822.2.1109.0&quot;}
        com.grzm/awyeah-api {:git/url &quot;https://github.com/grzm/awyeah-api&quot;
                             :git/sha &quot;0fa7dd51f801dba615e317651efda8c597465af6&quot;}
        org.babashka/spec.alpha {:git/url &quot;https://github.com/babashka/spec.alpha&quot;
                                 :git/sha &quot;433b0778e2c32f4bb5d0b48e5a33520bee28b906&quot;}}}
</code></pre><p>After doing this, we need to build and deploy a new deps layer with Blambda:</p><pre><code class="language-text">$ bb blambda build-deps-layer --deps-path src/bb.edn
[...]
Compressing custom runtime layer: target/deps.zip

$ bb blambda deploy-deps-layer --deps-layer-name s3-log-parser-deps
Publishing layer version for layer s3-log-parser-deps
Published layer arn:aws:lambda:eu-west-1:123456789100:layer:s3-log-parser-deps:2
</code></pre><p>If you&apos;ll cast your mind back a few weeks to last time we were messing around with a lamdbda handler, you may recall that we started with something like this:</p><pre><code class="language-clojure">(ns s3-log-parser)

(defn handler [event context]
  (prn {:msg &quot;Invoked with event&quot;,
        :data {:event event}})
  {&quot;statusCode&quot; 200
   &quot;body&quot; &quot;Hello, Blambda!&quot;})
</code></pre><p>Again, no judgement—we&apos;ve gotta start somewhere—but this doesn&apos;t have much to do with S3. Let&apos;s remedy that!</p><pre><code class="language-clojure">(ns s3-log-parser
  (:require [com.grzm.awyeah.client.api :as aws]))

(comment

  ;; Don&apos;t print this!
  (def s3 (aws/client {:api :s3, :region &quot;eu-west-1&quot;}))
  ;; =&gt; #&apos;s3-log-parser/s3

  ;; Would be so useful but there are too many ops for S3 😭
  (aws/ops s3)

  ;; Prints instead of returning an object; check your REPL buffer
  (aws/doc s3 :ListObjectsV2)
  
  )
</code></pre><p>After requiring the awyeah-api client in our namespace, we&apos;ll open up a <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a> and start evaluating forms right in our source buffer! This of course assumes that you&apos;ve started a <a href="https://github.com/babashka/babashka">Babashka</a> REPL by doing something along the lines of</p><pre><code class="language-text">bb nrepl-server
</code></pre><p>and you&apos;re using something along the lines of <a href="https://docs.cider.mx/cider/index.html">CIDER</a> and you&apos;ve told your editor (Emacs, I hope) to connect to the Babashka REPL. The next step is to evaluate the buffer (<strong>C-c C-k</strong> in CIDER, which runs <code>cider-load-buffer</code>) so that the namespace is loaded.</p><p>Once you&apos;ve done that stuff, putting your cursor at the end of a form and hitting <strong>C-c C-v f c e</strong> (<code>cider-pprint-eval-last-sexp-to-comment</code>)—or the equivalent in your editor—should result in the form being evaluated and the result being printed back to your code buffer. That&apos;s what the</p><pre><code class="language-clojure">;; =&gt; #&apos;s3-log-parser/s3
</code></pre><p>stuff is in my code blocks. Whenever you see <code>;; =&gt; </code>, you&apos;ll know that is the result of evaluating a form. It&apos;s a really nice way to do REPL-driven development; you can do little experiments right next to the bit of code you&apos;re working on, and it&apos;s easy to copy and paste bits of those experiments into functions and so on.</p><p>The first thing we&apos;re doing inside the comment is creating an S3 client using the <a href="https://cognitect-labs.github.io/aws-api/cognitect.aws.client.api-api.html#cognitect.aws.client.api/client">aws/client</a> function. The reason I have that little note not to print the result is that <code>aws/client</code> returns this big data structure describing all of the stuff the client can do, which in the case of S3 takes about 2000 lines to print, which takes CIDER a few seconds to do and really gunks up my code buffer. So instead of <strong>C-c C-v f c e</strong>, I do <strong>C-c C-e</strong> (<code>cider-eval-last-sexp</code>), which evaluates the form and prints the result in a temporary popup thingy instead of as a comment back into my code buffer.</p><p>The <a href="https://cognitect-labs.github.io/aws-api/cognitect.aws.client.api-api.html#cognitect.aws.client.api/ops">aws/ops</a> function is also really useful for clients that are a bit smaller than S3&apos;s. It prints out all of the operations a client can perform, along with the parameters and return values of the operation. Again, it is too much to print here. 😭</p><p>The <a href="https://cognitect-labs.github.io/aws-api/cognitect.aws.client.api-api.html#cognitect.aws.client.api/doc">aws/doc</a> function can help us out, though. It takes a client and an operation and prints out a nice documentation string. If I move my cursor to the end of the form and do a nice little <strong>C-c C-e</strong>, I get the following printed into my REPL buffer:</p><pre><code class="language-text">-------------------------
ListObjectsV2

&lt;p&gt;Returns some or all (up to 1,000) of the objects in a bucket with each request.
You can use the request parameters as selection criteria to return a subset of
the objects in a bucket. A &lt;code&gt;200 OK&lt;/code&gt; response can contain valid or
invalid XML. Make sure to design your application to parse the contents of the
[...]
&lt;/p&gt; &lt;/li&gt; &lt;/ul&gt;

-------------------------
Request

{:Prefix string,
 :StartAfter string,
 :Bucket string,
 :EncodingType [:one-of [&quot;url&quot;]],
 :Delimiter string,
 :FetchOwner boolean,
 :RequestPayer [:one-of [&quot;requester&quot;]],
 :ContinuationToken string,
 :MaxKeys integer,
 :ExpectedBucketOwner string}

Required

[:Bucket]

-------------------------
Response

{:Prefix string,
 :StartAfter string,
 :EncodingType [:one-of [&quot;url&quot;]],
 :Delimiter string,
 :NextContinuationToken string,
 :CommonPrefixes [:seq-of {:Prefix string}],
 :ContinuationToken string,
 :Contents
 [:seq-of
  {:Key string,
   :LastModified timestamp,
   :ETag string,
   :ChecksumAlgorithm
   [:seq-of [:one-of [&quot;CRC32&quot; &quot;CRC32C&quot; &quot;SHA1&quot; &quot;SHA256&quot;]]],
   :Size integer,
   :StorageClass
   [:one-of
    [&quot;STANDARD&quot;
     &quot;REDUCED_REDUNDANCY&quot;
     &quot;GLACIER&quot;
     &quot;STANDARD_IA&quot;
     &quot;ONEZONE_IA&quot;
     &quot;INTELLIGENT_TIERING&quot;
     &quot;DEEP_ARCHIVE&quot;
     &quot;OUTPOSTS&quot;
     &quot;GLACIER_IR&quot;]],
   :Owner {:DisplayName string, :ID string}}],
 :MaxKeys integer,
 :IsTruncated boolean,
 :Name string,
 :KeyCount integer}
</code></pre><p>OK, that&apos;s pretty cool. Most of the time, however, I find it easier to just use the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html">AWS API
documentation</a>.</p><p>Anyway, we&apos;ve now figured out that we want to use the <code>ListObjectsV2</code> operation, and we know from the docs that it needs a bucket and can take a key prefix to return only objects in a certain folder hierarchy, as it were. We can also add a maximum number of objects to return for testing purposes.</p><p>At this point, we have all the information we need to write a function to list S3 objects with a certain prefix, so we could go ahead and slap it in our code. However, I don&apos;t ever trust myself to have read the docs correctly, so I always just try things out in my REPL first to see what happens:</p><pre><code class="language-clojure">(comment

  (aws/invoke s3 {:op :ListObjectsV2
                  :request {:Bucket &quot;logs.jmglov.net&quot;
                            :Prefix &quot;logs/2022-06-26&quot;
                            :MaxKeys 2}})
  ;; =&gt; {:Prefix &quot;logs/2022-06-26&quot;,
  ;;     :NextContinuationToken
  ;;     &quot;1ClCd7jr58LZ6u1Ts2UAEknPY2/jktCdH8LS3lGtB7oJskG+l1K4+97f+KCSZ6AhI69gyHv9phN8L8nKnbkqTxc/NT/GWdz9A&quot;,
  ;;     :Contents
  ;;     [{:Key &quot;logs/2022-06-26-00-14-34-7526D4F869A33078&quot;,
  ;;       :LastModified #inst &quot;2022-06-26T00:14:35.000-00:00&quot;,
  ;;       :ETag &quot;\&quot;815876abf870fa05421183daa60a0513\&quot;&quot;,
  ;;       :Size 366,
  ;;       :StorageClass &quot;STANDARD&quot;}
  ;;      {:Key &quot;logs/2022-06-26-00-14-36-F1E7815BC3A92960&quot;,
  ;;       :LastModified #inst &quot;2022-06-26T00:14:37.000-00:00&quot;,
  ;;       :ETag &quot;\&quot;91b2ceef95e28d72384ff55b77453a71\&quot;&quot;,
  ;;       :Size 383,
  ;;       :StorageClass &quot;STANDARD&quot;}],
  ;;     :MaxKeys 2,
  ;;     :IsTruncated true,
  ;;     :Name &quot;logs.jmglov.net&quot;,
  ;;     :KeyCount 2}
  
  )
</code></pre><p>Nice! I got the request right on the first try, and now we know what the response looks like. The power of REPL-driven development is evident here, in that I&apos;m playing with real data, not copying and pasting from an example response or something like that. Documentation sometimes lies, but real services don&apos;t.</p><p>OK, so now we know how to use <code>ListObjectsV2</code>, so let&apos;s turn this stuff into a proper function that returns all of the log objects for a specific date. Let&apos;s also remove the hard-coded stuff and put it in a <code>config</code> map:</p><pre><code class="language-clojure">(def config {:region &quot;eu-west-1&quot;
             :s3-bucket &quot;logs.jmglov.net&quot;
             :s3-prefix &quot;logs/&quot;})

(defn list-logs [date]
  (let [{:keys [region s3-bucket s3-prefix]} config
        request {:Bucket s3-bucket
                 :Prefix (format &quot;%s%s&quot; s3-prefix date)}
        response (aws/invoke s3 {:op :ListObjectsV2
                                 :request request})]
    (prn {:msg &quot;Listing log files&quot;, :data request})
    (prn {:msg &quot;Response&quot;, :data response})
    (-&gt;&gt; response
         :Contents
         (map :Key))))
</code></pre><p>Having written a shiny new function, we&apos;ll want to prove to ourselves that it works by testing it out. We could write a unit test (OK, it&apos;s not really a unit test, but you get what I mean), but that would require setting up test machinery which we currently don&apos;t have, which sounds quite distracting. How&apos;s about we embrace the REPL and just test stuff out in a comment block right below the function we&apos;ve written?</p><p>The first step is loading the new code into our environment, which we can do by evaluating the buffer again (<strong>C-c C-k</strong> or your editor&apos;s equivalent). Having done that, we write a function call and do the eval and print dance (<strong>C-c C-v f c e</strong> or your editor&apos;s equivalent):</p><pre><code class="language-clojure">(comment

  (list-logs &quot;2022-06-28&quot;)
  ;; =&gt; (&quot;logs/2022-06-28-00-12-36-5E32B8C5369C818E&quot;
  ;;     &quot;logs/2022-06-28-00-15-28-989878A1E585B6F5&quot;)

  )
</code></pre><p>Awesome, the function works as designed! 🎉</p><div class="markdown-heading"><h2 id="talking-back">Talking back</h2><a href="#talking-back" class="anchor" aria-label="Permalink: Talking back"><img src="assets/link.svg" /></a></div><p>Now that we know how to list objects, let&apos;s make the lambda do the business! That requires us to do the following:</p><ol start="1"><li>Modify our <code>config</code> map to load configuration from the environment</li><li>Print a nice little log statement that lets us know that the Lambda is cold starting (any code that is outside the handler function will only run when a new lambda instance is started; after that, the namespace is already loaded, so the runtime will just call the handler function for subsequent requests)</li><li>Create an S3 client (again, outside the handler function so the S3 client will persist across requests; this is a common pattern for expensive operations like creating clients or populating caches or whatever)</li><li>Making our handler function call <code>list-logs</code>, then JSON-encode the result into the lambda&apos;s response body</li></ol><p>Here&apos;s what that looks like:</p><pre><code class="language-clojure">(ns s3-log-parser
  (:require [com.grzm.awyeah.client.api :as aws]
            [cheshire.core :as json]))

(def config
  {:region (System/getenv &quot;AWS_REGION&quot;)
   :s3-bucket (System/getenv &quot;S3_BUCKET&quot;)
   :s3-prefix (System/getenv &quot;S3_PREFIX&quot;)})

(prn {:msg &quot;Lambda starting&quot;, :data {:config config}})

(def s3 (aws/client {:api :s3, :region (:region config)}))

(defn list-logs [date]
  (let [{:keys [region s3-bucket s3-prefix]} config
        request {:Bucket s3-bucket
                 :Prefix (format &quot;%s%s&quot; s3-prefix date)}
        response (aws/invoke s3 {:op :ListObjectsV2
                                 :request request})]
    (prn {:msg &quot;Listing log files&quot;, :data request})
    (prn {:msg &quot;Response&quot;, :data response})
    (-&gt;&gt; response
         :Contents
         (map :Key))))

(defn handler [event _context]
  (prn {:msg &quot;Invoked with event&quot;, :data {:event event}})
  (let [logs (list-logs &quot;2022-06-26&quot;)]
    {&quot;statusCode&quot; 200
     &quot;body&quot; (json/encode {:logs logs})}))
</code></pre><p>Again, let&apos;s prove this works before actually deploying a lambda. We&apos;ll evaluate the buffer to pick up the new handler, but now we might have a slight issue:</p><pre><code class="language-clojure">(comment

  config
  ;; =&gt; {:region nil, :s3-bucket nil, :s3-prefix nil}

  )
</code></pre><p>The <code>config</code> map is being initialised from environment variables that we haven&apos;t set. We could set the environment variables and then restart our REPL, but that doesn&apos;t feel like the Clojure way. Why don&apos;t we just re-define <code>config</code> and the S3 client in our comment block instead?</p><pre><code class="language-clojure">(comment

  (def config {:region &quot;eu-west-1&quot;
               :s3-bucket &quot;logs.jmglov.net&quot;
               :s3-prefix &quot;logs/&quot;})
  ;; =&gt; #&lt;Var@6c7f283b:
  ;;      {:region &quot;eu-west-1&quot;, :s3-bucket &quot;logs.jmglov.net&quot;, :s3-prefix &quot;logs/&quot;}&gt;

  ;; Don&apos;t print this! Use C-c C-e instead.
  (def s3 (aws/client {:api :s3, :region (:region config)}))

  )
</code></pre><p>Now we can actually test the handler function in our REPL:</p><pre><code class="language-clojure">(comment

  (handler {} {})
  ;; =&gt; {&quot;statusCode&quot; 200,
  ;;     &quot;body&quot;
  ;;     &quot;{\&quot;logs\&quot;:[\&quot;logs/2022-06-26-00-14-34-7526D4F869A33078\&quot;,\&quot;logs/2022-06-26-00-14-36-F1E7815BC3A92960\&quot;]}&quot;}

  )
</code></pre><p>Looks like it works! Let&apos;s try it out as an actual lambda!</p><p>If we open the <a href="https://eu-west-1.console.aws.amazon.com/lambda/#/functions">AWS Lambda
console</a> and click on our s3-log-parser function, we now need to do three things:</p><ol start="1"><li>Update the configuration to use the new version of the s3-log-parser-deps layer that we previously deployed</li><li>Set the environment variables that our code is expecting</li><li>Update the code itself</li></ol><p>For the first step, let&apos;s take a look at the <strong>Function overview</strong> section in the console:</p><p>![Screenshot of the Function overview section in the Lambda
console](assets/2022-09-02-overview.png &quot;Click on Layers&quot; class=&quot;border&quot;)</p><p>If we click on the &quot;Layers&quot; icon and then <strong>Edit</strong>, we can see that our function is currently using two layers: the blambda runtime and the deps layer:</p><p>![Screenshot of the Edit layers page in the Lambda console](assets/2022-09-02-layers.png &quot;Change deps layer version and save&quot; class=&quot;border&quot;)</p><p>We need to change the version of the <code>s3-log-parser-deps</code> to 2 and then click <strong>Save</strong>.</p><p>Now that our deps are updated, let&apos;s set the environment variables. If we click on the <strong>Configuration</strong> tab just under the function overview, we see <strong>Environment variables</strong> on the left hand side. Clicking that reveals that we have no environment variables currently set:</p><p>![Screenshot of the Configuration tab in the Lambda
console](assets/2022-09-02-env.png &quot;Click Edit&quot; class=&quot;border&quot;)</p><p>Let&apos;s click the <strong>Edit</strong> button and add the <code>S3_BUCKET</code> and <code>S3_PREFIX</code> environment variables (<code>AWS_REGION</code> is set by the Lambda instance itself, so we don&apos;t need to set it):</p><p>![Screenshot of the Edit environment variables page in the Lambda
console](assets/2022-09-02-env-filled.png &quot;Click Save&quot; class=&quot;border&quot;)</p><p>And now it&apos;s time for the code itself. Let&apos;s click on the <strong>Code</strong> tab, then just copy and paste the contents of our editor&apos;s code buffer over top of the code in <code>s3_log_parser.clj</code>:</p><p>![Screenshot of the Code source tab in the Lambda
console](assets/2022-09-02-code1.png &quot;Click Deploy&quot; class=&quot;border&quot;)</p><p>The really cool thing about Rich comments is that we don&apos;t need to remove them from our source code, since they&apos;re not evaluated when loading the namespace!</p><p>Now we click <strong>Deploy</strong> to get the new code out there, and there&apos;s only one thing standing between us and glory: configuring a test event. In order to do this, we need to click the dropdown on the <strong>Test</strong> button, then select <strong>Create new event</strong>. We can fill in something like &quot;test&quot; for the <strong>Event name</strong>, leave the <strong>Event sharing settings</strong> to the default of &quot;Private&quot;, and then click on the <strong>Template</strong> dropdown and select &quot;API Gateway AWS Proxy&quot; (since we intend this lambda to be invoked using a <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html">function
URL</a>, which uses the same input payload as AWS Gateway):</p><p>![Screenshot of the Configure test event window in the Lambda
console](assets/2022-09-02-test-event.png &quot;Click Save&quot; class=&quot;border&quot;)</p><p>If we scroll down and click <strong>Save</strong>, we&apos;re in business! Now we can click the <strong>Test</strong> button and revel in our success:</p><p>![Screenshot of the Execution results tab in the Lambda
console](assets/2022-09-02-test1.png &quot;Victory!&quot; class=&quot;border&quot;)</p><div class="markdown-heading"><h2 id="accepting-input">Accepting input</h2><a href="#accepting-input" class="anchor" aria-label="Permalink: Accepting input"><img src="assets/link.svg" /></a></div><p>As amazing as all this is, it is a little limiting that our lambda only lists logs for 2022-06-26. How about we accept the date as a query string parameter instead? Looking at the <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html">AWS Lambda proxy integration
payload</a>, we can see that the query parameters are exposed in a <code>queryStringParameters</code> object in the event. Let&apos;s grab that and use it as the <code>date</code> parameter to <code>list-logs</code>:</p><pre><code class="language-clojure">(defn handler [event _context]
  (prn {:msg &quot;Invoked with event&quot;, :data {:event event}})
  (let [date (get-in event [&quot;queryStringParameters&quot; &quot;date&quot;])
        logs (list-logs date)]
    {&quot;statusCode&quot; 200
     &quot;body&quot; (json/encode {:logs logs})}))

(comment

  (def event {&quot;queryStringParameters&quot; {&quot;date&quot; &quot;2022-09-02&quot;}})
  ;; =&gt; #&lt;Var@4262c861: {&quot;queryStringParameters&quot; {&quot;date&quot; &quot;2022-09-02&quot;}}&gt;

  (handler event {})
  ;; =&gt; {&quot;statusCode&quot; 200,
  ;;     &quot;body&quot;
  ;;     &quot;{\&quot;logs\&quot;:[\&quot;logs/2022-09-02-00-12-42-F789B0CC4E3D8814\&quot;,\&quot;logs/2022-09-02-00-13-14-534A4D7BB857B5D3\&quot;]}&quot;}

  )
</code></pre><p>This whole <code>(prn {:msg ...})</code> thing is getting a bit tiring, so let&apos;s add a <code>log</code> function instead. We might as well also add the timestamp to the log message whilst we&apos;re at it:</p><pre><code class="language-clojure">(ns s3-log-parser
  (:require [cheshire.core :as json]
            [com.grzm.awyeah.client.api :as aws])
  (:import (java.time Instant)))

(defn log [msg data]
  (prn {:msg msg
        :data data
        :timestamp (str (Instant/now))}))
</code></pre><p>OK, this is moving in the right direction, but what if someone sends in the date in the wrong format?</p><pre><code class="language-clojure">(comment

  (handler {&quot;queryStringParameters&quot; {&quot;date&quot; &quot;2/9/2022&quot;}} {})
  ;; =&gt; {&quot;statusCode&quot; 200, &quot;body&quot; &quot;{\&quot;logs\&quot;:[]}&quot;}

  )
</code></pre><p>I mean, this is technically correct, but it would be much more friendly to actually let the caller know that they did something wrong. Let&apos;s parse the date to be sure it&apos;s valid before handing it off to <code>list-logs</code>:</p><pre><code class="language-clojure">(ns s3-log-parser
  (:require [cheshire.core :as json]
            [com.grzm.awyeah.client.api :as aws])
  (:import (java.time Instant
                      LocalDate)))

(defn get-date [date-str]
  (try
    (LocalDate/parse date-str)
    (catch Exception _
      (let [msg (format &quot;Invalid date: %s&quot; date-str)
            data {:date date-str}]
        (log msg data)
        (throw (ex-info msg data))))))

(comment

  (get-date &quot;2/9/2022&quot;)
  ;; =&gt; : Invalid date: 2/9/2022 s3-log-parser 

  )
</code></pre><p>Cool. There&apos;s another annoyance here, though: we&apos;re logging the error and then throwing an exception with the exact same data. Let&apos;s create a function to do this for us, and then we can be more concise in <code>get-date</code>:</p><pre><code class="language-clojure">(defn error [msg data]
  (log msg data)
  (throw (ex-info msg data)))

(defn get-date [date-str]
  (try
    (LocalDate/parse date-str)
    (catch Exception _
      (error (format &quot;Invalid date: %s&quot; date-str) {:date date-str}))))

(comment

  (get-date &quot;2022-06-28&quot;)
  ;; =&gt; #object[java.time.LocalDate 0x502a28d3 &quot;2022-06-28&quot;]

  (get-date &quot;2/9/2022&quot;)
  ;; =&gt; : Invalid date: nope s3-log-parser 

  )
</code></pre><p>If we think a little about our API, it seems probable that someone could call it without providing a date parameter, in which case it seems reasonable to get today&apos;s logs. Let&apos;s update <code>get-date</code> accordingly:</p><pre><code class="language-clojure">(defn get-date [date-str]
  (if date-str
    (try
      (LocalDate/parse date-str)
      (catch Exception _
        (error (format &quot;Invalid date: %s&quot; date-str) {:date date-str})))
    (LocalDate/now)))

(comment

  (get-date nil)
  ;; =&gt; #object[java.time.LocalDate 0x1b2b5155 &quot;2022-09-02&quot;]

  )
</code></pre><p>Now that <code>get-date</code> can throw an exception, we should handle that by returning a 400:</p><pre><code class="language-clojure">(defn handler [event _context]
  (log &quot;Invoked with event&quot; {:event event})
  (try
    (let [date (get-date (get-in event [&quot;queryStringParameters&quot; &quot;date&quot;]))
          logs (list-logs date)]
      {&quot;statusCode&quot; 200
       &quot;body&quot; (json/encode {:logs logs})})
     (catch Exception e
       (log (ex-message e) (ex-data e))
       {&quot;statusCode&quot; 400
        &quot;body&quot; (ex-message e)}))))

(comment

  (handler {&quot;queryStringParameters&quot; {&quot;date&quot; &quot;2022-06-28&quot;}} {})
  ;; =&gt; {&quot;statusCode&quot; 200,
  ;;     &quot;body&quot;
  ;;     &quot;{\&quot;logs\&quot;:[\&quot;logs/2022-06-28-00-12-36-5E32B8C5369C818E\&quot;,\&quot;logs/2022-06-28-00-15-28-989878A1E585B6F5\&quot;]}&quot;}

  (handler {} {})
  ;; =&gt; {&quot;statusCode&quot; 200,
  ;;     &quot;body&quot;
  ;;     &quot;{\&quot;logs\&quot;:[\&quot;logs/2022-09-01-00-12-48-36034402F760D842\&quot;,\&quot;logs/2022-09-01-00-13-47-48D19FF5B34710F9\&quot;]}&quot;}

  )
</code></pre><div class="markdown-heading"><h2 id="gettin&apos;-loggy-wit&apos;-it">Gettin&apos; loggy wit&apos; it</h2><a href="#gettin&apos;-loggy-wit&apos;-it" class="anchor" aria-label="Permalink: Gettin&apos; loggy wit&apos; it"><img src="assets/link.svg" /></a></div><p>Alright, we now have a lambda that can list logs. However, that&apos;s not really what we set out to do; we actually wanted to parse the logs and return the data contained therein. Of course, a necessary precursor to parsing the logs is actually retrieving them from S3. Looking at the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_Operations.html">S3 API
documentation</a>, the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html">GetObject</a> operation looks promising. Let&apos;s try it out!</p><pre><code class="language-clojure">(comment

  (aws/invoke s3 {:op :GetObject
                  :request {:Bucket (:s3-bucket config)
                            :Key &quot;logs/2022-06-28-00-15-28-989878A1E585B6F5&quot;}})
  ;; =&gt; {:LastModified #inst &quot;2022-06-28T00:15:29.000-00:00&quot;,
  ;;     :ETag &quot;\&quot;59877f6538514fe39b6874d9220c10a6\&quot;&quot;,
  ;;     :Metadata {},
  ;;     :ServerSideEncryption &quot;AES256&quot;,
  ;;     :ContentLength 379,
  ;;     :ContentType &quot;text/plain&quot;,
  ;;     :AcceptRanges &quot;bytes&quot;,
  ;;     :Body
  ;;     #object[java.io.BufferedInputStream 0x61636398 &quot;java.io.BufferedInputStream@61636398&quot;]}

  )
</code></pre><p>OK, so <code>GetObject</code> returns the contents of the object as a <code>BufferedInputStream</code>. In order to do something reasonable with that, we need to wrap it in some sort of reader, which we can do with <a href="https://clojuredocs.org/clojure.java.io/reader">clojure.java.io/reader</a>:</p><pre><code class="language-clojure">(ns s3-log-parser
  (:require [clojure.java.io :as io]
            [cheshire.core :as json]
            [com.grzm.awyeah.client.api :as aws])
  (:import (java.time Instant
                      LocalDate)))

(comment
  (-&gt;&gt; (aws/invoke s3 {:op :GetObject
                       :request {:Bucket (:s3-bucket config)
                                 :Key &quot;logs/2022-06-28-00-15-28-989878A1E585B6F5&quot;}})
       :Body
       io/reader)
  ;; =&gt; #object[java.io.BufferedReader 0x7aac737b &quot;java.io.BufferedReader@7aac737b&quot;]

  (-&gt;&gt; (aws/invoke s3 {:op :GetObject
                       :request {:Bucket (:s3-bucket config)
                                 :Key &quot;logs/2022-06-28-00-15-28-989878A1E585B6F5&quot;}})
       :Body
       io/reader
       slurp)
  ;; =&gt; &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:44:08 +0000] 64.252.68.192 - DC5849267MERJ0J5 WEBSITE.GET.OBJECT blog/atom.xml \&quot;GET /blog/atom.xml HTTP/1.1\&quot; 304 - - 87380 25 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - xm6O1t0x9H8Opu44YrFM/PxX/SUFizd4pS1/FJ/oJqdywpkzcmqx/N7Kv2eMF1Ij+32rM17h/HQ= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -\n&quot;

  )
</code></pre><p>Reading the contents into a string with <a href="https://clojuredocs.org/clojure.core/slurp">slurp</a> is cool, but it would be nicer if we can get a sequence of lines. There&apos;s a helpful function in clojure.core called <a href="https://clojuredocs.org/clojure.core/line-seq">line-seq</a>, which does just that. Even better, it can also consume from a reader!</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (aws/invoke s3 {:op :GetObject
                       :request {:Bucket (:s3-bucket config)
                                 :Key &quot;logs/2022-06-28-00-15-28-989878A1E585B6F5&quot;}})
       :Body
       io/reader
       line-seq)
  ;; =&gt; (&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:44:08 +0000] 64.252.68.192 - DC5849267MERJ0J5 WEBSITE.GET.OBJECT blog/atom.xml \&quot;GET /blog/atom.xml HTTP/1.1\&quot; 304 - - 87380 25 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - xm6O1t0x9H8Opu44YrFM/PxX/SUFizd4pS1/FJ/oJqdywpkzcmqx/N7Kv2eMF1Ij+32rM17h/HQ= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;)

  )
</code></pre><p>Now that we&apos;ve learned how to grab lines from a log, let&apos;s put it in a function:</p><pre><code class="language-clojure">(defn get-log-lines [s3-key]
  (-&gt;&gt; (aws/invoke s3 {:op :GetObject
                       :request {:Bucket (:s3-bucket config)
                                 :Key s3-key}})
       :Body
       io/reader
       line-seq))

(comment

  (get-log-lines &quot;logs/2022-06-28-00-15-28-989878A1E585B6F5&quot;)
  ;; =&gt; (&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:44:08 +0000] 64.252.68.192 - DC5849267MERJ0J5 WEBSITE.GET.OBJECT blog/atom.xml \&quot;GET /blog/atom.xml HTTP/1.1\&quot; 304 - - 87380 25 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - xm6O1t0x9H8Opu44YrFM/PxX/SUFizd4pS1/FJ/oJqdywpkzcmqx/N7Kv2eMF1Ij+32rM17h/HQ= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;)

  )
</code></pre><p>Now we can glue together what we&apos;ve done so far to get all the log lines for a specific date!</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; (list-logs &quot;2022-06-28&quot;)
       (mapcat get-log-lines))
  ;; =&gt; (&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:30:23 +0000] 64.252.88.38 - DA5918VPJFK9A654 WEBSITE.GET.OBJECT blog/2022-06-21-todo-list.html \&quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1\&quot; 304 - - 5447 32 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;
  ;;     &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:44:08 +0000] 64.252.68.192 - DC5849267MERJ0J5 WEBSITE.GET.OBJECT blog/atom.xml \&quot;GET /blog/atom.xml HTTP/1.1\&quot; 304 - - 87380 25 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - xm6O1t0x9H8Opu44YrFM/PxX/SUFizd4pS1/FJ/oJqdywpkzcmqx/N7Kv2eMF1Ij+32rM17h/HQ= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;)

  )
</code></pre><p>Now we&apos;re getting somewhere!</p><div class="markdown-heading"><h2 id="errors-and-taxes">Errors and taxes</h2><a href="#errors-and-taxes" class="anchor" aria-label="Permalink: Errors and taxes"><img src="assets/link.svg" /></a></div><p>Of course, we haven&apos;t taken into account the fact that calls to S3 can fail, and of course anything that <strong>can</strong> fail <strong>will</strong> eventually fail. Let&apos;s see what happens if we feed <code>GetObject</code> a key that doesn&apos;t exist:</p><pre><code class="language-clojure">(comment

  (aws/invoke s3 {:op :GetObject
                  :request {:Bucket (:s3-bucket config)
                            :Key &quot;NOPE!&quot;}})
  ;; =&gt; {:Error
  ;;     {:HostIdAttrs {},
  ;;      :KeyAttrs {},
  ;;      :Message &quot;The specified key does not exist.&quot;,
  ;;      :Key &quot;NOPE!&quot;,
  ;;      :CodeAttrs {},
  ;;      :RequestIdAttrs {},
  ;;      :HostId
  ;;      &quot;Qfz+CzbvxySHBLdd1vIfX8rd8dpkgl1fnlxLTWSHGdtt77jqh/n9EJNzHiqKhZeqqMWP+ZUMRBQ=&quot;,
  ;;      :MessageAttrs {},
  ;;      :RequestId &quot;0TESGW38EP6NQ6XK&quot;,
  ;;      :Code &quot;NoSuchKey&quot;},
  ;;     :ErrorAttrs {},
  ;;     :cognitect.anomalies/category :cognitect.anomalies/not-found}

  )
</code></pre><p>OK, this is straightforward enough to handle. We&apos;ll just check for an <code>:Error</code> key in the response and call our <code>error</code> function to log and throw:</p><pre><code class="language-clojure">(defn get-log-lines [s3-key]
  (let [resp (aws/invoke s3 {:op :GetObject
                             :request {:Bucket (:s3-bucket config)
                                       :Key s3-key}})]
    (if (:Error resp)
      (error (-&gt; resp :Error :Message) (:Error resp))
      (-&gt;&gt; resp
           :Body
           io/reader
           line-seq))))

(comment

  (get-log-lines &quot;NOPE!&quot;)
  ;; =&gt; : The specified key does not exist. s3-log-parser

  )
</code></pre><p>It is a little distracting to have this if / else conditional in the middle of our otherwise pristine <code>get-log-lines</code> function, however. Let&apos;s pull error handling out into a separate function:</p><pre><code class="language-clojure">(defn handle-error [{err :Error :as resp}]
  (if err
    (error (:Message err) err)
    resp))

(comment

  (handle-error
   {:Error
    {:HostIdAttrs {},
     :KeyAttrs {},
     :Message &quot;The specified key does not exist.&quot;,
     :Key &quot;NOPE!&quot;,
     :CodeAttrs {},
     :RequestIdAttrs {},
     :HostId
     &quot;Qfz+CzbvxySHBLdd1vIfX8rd8dpkgl1fnlxLTWSHGdtt77jqh/n9EJNzHiqKhZeqqMWP+ZUMRBQ=&quot;,
     :MessageAttrs {},
     :RequestId &quot;0TESGW38EP6NQ6XK&quot;,
     :Code &quot;NoSuchKey&quot;},
    :ErrorAttrs {},
    :cognitect.anomalies/category :cognitect.anomalies/not-found})
  ;; =&gt; : The specified key does not exist. s3-log-parser

  (handle-error {:foo 1})
  ;; =&gt; {:foo 1}

  )
</code></pre><p>Now we can keep <code>get-log-lines</code> focused on the happy path:</p><pre><code class="language-clojure">(defn get-log-lines [s3-key]
  (-&gt;&gt; (aws/invoke s3 {:op :GetObject
                       :request {:Bucket (:s3-bucket config)
                                 :Key s3-key}})
       handle-error
       :Body
       io/reader
       line-seq))
</code></pre><div class="markdown-heading"><h2 id="picking-up-the-pieces">Picking up the pieces</h2><a href="#picking-up-the-pieces" class="anchor" aria-label="Permalink: Picking up the pieces"><img src="assets/link.svg" /></a></div><p>We now have what we need to read logs, so let&apos;s update the handler to do just that:</p><pre><code class="language-clojure">(defn handler [event _context]
  (log &quot;Invoked with event&quot; {:event event})
  (try
    (let [date (get-date (get-in event [&quot;queryStringParameters&quot; &quot;date&quot;]))
          logs (list-logs date)
          log-lines (mapcat get-log-lines logs)]
      {&quot;statusCode&quot; 200
       &quot;body&quot; (json/encode {:logs logs
                            :lines log-lines})})
     (catch Exception e
       (log (ex-message e) (ex-data e))
       {&quot;statusCode&quot; 400
        &quot;body&quot; (ex-message e)}))))

(comment

  (handler {} {})
  ;; =&gt; {&quot;statusCode&quot; 200,
  ;;     &quot;body&quot;
  ;;     &quot;{\&quot;logs\&quot;:[\&quot;logs/2022-09-01-00-12-48-36034402F760D842\&quot;,\&quot;logs/2022-09-01-00-13-47-48D19FF5B34710F9\&quot;],\&quot;lines\&quot;:[\&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [31/Aug/2022:23:40:32 +0000] 64.252.89.133 - BC0KZGTDKR1QP07G WEBSITE.HEAD.OBJECT blog/2022-08-26-doing-software-wrong.html \\\&quot;HEAD /blog/2022-08-26-doing-software-wrong.html HTTP/1.1\\\&quot; 304 - - 7536 34 - \\\&quot;-\\\&quot; \\\&quot;Amazon CloudFront\\\&quot; - ApxkRhuJl/C73ZiR70xT6Stn2b1RkIcDPMnapeH5kWWQ+mT41qXfNeLaqpMc3j+5WCnrqoJH8N0= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -\&quot;,\&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [31/Aug/2022:23:14:14 +0000] 64.252.73.234 - M987YV3YB7DHBWA3 WEBSITE.GET.OBJECT index.html \\\&quot;GET / HTTP/1.1\\\&quot; 304 - - 3459 18 - \\\&quot;-\\\&quot; \\\&quot;Amazon CloudFront\\\&quot; - 14MYY/WyblbL1WgULsK86Cwwtn+tHCOgs+Y98xIkC/EIwkqMeN/SWpBsF6x2gC1Tir7DYRc/+Zk= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -\&quot;]}&quot;}


  )
</code></pre><p>It&apos;s neat to be able to test the handler in the REPL, but it is a little annoying to have to always invoke it like <code>(handler {} {})</code> if we just want an empty event. Let&apos;s use Clojure&apos;s multi-arity functions to define a <code>handler/0</code> and a <code>handler/1</code> (the way you reference functions of different arities in Erlang is simply the best; read <code>handler/0</code> as &quot;a function <code>handler</code> taking 0 arguments&quot;, and <code>handler/1</code> as &quot;a function <code>handler</code> taking 1 argument&quot;).</p><pre><code class="language-clojure">(defn handler
  ([]
   (handler {} {}))
  ([event]
   (handler event {}))
  ([event _context]
   (log &quot;Invoked with event&quot; {:event event})
   (try
     (let [date (get-date (get-in event [&quot;queryStringParameters&quot; &quot;date&quot;]))
           logs (list-logs date)
           log-lines (mapcat get-log-lines logs)]
       {&quot;statusCode&quot; 200
        &quot;body&quot; (json/encode {:logs logs
                             :lines log-lines})})
     (catch Exception e
       (log (ex-message e) (ex-data e))
       {&quot;statusCode&quot; 400
        &quot;body&quot; (ex-message e)}))))

(comment

  (handler)
  ;; =&gt; {&quot;statusCode&quot; 200,
  ;;     &quot;body&quot;
  ;;     &quot;{\&quot;logs\&quot;:[\&quot;logs/2022-09-01-00-12-48-36034402F760D842\&quot;,\&quot;logs/2022-09-01-00-13-47-48D19FF5B34710F9\&quot;],\&quot;lines\&quot;:[\&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [31/Aug/2022:23:40:32 +0000] 64.252.89.133 - BC0KZGTDKR1QP07G WEBSITE.HEAD.OBJECT blog/2022-08-26-doing-software-wrong.html \\\&quot;HEAD /blog/2022-08-26-doing-software-wrong.html HTTP/1.1\\\&quot; 304 - - 7536 34 - \\\&quot;-\\\&quot; \\\&quot;Amazon CloudFront\\\&quot; - ApxkRhuJl/C73ZiR70xT6Stn2b1RkIcDPMnapeH5kWWQ+mT41qXfNeLaqpMc3j+5WCnrqoJH8N0= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -\&quot;,\&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [31/Aug/2022:23:14:14 +0000] 64.252.73.234 - M987YV3YB7DHBWA3 WEBSITE.GET.OBJECT index.html \\\&quot;GET / HTTP/1.1\\\&quot; 304 - - 3459 18 - \\\&quot;-\\\&quot; \\\&quot;Amazon CloudFront\\\&quot; - 14MYY/WyblbL1WgULsK86Cwwtn+tHCOgs+Y98xIkC/EIwkqMeN/SWpBsF6x2gC1Tir7DYRc/+Zk= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -\&quot;]}&quot;}

  )
</code></pre><p>OK, we now have something worth pasting into the Lambda console and testing out!</p><p>![Screenshot of the AWS Lambda console showing a successful test
result](assets/2022-09-02-test2.png &quot;The sweet smell of victory!&quot; class=&quot;border&quot;)</p><div class="markdown-heading"><h2 id="what-does-it-all-mean?">What does it all mean?</h2><a href="#what-does-it-all-mean?" class="anchor" aria-label="Permalink: What does it all mean?"><img src="assets/link.svg" /></a></div><p>There&apos;s one final thing to do: actually parse the log lines. If we take a look at the <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/LogFormat.html">Amazon S3 server access log
format</a> documentation, we can see how we need to parse this thing. And for parsing strings, the obvious place to turn is a regular expression!</p><pre><code class="language-clojure">(comment

  (re-seq #&quot;^(\S+) (\S+) \[([^]]+)\] (\S+) (\S+) (\S+) (\S+) (\S+) \&quot;([^\&quot;]+)\&quot; (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) \&quot;([^\&quot;]+)\&quot; \&quot;([^\&quot;]+)\&quot; (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+).*$&quot;
          &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:30:23 +0000] 64.252.88.38 - DA5918VPJFK9A654 WEBSITE.GET.OBJECT blog/2022-06-21-todo-list.html \&quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1\&quot; 304 - - 5447 32 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;)
  ;; =&gt; ([&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:30:23 +0000] 64.252.88.38 - DA5918VPJFK9A654 WEBSITE.GET.OBJECT blog/2022-06-21-todo-list.html \&quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1\&quot; 304 - - 5447 32 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;
  ;;      &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188&quot;
  ;;      &quot;jmglov.net&quot;
  ;;      &quot;27/Jun/2022:23:30:23 +0000&quot;
  ;;      &quot;64.252.88.38&quot;
  ;;      &quot;-&quot;
  ;;      &quot;DA5918VPJFK9A654&quot;
  ;;      &quot;WEBSITE.GET.OBJECT&quot;
  ;;      &quot;blog/2022-06-21-todo-list.html&quot;
  ;;      &quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1&quot;
  ;;      &quot;304&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;5447&quot;
  ;;      &quot;32&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;Amazon CloudFront&quot;
  ;;      &quot;-&quot;
  ;;      &quot;ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI=&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;jmglov.net.s3-website-eu-west-1.amazonaws.com&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;])

  )
</code></pre><p>Amazing! But also not amazing. Regular expressions get a bad name for being cryptic and brittle, so let&apos;s see if we can use the power of Clojure to make this one accessible and resilient!</p><p>We can define a variable that holds both the name of the field and the pattern used to match it:</p><pre><code class="language-clojure">(ns s3-log-parser
  (:require [clojure.java.io :as io]
            [clojure.string :as str]
            [cheshire.core :as json]
            [com.grzm.awyeah.client.api :as aws])
  (:import (java.time Instant
                      LocalDate)))

(comment

  (def log-fields
    (-&gt;&gt; [:bucket-owner &quot;(\\S+)&quot;
          :bucket &quot;(\\S+)&quot;
          :time &quot;\\[([^]]+)\\]&quot;
          :remote-ip &quot;(\\S+)&quot;
          :requester &quot;(\\S+)&quot;
          :request-id &quot;(\\S+)&quot;
          :operation &quot;(\\S+)&quot;
          :key &quot;(\\S+)&quot;
          :request-uri &quot;\&quot;([^\&quot;]+)\&quot;&quot;
          :http-status &quot;(\\S+)&quot;
          :error-code &quot;(\\S+)&quot;
          :bytes-sent &quot;(\\S+)&quot;
          :object-size &quot;(\\S+)&quot;
          :total-time &quot;(\\S+)&quot;
          :turn-around-time &quot;(\\S+)&quot;
          :referer &quot;\&quot;([^\&quot;]+)\&quot;&quot;
          :user-agent &quot;\&quot;([^\&quot;]+)\&quot;&quot;
          :version-id &quot;(\\S+)&quot;
          :host-id &quot;(\\S+)&quot;
          :signature-version &quot;(\\S+)&quot;
          :cipher-suite &quot;(\\S+)&quot;
          :authentication-type &quot;(\\S+)&quot;
          :host-header &quot;(\\S+)&quot;
          :tls-version &quot;(\\S+)&quot;
          :access-point-arn &quot;(\\S+)&quot;]
         (partition-all 2)))
  ;; =&gt; #&lt;Var@4b3cc742:
  ;;      ((:bucket-owner &quot;(\\S+)&quot;)
  ;;       (:bucket &quot;(\\S+)&quot;)
  ;;       (:time &quot;\\[([^]]+)\\]&quot;)
  ;;       (:remote-ip &quot;(\\S+)&quot;)
  ;;       (:requester &quot;(\\S+)&quot;)
  ;;       (:request-id &quot;(\\S+)&quot;)
  ;;       (:operation &quot;(\\S+)&quot;)
  ;;       (:key &quot;(\\S+)&quot;)
  ;;       (:request-uri &quot;\&quot;([^\&quot;]+)\&quot;&quot;)
  ;;       (:http-status &quot;(\\S+)&quot;)
  ;;       (:error-code &quot;(\\S+)&quot;)
  ;;       (:bytes-sent &quot;(\\S+)&quot;)
  ;;       (:object-size &quot;(\\S+)&quot;)
  ;;       (:total-time &quot;(\\S+)&quot;)
  ;;       (:turn-around-time &quot;(\\S+)&quot;)
  ;;       (:referer &quot;\&quot;([^\&quot;]+)\&quot;&quot;)
  ;;       (:user-agent &quot;\&quot;([^\&quot;]+)\&quot;&quot;)
  ;;       (:version-id &quot;(\\S+)&quot;)
  ;;       (:host-id &quot;(\\S+)&quot;)
  ;;       (:signature-version &quot;(\\S+)&quot;)
  ;;       (:cipher-suite &quot;(\\S+)&quot;)
  ;;       (:authentication-type &quot;(\\S+)&quot;)
  ;;       (:host-header &quot;(\\S+)&quot;)
  ;;       (:tls-version &quot;(\\S+)&quot;)
  ;;       (:access-point-arn &quot;(\\S+)&quot;))&gt;

  )
</code></pre><p>Having done this, let&apos;s build the regex from the individual patterns:</p><pre><code class="language-clojure">(comment

  (def log-regex (-&gt;&gt; log-fields
                      (map second)
                      (str/join &quot; &quot;)
                      (format &quot;^%s(.*)$&quot;)
                      re-pattern))
  ;; =&gt; #&lt;Var@487539b9:
  ;;      #&quot;^(\S+) (\S+) \[([^]]+)\] (\S+) (\S+) (\S+) (\S+) (\S+) \&quot;([^\&quot;]+)\&quot; (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) \&quot;([^\&quot;]+)\&quot; \&quot;([^\&quot;]+)\&quot; (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)(.*)$&quot;&gt;

  (re-seq log-regex
          &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:30:23 +0000] 64.252.88.38 - DA5918VPJFK9A654 WEBSITE.GET.OBJECT blog/2022-06-21-todo-list.html \&quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1\&quot; 304 - - 5447 32 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;)
  ;; =&gt; ([&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:30:23 +0000] 64.252.88.38 - DA5918VPJFK9A654 WEBSITE.GET.OBJECT blog/2022-06-21-todo-list.html \&quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1\&quot; 304 - - 5447 32 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;
  ;;      &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188&quot;
  ;;      &quot;jmglov.net&quot;
  ;;      &quot;27/Jun/2022:23:30:23 +0000&quot;
  ;;      &quot;64.252.88.38&quot;
  ;;      &quot;-&quot;
  ;;      &quot;DA5918VPJFK9A654&quot;
  ;;      &quot;WEBSITE.GET.OBJECT&quot;
  ;;      &quot;blog/2022-06-21-todo-list.html&quot;
  ;;      &quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1&quot;
  ;;      &quot;304&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;5447&quot;
  ;;      &quot;32&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;Amazon CloudFront&quot;
  ;;      &quot;-&quot;
  ;;      &quot;ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI=&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;jmglov.net.s3-website-eu-west-1.amazonaws.com&quot;
  ;;      &quot;-&quot;
  ;;      &quot;-&quot;
  ;;      &quot;&quot;])

  )
</code></pre><p>Now we can grab the names of the fields and build a map by zipping them together with the matched groups from the regex:</p><pre><code class="language-clojure">(comment

  (def log-keys (map first log-fields))
  ;; =&gt; #&lt;Var@abab7a:
  ;;      (:bucket-owner
  ;;       :bucket
  ;;       :time
  ;;       :remote-ip
  ;;       :requester
  ;;       :request-id
  ;;       :operation
  ;;       :key
  ;;       :request-uri
  ;;       :http-status
  ;;       :error-code
  ;;       :bytes-sent
  ;;       :object-size
  ;;       :total-time
  ;;       :turn-around-time
  ;;       :referer
  ;;       :user-agent
  ;;       :version-id
  ;;       :host-id
  ;;       :signature-version
  ;;       :cipher-suite
  ;;       :authentication-type
  ;;       :host-header
  ;;       :tls-version
  ;;       :access-point-arn)&gt;

  (-&gt;&gt; &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:30:23 +0000] 64.252.88.38 - DA5918VPJFK9A654 WEBSITE.GET.OBJECT blog/2022-06-21-todo-list.html \&quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1\&quot; 304 - - 5447 32 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;
       (re-seq log-regex)
       first
       (drop 1)
       (zipmap log-keys))
  ;; =&gt; {:tls-version &quot;-&quot;,
  ;;     :request-uri &quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1&quot;,
  ;;     :access-point-arn &quot;-&quot;,
  ;;     :request-id &quot;DA5918VPJFK9A654&quot;,
  ;;     :referer &quot;-&quot;,
  ;;     :user-agent &quot;Amazon CloudFront&quot;,
  ;;     :remote-ip &quot;64.252.88.38&quot;,
  ;;     :key &quot;blog/2022-06-21-todo-list.html&quot;,
  ;;     :host-header &quot;jmglov.net.s3-website-eu-west-1.amazonaws.com&quot;,
  ;;     :version-id &quot;-&quot;,
  ;;     :time &quot;27/Jun/2022:23:30:23 +0000&quot;,
  ;;     :operation &quot;WEBSITE.GET.OBJECT&quot;,
  ;;     :object-size &quot;5447&quot;,
  ;;     :authentication-type &quot;-&quot;,
  ;;     :error-code &quot;-&quot;,
  ;;     :bytes-sent &quot;-&quot;,
  ;;     :requester &quot;-&quot;,
  ;;     :http-status &quot;304&quot;,
  ;;     :turn-around-time &quot;-&quot;,
  ;;     :signature-version &quot;-&quot;,
  ;;     :total-time &quot;32&quot;,
  ;;     :host-id
  ;;     &quot;ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI=&quot;,
  ;;     :cipher-suite &quot;-&quot;,
  ;;     :bucket &quot;jmglov.net&quot;,
  ;;     :bucket-owner
  ;;     &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188&quot;}

  )
</code></pre><p>There is one slight annoyance here, which is that we have all of these fields with values of &quot;-&quot;. According to the docs, a &quot;-&quot; means there&apos;s no value for that field, so let&apos;s replace this with <code>nil</code>, which is Clojure&apos;s way of saying &quot;no value here&quot;:</p><pre><code class="language-clojure">(comment

  (-&gt;&gt; &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188 jmglov.net [27/Jun/2022:23:30:23 +0000] 64.252.88.38 - DA5918VPJFK9A654 WEBSITE.GET.OBJECT blog/2022-06-21-todo-list.html \&quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1\&quot; 304 - - 5447 32 - \&quot;-\&quot; \&quot;Amazon CloudFront\&quot; - ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI= - - - jmglov.net.s3-website-eu-west-1.amazonaws.com - -&quot;
       (re-seq log-regex)
       first
       (drop 1)
       (map #(if (= &quot;-&quot; %) nil %))
       (zipmap log-keys))
  ;; =&gt; {:tls-version nil,
  ;;     :request-uri &quot;GET /blog/2022-06-21-todo-list.html HTTP/1.1&quot;,
  ;;     :access-point-arn nil,
  ;;     :request-id &quot;DA5918VPJFK9A654&quot;,
  ;;     :referer nil,
  ;;     :user-agent &quot;Amazon CloudFront&quot;,
  ;;     :remote-ip &quot;64.252.88.38&quot;,
  ;;     :key &quot;blog/2022-06-21-todo-list.html&quot;,
  ;;     :host-header &quot;jmglov.net.s3-website-eu-west-1.amazonaws.com&quot;,
  ;;     :version-id nil,
  ;;     :time &quot;27/Jun/2022:23:30:23 +0000&quot;,
  ;;     :operation &quot;WEBSITE.GET.OBJECT&quot;,
  ;;     :object-size &quot;5447&quot;,
  ;;     :authentication-type nil,
  ;;     :error-code nil,
  ;;     :bytes-sent nil,
  ;;     :requester nil,
  ;;     :http-status &quot;304&quot;,
  ;;     :turn-around-time nil,
  ;;     :signature-version nil,
  ;;     :total-time &quot;32&quot;,
  ;;     :host-id
  ;;     &quot;ukDRnMomesiUakfwW1nSFaoxoQQ/Nn14Dv+4helmPEcIkaIxEFfPojLviLC9vdbiER5zyB/ZOxI=&quot;,
  ;;     :cipher-suite nil,
  ;;     :bucket &quot;jmglov.net&quot;,
  ;;     :bucket-owner
  ;;     &quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188&quot;}

  )
</code></pre><p>Much nicer!</p><div class="markdown-heading"><h2 id="cleaning-up">Cleaning up</h2><a href="#cleaning-up" class="anchor" aria-label="Permalink: Cleaning up"><img src="assets/link.svg" /></a></div><p>OK, now that we&apos;ve written all of this parsing code, we need to put it somewhere, and our name namespace doesn&apos;t feel right. Let&apos;s create a new file to hold all of the parsing logic, <code>parser.clj</code>:</p><pre><code class="language-clojure">(ns parser
  (:require [clojure.string :as str]))

(def log-fields
  (-&gt;&gt; [:bucket-owner &quot;(\\S+)&quot;
        :bucket &quot;(\\S+)&quot;
        :time &quot;\\[([^]]+)\\]&quot;
        :remote-ip &quot;(\\S+)&quot;
        :requester &quot;(\\S+)&quot;
        :request-id &quot;(\\S+)&quot;
        :operation &quot;(\\S+)&quot;
        :key &quot;(\\S+)&quot;
        :request-uri &quot;\&quot;([^\&quot;]+)\&quot;&quot;
        :http-status &quot;(\\S+)&quot;
        :error-code &quot;(\\S+)&quot;
        :bytes-sent &quot;(\\S+)&quot;
        :object-size &quot;(\\S+)&quot;
        :total-time &quot;(\\S+)&quot;
        :turn-around-time &quot;(\\S+)&quot;
        :referer &quot;\&quot;([^\&quot;]+)\&quot;&quot;
        :user-agent &quot;\&quot;([^\&quot;]+)\&quot;&quot;
        :version-id &quot;(\\S+)&quot;
        :host-id &quot;(\\S+)&quot;
        :signature-version &quot;(\\S+)&quot;
        :cipher-suite &quot;(\\S+)&quot;
        :authentication-type &quot;(\\S+)&quot;
        :host-header &quot;(\\S+)&quot;
        :tls-version &quot;(\\S+)&quot;
        :access-point-arn &quot;(\\S+)&quot;]
       (partition-all 2)))

(def log-keys (map first log-fields))
(def log-regex (-&gt;&gt; log-fields
                    (map second)
                    (str/join &quot; &quot;)
                    (format &quot;^%s(.*)$&quot;)
                    re-pattern))

(defn parse-line [log-line]
  (-&gt;&gt; log-line
       (re-seq log-regex)
       first
       (drop 1)
       (map #(if (= &quot;-&quot; %) nil %))
       (zipmap log-keys)))
</code></pre><p>Now we can use this stuff in the handler, back in <code>s3_log_parser.clj</code>:</p><pre><code class="language-clojure">(ns s3-log-parser
  (:require [clojure.java.io :as io]
            [cheshire.core :as json]
            [com.grzm.awyeah.client.api :as aws]
            [parser])
  (:import (java.time Instant
                      LocalDate)))

(defn handler
  ([]
   (handler {} {}))
  ([event]
   (handler event {}))
  ([event _context]
   (log &quot;Invoked with event&quot; {:event event})
   (try
     (let [date (get-date (get-in event [&quot;queryStringParameters&quot; &quot;date&quot;]))
           logs (list-logs date)
           log-entries (-&gt;&gt; logs
                            (mapcat get-log-lines)
                            (map parser/parse-line))
           body {:date (str date), :logs logs, :entries log-entries}]
       (log &quot;Successfully parsed logs&quot; body)
       {&quot;statusCode&quot; 200
        &quot;body&quot; (json/encode body)})
     (catch Exception e
       (log (ex-message e) (ex-data e))
       {&quot;statusCode&quot; 400
        &quot;body&quot; (ex-message e)}))))

(comment

  (handler {})
  ;; =&gt; {&quot;statusCode&quot; 200,
  ;;     &quot;body&quot;
  ;;     &quot;{\&quot;date\&quot;:\&quot;2022-09-02\&quot;,\&quot;logs\&quot;:[\&quot;logs/2022-09-02-00-12-48-36034402F760D842\&quot;,\&quot;logs/2022-09-02-00-13-47-48D19FF5B34710F9\&quot;],\&quot;entries\&quot;:[{\&quot;request-uri\&quot;:\&quot;HEAD /blog/2022-08-26-doing-software-wrong.html HTTP/1.1\&quot;,\&quot;request-id\&quot;:\&quot;BC0KZGTDKR1QP07G\&quot;,\&quot;user-agent\&quot;:\&quot;Amazon CloudFront\&quot;,\&quot;remote-ip\&quot;:\&quot;64.252.89.133\&quot;,\&quot;key\&quot;:\&quot;blog/2022-08-26-doing-software-wrong.html\&quot;,\&quot;host-header\&quot;:\&quot;jmglov.net.s3-website-eu-west-1.amazonaws.com\&quot;,\&quot;time\&quot;:\&quot;31/Aug/2022:23:40:32 +0000\&quot;,\&quot;operation\&quot;:\&quot;WEBSITE.HEAD.OBJECT\&quot;,\&quot;object-size\&quot;:\&quot;7536\&quot;,\&quot;http-status\&quot;:\&quot;304\&quot;,\&quot;total-time\&quot;:\&quot;34\&quot;,\&quot;host-id\&quot;:\&quot;ApxkRhuJl/C73ZiR70xT6Stn2b1RkIcDPMnapeH5kWWQ+mT41qXfNeLaqpMc3j+5WCnrqoJH8N0=\&quot;,\&quot;bucket\&quot;:\&quot;jmglov.net\&quot;,\&quot;bucket-owner\&quot;:\&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188\&quot;},{\&quot;request-uri\&quot;:\&quot;GET / HTTP/1.1\&quot;,\&quot;request-id\&quot;:\&quot;M987YV3YB7DHBWA3\&quot;,\&quot;user-agent\&quot;:\&quot;Amazon CloudFront\&quot;,\&quot;remote-ip\&quot;:\&quot;64.252.73.234\&quot;,\&quot;key\&quot;:\&quot;index.html\&quot;,\&quot;host-header\&quot;:\&quot;jmglov.net.s3-website-eu-west-1.amazonaws.com\&quot;,\&quot;time\&quot;:\&quot;31/Aug/2022:23:14:14 +0000\&quot;,\&quot;operation\&quot;:\&quot;WEBSITE.GET.OBJECT\&quot;,\&quot;object-size\&quot;:\&quot;3459\&quot;,\&quot;http-status\&quot;:\&quot;304\&quot;,\&quot;total-time\&quot;:\&quot;18\&quot;,\&quot;host-id\&quot;:\&quot;14MYY/WyblbL1WgULsK86Cwwtn+tHCOgs+Y98xIkC/EIwkqMeN/SWpBsF6x2gC1Tir7DYRc/+Zk=\&quot;,\&quot;bucket\&quot;:\&quot;jmglov.net\&quot;,\&quot;bucket-owner\&quot;:\&quot;022d83ad6361dec3c93757e75c1c3a7982532ffdbf3bf87976490873591e2188\&quot;}]}&quot;}

  )
</code></pre><p>Now that everything looks good, we can go back to the Lambda console and try it out. We&apos;ll need to add our <code>parser.clj</code> file to the code, which we can do by using the <strong>File &gt; New File</strong> menu option in the <strong>Code source</strong> section of the console, pasting in the contents of <code>parser.clj</code>, and then doing <strong>File &gt; Save As...</strong> and entering &quot;parser.clj&quot; as the filename. We now need to paste the contents of <code>s3_log_parser.clj</code> into that file in the console, then press the <strong>Deploy</strong> button to put the new code out into the world.</p><p>Finally, we can take a deep breath, position the mouse cursor over the <strong>Test</strong> button, close our eyes, and click... victory!</p><p><img alt="Screenshot of the AWS Lambda console showing a test result with parsed
lines" src="assets/2022-09-02-parsed.png" title="Now what to do with this stuff?" /></p><p>Of course, this is a really clunky and error prone way to deploy code. In the next instalment of Dogfooding Blambda, we&apos;ll build a production grade deployment framework.</p><p>But for now, let&apos;s rest on our laurels so I can go eat some lunch. 😉</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-08-17-hacking-blog-sharing.html</id>
    <link href="https://jmglov.net/blog/2022-08-17-hacking-blog-sharing.html"/>
    <title>Hacking the blog: social sharing</title>
    <updated>2022-08-17T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>It appears that it has been one month and one day since <a href="2022-07-15-hacking-blog-actually-caching.html">I last hacked the
blog</a>. Hard to believe! It&apos;s easier to believe that it&apos;s been <s>five</s> six days (I started this post yesterday but didn&apos;t finish it until today 😬) since <a href="2022-08-11-dogfooding-blambda-cli-ier.html">I last
blogged</a>. I went camping over the weekend, and still haven&apos;t finished putting my gear away! 😅</p><p>![A desk with a computer and a lot of camping gear spread all over it][desk]</p><p>As much fun as I&apos;ve been having with the actual blogging, I must say I&apos;ve been having less fun sharing blog posts on Twitter, since when I do, the only thing I see is a boring old URL.</p><p>![A tweet with a link to one of my blog posts which is just a URL][boring]</p><p>By contrast, when I share an excellent post about an excellent Arsenal performance by an excellent blogger, I see an excellent preview thingy with a picture and a title and a summary and I&apos;m now super engaged and want to click!</p><p>![A tweet with a link to a 7amkickoff blog post with a nice image and a summary][awesome]</p><p>I want nice things too!</p><p>But luckily, since I&apos;m the owner / operator of my blog, I can just make nice things for myself and then have those nice things (but not eat them, because apparently you can&apos;t have a thing and eat it too, because then you won&apos;t have it anymore).</p><p>The first order of business is figuring out what to search for. I tried &quot;website thumbnail image&quot; and found a great article by Michelle Mannering: &quot;<a href="https://dev.to/mishmanners/how-to-add-a-social-media-share-card-to-any-website-ha8">How to add a
social media share card to any
website</a>&quot;. OK, so let&apos;s call this thingy a &quot;share card&quot; from now on.</p><p>According to Michelle, these are the tags that control the share card:</p><pre><code class="language-html">    &lt;!-- Primary Meta Tags --&gt; &lt;!-- this is the default metadata which all websites can draw on --&gt; 
    &lt;title&gt;YOUR_WEBSITE&lt;/title&gt;
    &lt;meta name=&quot;title&quot; content=&quot;YOUR_HEADING&quot;&gt;
    &lt;meta name=&quot;description&quot; content=&quot;YOUR_SUMMARY&quot;&gt;

    &lt;!-- Open Graph / Facebook --&gt; &lt;!-- this is what Facebook and other social websites will draw on --&gt;
    &lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;
    &lt;meta property=&quot;og:url&quot; content=&quot;YOUR_URL&quot;&gt;
    &lt;meta property=&quot;og:title&quot; content=&quot;YOUR_HEADING&quot;&gt;
    &lt;meta property=&quot;og:description&quot; content=&quot;YOUR_SUMMARY&quot;&gt;
    &lt;meta property=&quot;og:image&quot; content=&quot;YOUR_IMAGE_URL&quot;&gt;

    &lt;!-- Twitter --&gt; &lt;!-- You can have different summary for Twitter! --&gt;
    &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot;&gt;
    &lt;meta name=&quot;twitter:url&quot; content=&quot;YOUR_URL&quot;&gt;
    &lt;meta name=&quot;twitter:title&quot; content=&quot;YOUR_HEADING&quot;&gt;
    &lt;meta name=&quot;twitter:description&quot; content=&quot;YOUR_SUMMARY&quot;&gt;
    &lt;meta name=&quot;twitter:image&quot; content=&quot;YOUR_IMAGE_URL&quot;&gt;
</code></pre><p>(The article actually says <code>&lt;meta property=&quot;twitter:...&quot;&gt;</code>, but according to Twitter&apos;s <a href="https://developer.twitter.com/en/docs/twitter-for-websites/cards/guides/getting-started">Cards
documentation</a>, it should be <code>&lt;meta name=&quot;twitter:...&quot;&gt;</code>, so I&apos;ll use that instead.)</p><p>If I slap these tags into the <code>&lt;head&gt;</code> of my document, I should win!</p><p>But what to put in the content of these tags? Let&apos;s take them one by one, using the 7amkickoff sharing card as a reference:</p><ul><li><code>YOUR_HEADING</code>: &quot;Summer days&quot;. This looks like the page title.</li><li><code>YOUR_URL</code>: ???. I guess this is the page URL.</li><li><code>YOUR_SUMMARY</code>: &quot;Summer days are meant to be spent doing something quiet in the early morning, followed by...&quot;. OK, this is a preview of the post&apos;s content.</li><li><code>YOUR_IMAGE_URL</code>: logo with the &quot;7&quot;. The thumbnail image (called a &quot;featured image&quot; by Wordpress and Medium, IIRC).</li></ul><p>Now we can go page by page, filling these in as we go.</p><ol start="1"><li>Index page:<ul><li><code>YOUR_HEADING</code>: page title (<a href="https://github.com/borkdude/quickblog">quickblog</a>&apos;s <code>:blog-title</code> key)</li><li><code>YOUR_URL</code>: page URL (quickblog: <code>:blog-root</code> + &quot;index.html&quot;)</li><li><code>YOUR_SUMMARY</code>: let&apos;s use a description of the blog here (quickblog: <code>:blog-description</code>)</li><li><code>YOUR_IMAGE_URL</code>: we can put a blog logo here (let&apos;s add a new <code>:blog-image</code> key to quickblog)</li></ul></li><li>Archive page:<ul><li><code>YOUR_HEADING</code>: page title (quickblog: <code>:blog-title</code> + &quot; - Archive&quot;)</li><li><code>YOUR_URL</code>: page URL (quickblog: <code>:blog-root</code> + &quot;archive.html&quot;)</li><li><code>YOUR_SUMMARY</code>: (quickblog: &quot;Archive - &quot; + <code>:blog-description</code>)</li><li><code>YOUR_IMAGE_URL</code>: (quickblog: <code>:blog-image</code>)</li></ul></li><li>Tags page (i.e. the page listing all of the tags):<ul><li><code>YOUR_HEADING</code>: page title (quickblog: <code>:blog-title</code> + &quot; - Tags&quot;)</li><li><code>YOUR_URL</code>: page URL (quickblog: <code>:blog-root</code> + &quot;tags/index.html&quot;)</li><li><code>YOUR_SUMMARY</code>: (quickblog: &quot;Tags - &quot; + <code>:blog-description</code>)</li><li><code>YOUR_IMAGE_URL</code>: (quickblog: <code>:blog-image</code>)</li></ul></li><li>Tag pages (i.e. pages for individual tags with links to the posts with that tag):<ul><li><code>YOUR_HEADING</code>: page title (quickblog: <code>:blog-title</code> + &quot; - Tag - &quot; + tag name)</li><li><code>YOUR_URL</code>: page URL (quickblog: <code>:blog-root</code> + &quot;tags/{{tag}}.html&quot;)</li><li><code>YOUR_SUMMARY</code>: (quickblog: &quot;Posts tagged &apos;{{tag}}&apos; - &quot; + <code>:blog-description</code>)</li><li><code>YOUR_IMAGE_URL</code>: (quickblog: <code>:blog-image</code>)</li></ul></li><li>Posts:<ul><li><code>YOUR_HEADING</code>: page title, which is the value of the post&apos;s <code>title</code> metadata (specified in Markdown as <code>Title: Something or other</code>, as detailed in the <a href="2022-07-14-hacking-blog-repl.html">very first Hacking the blog
     post</a>)</li><li><code>YOUR_URL</code>: page URL (quickblog: <code>:blog-root</code> + &quot;{{file}}.html&quot;; assuming the post&apos;s Markdown file is called <code>something.md</code>, <code>file</code> will be &quot;something&quot;)</li><li><code>YOUR_SUMMARY</code>: let&apos;s add a new piece of metadata to the Markdown file called <code>Description:</code> (I know the article I referenced is calling it <code>YOUR_SUMMARY</code>, but I figure it&apos;s less surprising for this to match the name of the meta tags where we&apos;ll put it)</li><li><code>YOUR_IMAGE_URL</code>: let&apos;s add an <code>Image:</code> metadata for this</li></ul></li></ol><p>Having figured out what to put in the meta tags, let&apos;s actually implement this! The nice thing about my blog being powered by quickblog is that all of the changes happen there (and are thus available to all quickblog users). Let&apos;s start by cloning quickblog. I&apos;ll open a terminal, change to the parent directory of my blog, and then run:</p><pre><code class="language-text">$ git clone git@github.com:borkdude/quickblog.git
</code></pre><p>Now I have a <code>quickblog</code> directory as a sibling of the <code>jmglov.net</code> directory that contains my blog. In order for my blog to pick up the local changes I&apos;m about to make to quickblog, I need to change my dependency from using quickblog from Github to use the local copy instead.</p><p>My <code>bb.edn</code> currently looks like this:</p><pre><code class="language-clojure">{:deps {io.github.borkdude/quickblog
        #_&quot;You use the newest SHA here:&quot;
        {:git/sha &quot;1c26f244003e590863ae6bba0b25b2ba6a258ac9&quot;}}
 ;; ...
 }
</code></pre><p>I&apos;ll change it to this:</p><pre><code class="language-clojure">{:deps {io.github.borkdude/quickblog {:local/root &quot;../quickblog&quot;}
        #_&quot;You use the newest SHA here:&quot;
        #_{:git/sha &quot;1c26f244003e590863ae6bba0b25b2ba6a258ac9&quot;}}
 ;; ...
 }
</code></pre><p>I left the <code>{:git/sha &quot;1c26f244003e590863ae6bba0b25b2ba6a258ac9&quot;}</code> bit there for reference, but commented it out with the <code>#_</code> <a href="https://clojure.org/reference/reader#_dispatch">reader
macro</a>, which causes Clojure&apos;s reader to ignore the next form. You can think of it as more or less the <code>/* ... */</code> style comment in languages like Java and C.</p><p>Now, any changes I make to my local quickblog directory will be reflected in my blog when I run <code>bb render</code>.</p><p>Now that we&apos;re all set up, let&apos;s take a look at the quickblog source code and figure out how we&apos;re going to do this. The place to start is the page template, <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/resources/quickblog/templates/base.html"><code>base.html</code></a>. If we open it up and take a look at the <code>&lt;head&gt;</code> section, here&apos;s what we see:</p><pre><code class="language-html">  &lt;head&gt;
    &lt;title&gt;{{title}}&lt;/title&gt;
    &lt;meta charset=&quot;utf-8&quot;/&gt;
    &lt;link type=&quot;application/atom+xml&quot; rel=&quot;alternate&quot; href=&quot;{{relative-path | safe}}atom.xml&quot; title=&quot;{{title}}&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;{{relative-path | safe}}style.css&quot;&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/components/prism-clojure.min.js&quot;&gt;&lt;/script&gt;
    {{watch | safe }}
    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/themes/prism.min.css&quot;&gt;

{% if favicon-tags %}{{favicon-tags | safe}}{% endif %}
  &lt;/head&gt;
</code></pre><p>The <code>{% ... %}</code> and <code>{{...}}</code> stuff are <a href="https://github.com/yogthos/Selmer">Selmer</a> tags and variables. The <code>{% if ... %}</code> tag includes the stuff before the <code>{% endif %}</code> if the condition is true, and the <code>{{foo}}</code> is substituted with the value of the <code>foo</code> template variable, or the empty string if the <code>foo</code> template variable is undefined or <code>nil</code>.</p><p>Let&apos;s add our social sharing tags below the <code>&lt;% if favicon-tags %&gt;</code> line (which you may remember from the &quot;<a href="2022-07-05-hacking-blog-favicon.html">Hacking the blog:
favicon</a>&quot; post). Since all pages have a title, we can include those tags unconditionally:</p><pre><code class="language-html">    &lt;!-- Social sharing (Facebook, Twitter, LinkedIn, etc.) --&gt;
    &lt;meta name=&quot;title&quot; content=&quot;{{title}}&quot;&gt;
    &lt;meta name=&quot;twitter:title&quot; content=&quot;{{title}}&quot;&gt;
    &lt;meta property=&quot;og:title&quot; content=&quot;{{title}}&quot;&gt;
</code></pre><p>We can also throw in <code>og:type</code>, since that should always be &quot;website&quot; for our purposes:</p><pre><code class="language-html">    &lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;
</code></pre><p>Since the template is already using <code>{{title}}</code>, we feel confident that the quickblog rendering code is providing it. Let&apos;s move on now to the description (<code>YOUR_SUMMARY</code>, I know, it&apos;s confusing; sorry). Let&apos;s add the tags to the template:</p><pre><code class="language-html">{% if sharing.description %}
    &lt;meta name=&quot;description&quot; content=&quot;{{sharing.description}}&quot;&gt;
    &lt;meta name=&quot;twitter:description&quot; content=&quot;{{sharing.description}}&quot;&gt;
    &lt;meta property=&quot;og:description&quot; content=&quot;{{sharing.description}}&quot;&gt;
{% endif %}
</code></pre><p>This is something new. When we include a <code>.</code> in a template variable, what we&apos;re saying is the bit before the dot is a map which contains a field named the bit after the dot. In this case, we expect a template variable called <code>sharing</code> to be provided like this:</p><pre><code class="language-clojure">:sharing {:description &quot;something&quot;}
</code></pre><p>We&apos;ll wrap this whole thing in an <code>{% if %} ... {% endif %}</code> so that nothing will be added to the template if the <code>sharing.description</code> variable is undefined.</p><p>Let&apos;s have faith that future us will find a way to provide the <code>sharing.description</code> variable somehow and forge on with our template. Next up is the URL:</p><pre><code class="language-html">{% if sharing.url %}
    &lt;meta name=&quot;twitter:url&quot; content=&quot;{{sharing.url}}&quot;&gt;
    &lt;meta property=&quot;og:url&quot; content=&quot;{{sharing.url}}&quot;&gt;
{% endif %}
</code></pre><p>Again, we&apos;ll have faith in our future selves, competent programmers that we are! The final piece of the puzzle is the image. We&apos;ll follow the same pattern, but with one small tweak:</p><pre><code class="language-html">{% if sharing.image %}
    &lt;meta name=&quot;twitter:image&quot; content=&quot;{{sharing.image}}&quot;&gt;
    &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot;&gt;
    &lt;meta property=&quot;og:image&quot; content=&quot;{{sharing.image}}&quot;&gt;
    &lt;meta property=&quot;og:image:alt&quot; content=&quot;{{sharing.image-alt}}&quot;&gt;
{% else %}
    &lt;meta name=&quot;twitter:card&quot; content=&quot;summary&quot;&gt;
{% endif %}
</code></pre><p>The <code>og:image:alt</code> property is one that I tracked down in the <a href="https://ogp.me/">Open Graph
protocol documentation</a>, and it provides alt text for the image, which is extremely important for making pages accessible to people using screen readers. I highly recommend reading resources like &quot;<a href="https://accessibility.huit.harvard.edu/describe-content-images">Write good Alt Text
to describe
images</a>&quot; to learn more.</p><p>The <code>twitter:card</code> property has multiple options, according to Twitter&apos;s cards documentation:</p><ul><li><code>summary</code></li><li><code>summary_large_image</code></li><li><code>app</code></li><li><code>player</code></li></ul><p>It does not specify what these mean. I guess Twitter needs to keep the mystery alive! What we&apos;ll do for now is use <code>summary_large_image</code> when we have an image, and regular old &quot;summary&quot; when we don&apos;t.</p><p>According to this page, Twitter has another couple of meta tags we can set:</p><ul><li><code>twitter:site</code> - @username for the website used in the card footer</li><li><code>twitter:creator</code> - @username for the content creator / author</li></ul><p>We might as well do that, since quickblog has a <code>:twitter-handle</code> option.</p><pre><code class="language-html">{% if sharing.author %}
    &lt;meta name=&quot;twitter:creator&quot; content=&quot;{{sharing.author-twitter-handle}}&quot;&gt;
{% endif %}
{% if sharing.twitter-handle %}
    &lt;meta name=&quot;twitter:site&quot; content=&quot;{{sharing.twitter-handle}}&quot;&gt;
{% endif %}
</code></pre><p>The reason for defining them separately is that <code>:twitter-handle</code> is the owner of the blog, but the author of an individual post might be different, and we&apos;ll allow that to be specified with the <code>Twitter-Handle:</code> metadata tag in the post.</p><p>OK, now we have everything taken care of in the template itself. Let&apos;s turn our roving eye to the rendering code, starting with the index.</p><p>If we open up <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/api.clj"><code>src/quickblog/api.clj</code></a>, we&apos;ll find a <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/api.clj#L157"><code>spit-index</code></a> function at line 157. It does some figuring out of which posts to include in the index, then makes a call to <code>lib/write-page!</code>. This is where the template variables are defined:</p><pre><code class="language-clojure">{:title blog-title
 :body body}
</code></pre><p>Looking back at our template, we want to add the following keys and values:</p><ul><li><code>description</code></li><li><code>url</code></li><li><code>image</code></li><li><code>author-twitter-handle</code></li><li><code>twitter-handle</code></li></ul><p>All of the information we need is contained in the <code>opts</code> that are passed to the function. Let&apos;s add the keys we need to the <a href="https://clojure.org/guides/destructuring#_associative_destructuring">destructuring
form</a>:</p><pre><code class="language-clojure">(defn- spit-index
  [{:keys [blog-title blog-description blog-image blog-image-alt
           blog-root twitter-handle
           posts cached-posts deleted-posts modified-posts num-index-posts
           out-dir]
    :as opts}]
</code></pre><p>Now we can fill in the map of template variables:</p><pre><code class="language-clojure">(lib/write-page! opts out-file
                 (base-html opts)
                 {:title blog-title
                  :body body
                  :sharing {:description blog-description
                            :author twitter-handle
                            :twitter-handle twitter-handle
                            :image (format &quot;%s/%s&quot; blog-root blog-image)
                            :image-alt blog-image-alt
                            :url (format &quot;%s/index.html&quot; blog-root)}})
</code></pre><p>In this case, both the author and site Twitter handles are the same, since this is the index page of the entire blog.</p><p>There&apos;s only one thing here that is slightly worrisome: does the value of the <code>:blog-root</code> option end in a <code>/</code> or not? quickblog&apos;s documentation is silent on the matter, so we&apos;d better handle both cases just to be safe. Let&apos;s add a function to <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/internal.clj"><code>internal.clj</code></a> to take care of this:</p><pre><code class="language-clojure">(defn blog-link [{:keys [blog-root] :as opts} relative-url]
  (when relative-url
    (format &quot;%s%s%s&quot;
            blog-root
            (if (str/ends-with? blog-root &quot;/&quot;) &quot;&quot; &quot;/&quot;)
            relative-url)))
</code></pre><p>And now we can use this in <code>spit-index</code>:</p><pre><code class="language-clojure">(defn- spit-index
  [{:keys [blog-title blog-description blog-image blog-image-alt twitter-handle
           posts cached-posts deleted-posts modified-posts num-index-posts
           out-dir]
    :as opts}]
  ;; ...
        (lib/write-page! opts out-file
                         (base-html opts)
                         {:title blog-title
                          :body body
                          :sharing {:description blog-description
                                    :author twitter-handle
                                    :twitter-handle twitter-handle
                                    :image (lib/blog-link opts blog-image)
                                    :image-alt blog-image-alt
                                    :url (lib/blog-link opts &quot;index.html&quot;)}})))))
</code></pre><p>Note that we no longer need the <code>blog-root</code> key in our destructuring form, so we&apos;ve removed it to be neat and tidy.</p><p>Now onto the archive page. We see that there&apos;s a <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/api.clj#L181"><code>spit-archive</code></a> function on line 181, so we&apos;ll do some very similar modifications there:</p><pre><code class="language-clojure">(defn- spit-archive [{:keys [blog-title blog-description
                             blog-image blog-image-alt twitter-handle
                             modified-metadata posts out-dir] :as opts}]
  ;; ...
        (lib/write-page! opts out-file
                         (base-html opts)
                         {:skip-archive true
                          :title title
                          :body (hiccup/html (lib/post-links &quot;Archive&quot; posts))
                          :sharing {:description (format &quot;Archive - %s&quot;
                                                         blog-description)
                                    :author twitter-handle
                                    :twitter-handle twitter-handle
                                    :image (lib/blog-link opts blog-image)
                                    :image-alt blog-image-alt
                                    :url (lib/blog-link opts &quot;archive.html&quot;)}})))))
</code></pre><p>The tags page is now up, but there&apos;s no conveniently named <code>spit-tags</code> function, so we&apos;ll have to figure out how this is generated. If we just search <code>api.clj</code> for <code>tags</code>, we get a promising hit on <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/api.clj#L120">line
120</a>:</p><pre><code class="language-clojure">(defn- gen-tags [{:keys [blog-title modified-tags posts
                         out-dir tags-dir]
                  :as opts}]
  ;; ...
      (lib/write-page! opts tags-file template
                       {:skip-archive true
                        :title (str blog-title &quot; - Tags&quot;)
                        :relative-path &quot;../&quot;
                        :body (hiccup/html (lib/tag-links &quot;Tags&quot; posts-by-tag))})
      ;; ...
</code></pre><p>Ah, our old friend <code>lib/write-page!</code>. Let&apos;s rinse and repeat here:</p><pre><code class="language-clojure">(defn- gen-tags [{:keys [blog-title blog-description
                         blog-image blog-image-alt twitter-handle
                         modified-tags posts out-dir tags-dir]
                  :as opts}]
  ;; ...
      (lib/write-page! opts tags-file template
                       {:skip-archive true
                        :title (str blog-title &quot; - Tags&quot;)
                        :relative-path &quot;../&quot;
                        :body (hiccup/html (lib/tag-links &quot;Tags&quot; posts-by-tag))
                        :sharing {:description (format &quot;Tags - %s&quot;
                                                       blog-description)
                                  :author twitter-handle
                                  :twitter-handle twitter-handle
                                  :image (lib/blog-link opts blog-image)
                                  :image-alt blog-image-alt
                                  :url (lib/blog-link opts &quot;tags/index.html&quot;)}})
      ;; ...
</code></pre><p><code>gen-tags</code> looks like it also handles the individual tag pages:</p><pre><code class="language-clojure">(doseq [tag-and-posts posts-by-tag]
  (lib/write-tag! opts tags-out-dir template tag-and-posts))
</code></pre><p>Let&apos;s drill into the <code>lib/write-tag!</code> function, defined on <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/internal.clj#L383">line
383</a> of <code>internal.clj</code>:</p><pre><code class="language-clojure">(defn write-tag! [{:keys [blog-title modified-tags] :as opts}
                  tags-out-dir
                  template
                  [tag posts]]
  (let [tag-filename (fs/file tags-out-dir (tag-file tag))]
    (when (or (modified-tags tag) (not (fs/exists? tag-filename)))
      (write-page! opts tag-filename template
                   {:skip-archive true
                    :title (str blog-title &quot; - Tag - &quot; tag)
                    :relative-path &quot;../&quot;
                    :body (hiccup/html (post-links (str &quot;Tag - &quot; tag) posts
                                                   {:relative-path &quot;../&quot;}))}))))
</code></pre><p>Nice! There&apos;s a call to <code>write-page!</code>, so we know exactly what we need to do:</p><pre><code class="language-clojure">(defn write-tag! [{:keys [blog-title blog-description
                          blog-image blog-image-alt twitter-handle
                          modified-tags] :as opts}
                  tags-out-dir
                  template
                  [tag posts]]
  ;; ...
      (write-page! opts tag-filename template
                   {:skip-archive true
                    :title (str blog-title &quot; - Tag - &quot; tag)
                    :relative-path &quot;../&quot;
                    :body (hiccup/html (post-links (str &quot;Tag - &quot; tag) posts
                                                   {:relative-path &quot;../&quot;}))
                    :sharing {:description (format &quot;Posts tagged \&quot;%s\&quot; - %s&quot;
                                                   tag blog-description)
                              :author twitter-handle
                              :twitter-handle twitter-handle
                              :image (blog-link opts blog-image)
                              :image-alt blog-image-alt
                              :url (blog-link opts &quot;tags/index.html&quot;)}}))
</code></pre><p>There&apos;s only one thing left to do: the post pages. Let&apos;s see if we can figure out how they&apos;re rendered.</p><p>Back in <code>api.clj</code>, there&apos;s a <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/api.clj#L89"><code>gen-posts</code></a> function at line 89. It&apos;s a bit long and scary looking, but there is a call to a <code>lib/write-post!</code> function at <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/api.clj#L102">line
102</a>, so it looks like we can probably get away with leaving <code>gen-posts</code> as is and making our changes in <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/internal.clj#L353"><code>lib/write-post!</code></a>. Let&apos;s have a look:</p><pre><code class="language-clojure">(defn write-post! [{:keys [discuss-fallback
                           cache-dir
                           out-dir
                           force-render
                           page-template
                           post-template
                           posts-dir]
                    :as opts}
                   {:keys [file title date discuss tags html]
                    :or {discuss discuss-fallback}}]
  (let [out-file (fs/file out-dir (html-file file))
        markdown-file (fs/file posts-dir file)
        cached-file (fs/file cache-dir (cache-file file))
        body (selmer/render post-template {:body @html
                                           :title title
                                           :date date
                                           :discuss discuss
                                           :tags tags})
        rendered-html (render-page opts page-template
                                   {:title title
                                    :body body})]
    (println &quot;Writing post:&quot; (str out-file))
    (spit out-file rendered-html)))
</code></pre><p>There are a few things to note here:</p><ol start="1"><li>There are two <code>:keys</code> destructurings happening here. The first is our old friend <code>opts</code>, but the second has no name. The names of the keys look familiar, though. <code>Title:</code>, <code>Date:</code>, and <code>Tags:</code> are the pieces of metadata automatically added to new posts when we run the <code>bb new</code> command, so let&apos;s assume that this second set of keys is the metadata defined in the post itself, plus some extra metadata that quickblog attaches.</li><li>There&apos;s a call to <code>selmer/render</code> here, which appears to be rendering the body of the post. Since the <code>&lt;meta&gt;</code> tags we&apos;re adding go in the <code>&lt;head&gt;</code> section of the page, we can safely ignore this part.</li><li>There&apos;s no call to <code>write-page!</code>, but <code>render-page</code> looks pretty similar. Let&apos;s add our template variables there.</li></ol><p>First, we&apos;ll add <code>twitter-handle</code> to the <code>opts</code> destructuring, give the second argument a name, <code>post-metadata</code>, and add the <code>description</code>, <code>image</code>, and <code>image-alt</code> keys to it:</p><pre><code class="language-clojure">(defn write-post! [{:keys [blog-root
                           twitter-handle
                           discuss-fallback
                           cache-dir
                           out-dir
                           force-render
                           page-template
                           post-template
                           posts-dir]
                    :as opts}
                   {:keys [file title date discuss tags html
                           description image image-alt]
                    :or {discuss discuss-fallback}
                    :as post-metadata}]
  ;; ...
</code></pre><p>Now, let&apos;s figure out what the values of the template variables should be. <code>description</code> and <code>image-alt</code> are straightforward; it&apos;s what the post author added as the <code>Description:</code> and <code>Image-Alt:</code> metadata in the post, so we can use it as is.</p><p><code>url</code> is only a bit more complicated. We can use the <code>blog-link</code> function as usual, and the <code>relative-url</code> argument should be the name of the HTML file corresponding to this post. We can see on <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/internal.clj#L363">line
363</a> that the output file uses a function called <code>html-file</code>, which transforms the post&apos;s <code>foo.md</code> file into <code>foo.html</code>. Just what we needed!</p><p><code>twitter-handle</code>, which is the Twitter handle of the blog owner, can be used straight up. For <code>author</code>, let&apos;s look first for a <code>twitter-handle</code> key in the post metadata, and then fall back to the blog&apos;s <code>twitter-handle</code> otherwise:</p><pre><code class="language-clojure">author (-&gt; (:twitter-handle post-metadata) (or twitter-handle))
</code></pre><p>Finally, we want the post&apos;s author to be able to add <code>Image:</code> metadata to the post, which they should be able to specify either as an absolute URL or a relative URL. We can handle that here:</p><pre><code class="language-clojure">image (when image (if (re-matches #&quot;^https?://.+&quot; image)
                    image
                    (blog-link opts image)))
</code></pre><p>Now we can just feed these keys to the <code>render-page</code> function:</p><pre><code class="language-clojure">rendered-html (render-page opts page-template
                           {:title title
                            :body body
                            :sharing (-&gt;map description
                                            author
                                            twitter-handle
                                            image
                                            image-alt
                                            url)})
</code></pre><p>Let&apos;s take a brief detour to look at this <code>-&gt;map</code> bit. It&apos;s a macro that lets us define a map with keys named the same as the variables holding the values. Or in other words, these two things are equivalent:</p><pre><code>(-&gt;map description author twitter-handle image image-alt url)

{:description description
 :author author
 :twitter-handle twitter-handle
 :image image
 :image-alt image-alt
 :url url}
</code></pre><p>In case you&apos;re interested, the macro is defined at <a href="https://github.com/borkdude/quickblog/blob/1c26f244003e590863ae6bba0b25b2ba6a258ac9/src/quickblog/internal.clj#L27">line
27</a>:</p><pre><code class="language-clojure">(defmacro -&gt;map [&amp; ks]
  (assert (every? symbol? ks))
  (zipmap (map keyword ks)
          ks))
</code></pre><p>If you&apos;re interested but don&apos;t understand what&apos;s going on here, I can highly recommend &quot;<a href="https://pragprog.com/titles/cjclojure/mastering-clojure-macros/">Mastering Clojure
Macros</a>&quot;, by Colin Jones, or <a href="https://www.braveclojure.com/writing-macros/">Chapter 8</a> of &quot;<a href="https://www.braveclojure.com/">Clojure for the Brave and True</a>&quot;, by Daniel Higgenbotham. You can read &quot;Clojure for the Brave and True&quot; for free online, but if you can afford to show Daniel some monetary appreciation, you can order the print version using his affiliate link: <a href="http://amzn.to/1H7MqmT">http://amzn.to/1H7MqmT</a>.</p><p>OK, we actually have everything we need to make this work! Let&apos;s generate a new post and test it out:</p><pre><code class="language-text">$ bb new --file test.md --title &quot;Test post&quot;
</code></pre><p>If we open up <code>posts/test.md</code>, we can add some metadata tags:</p><pre><code class="language-text">Title: Test post
Date: 2022-08-17
Tags: clojure
Twitter-Handle: jmglov
Description: This is an amazing blog post which tests the equally amazing social sharing functionality that we just added to quickblog!
Image: https://jmglov.net/test/2022-08-16-sharing-preview.png
Image-Alt: A leather-bound notebook lies open on a writing desk

Write a blog post here!
</code></pre><p>Now let&apos;s try things out! If we run:</p><pre><code class="language-text">$ bb watch
</code></pre><p>we can browse to our blog at <a href="http://localhost:1888/">http://localhost:1888/</a>. We should see the index page, and if we click on the <a href="http://localhost:1888/test.html">Test post</a> link, we can view the source of the page, look at the <code>&lt;head&gt;</code> section, and see:</p><pre><code class="language-html">&lt;head&gt;
  &lt;!-- some boring stuff here --&gt;

  &lt;!-- Social sharing (Facebook, Twitter, LinkedIn, etc.) --&gt;
  &lt;meta name=&quot;title&quot; content=&quot;Test post&quot;&gt;
  &lt;meta name=&quot;twitter:title&quot; content=&quot;Test post&quot;&gt;
  &lt;meta property=&quot;og:title&quot; content=&quot;Test post&quot;&gt;
  &lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;

  &lt;meta name=&quot;description&quot; content=&quot;This is an amazing blog post which tests the equally amazing social sharing functionality that we just added to quickblog!&quot;&gt;
  &lt;meta name=&quot;twitter:description&quot; content=&quot;This is an amazing blog post which tests the equally amazing social sharing functionality that we just added to quickblog!&quot;&gt;
  &lt;meta property=&quot;og:description&quot; content=&quot;This is an amazing blog post which tests the equally amazing social sharing functionality that we just added to quickblog!&quot;&gt;

  &lt;meta name=&quot;twitter:image&quot; content=&quot;https://jmglov.net/test/2022-08-16-sharing-preview.png&quot;&gt;
  &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot;&gt;
  &lt;meta property=&quot;og:image&quot; content=&quot;https://jmglov.net/test/2022-08-16-sharing-preview.png&quot;&gt;
  &lt;meta property=&quot;og:image:alt&quot; content=&quot;A leather-bound notebook lies open on a writing desk&quot;&gt;

  &lt;meta name=&quot;twitter:creator&quot; content=&quot;jmglov&quot;&gt;
  &lt;meta name=&quot;twitter:site&quot; content=&quot;quickblog&quot;&gt;
&lt;/head&gt;
</code></pre><p>Awesome! But how can we know what this will look like when shared on social media sites? Well, I&apos;ve done us all the great service of uploading this page to my website, so we can use <a href="https://metatags.io/">metatags.io</a> to test it. If we pop in <a href="https://jmglov.net/test/social-post.html">https://jmglov.net/test/social-post.html</a> to the text box at the top of the site, we should see something like this:</p><p>![The metatags.io site showing a preview of the social sharing card for our test page][metatags]</p><p>The spectacularity of this accomplishment cannot be overstated, my friends! 🏆</p><p>In case you&apos;re a quickblog user and you want to benefit from this stuff without having to do a bunch of typing, fear not! The latest version of quickblog already includes this functionality. 🙂</p><p>[desk]:[assets/2022-08-17-desk.png &quot;I&apos;ll put this away any day now.&quot;] [boring]:[assets/2022-08-17-boring.png &quot;Oh wow, so ex... zzz&quot;] [awesome]:[assets/2022-08-17-7amkickoff.png &quot;Engagement reaching new heights!&quot;] [metatags]:[assets/2022-08-17-metatags.png &quot;Spectacularity!&quot;]</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-08-11-dogfooding-blambda-cli-ier.html</id>
    <link href="https://jmglov.net/blog/2022-08-11-dogfooding-blambda-cli-ier.html"/>
    <title>Dogfooding Blambda 4: CLI, CLIier, CLIiest</title>
    <updated>2022-08-11T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>In <a href="2022-08-10-dogfooding-blambda-cli.html">yesterday&apos;s installment of Dogfooding
Blambda</a>, I fully intended to show y&apos;all <a href="https://github.com/jmglov/blambda">Blambda</a>&apos;s command line interface, then walk you through how I implemented it, using the amazing <a href="https://github.com/babashka/cli">babashka.cli</a> library. However, me being me, I kinda meandered all over the place, and by the time I had finished the &quot;show&quot; portion of Show and Tell, my dog let me know, kindly but firmly as only a dog can, that the &quot;tell&quot; portion would need to wait, because he couldn&apos;t anymore.</p><p>But hey, today is a new day, and I have heaps of time, so let&apos;s dig in!</p><p>After the <a href="2022-08-09-dogfooding-blambda-2.html">less than wonderful experience I
had</a> using Blambda in my <a href="https://github.com/jmglov/s3-log-parser">s3-log-parser</a> lambda, I decided that Blambda should be a library that exposed its functionality via an API, similar to how <a href="https://github.com/borkdude/quickblog">quickblog</a> works. Thinking about what the API should look like, I decided on the following functions:</p><ul><li><code>build-runtime-layer</code>: builds the Blambda custom runtime as a Lambda layer</li><li><code>deploy-runtime-layer</code>: deploys the custom runtime layer</li><li><code>build-deps-layer</code>: builds a layer for lambda dependencies</li><li><code>deploy-deps-layer</code>: deploys the dependencies layer</li><li><code>clean</code>: sweeps up around the place to give you that peaceful happy feeling that you so crave</li></ul><p>I had the code for building and deploying the custom runtime layer in Blamba&apos;s <a href="https://github.com/jmglov/blambda/blob/c253bf7d2b0bbbe3e53ad276b1c15c53b98d2088/bb.edn"><code>bb.edn</code></a>, as well as the code for building the deps layer, but in my infinite wisdom, the code for actually deploying the deps layer was in s3-log-parser, in the wonderfully named <a href="https://github.com/jmglov/s3-log-parser/blob/dcbb6546cc5e0d61a1374feeff78c0f58aa2d3c3/task_helper.clj"><code>task_helper.clj</code></a> file.</p><p>It was straightforward enough to move the code for building and deploying into a <a href="https://github.com/jmglov/blambda/blob/2453e15cf75c03b2b02de5ca89c76081bba40251/src/blambda/api.clj"><code>blambda.api</code></a> namespace, and I had at least had the foresight to write a primitive argument parser in Blambda&apos;s own <a href="https://github.com/jmglov/blambda/blob/c253bf7d2b0bbbe3e53ad276b1c15c53b98d2088/task_helper.clj#L41"><code>task_helper.clj</code></a> that turned something like <code>bb build-runtime-layer --bb-arch arm64 --bb-version 0.9.161</code> into:</p><pre><code class="language-clojure">{:bb-arch &quot;arm64&quot;
 :bb-version &quot;0.9.161&quot;}
</code></pre><p>Since this is also how babashka.cli works, the migration was fairly straightforward. I took my old <code>task-helper/defaults</code>:</p><pre><code class="language-clojure">{:aws-region {:doc &quot;AWS region&quot;
              :default (or (System/getenv &quot;AWS_DEFAULT_REGION&quot;) &quot;eu-west-1&quot;)}
:bb-version {:doc &quot;Babashka version&quot;
             :default &quot;0.9.161&quot;}
:bb-arch {:doc &quot;Architecture to target&quot;
          :default &quot;amd64&quot;
          :values [&quot;amd64&quot; &quot;arm64&quot;]}
:deps-path {:doc &quot;Path to bb.edn or deps.edn containing lambda deps&quot;}
:layer-name {:doc &quot;Name of custom runtime layer in AWS&quot;
             :default &quot;blambda&quot;}
:target-dir {:doc &quot;Build output directory&quot;
             :default &quot;target&quot;}
:work-dir {:doc &quot;Working directory&quot;
           :default &quot;.work&quot;}}
</code></pre><p>and turned them into a babashka.cli <a href="https://github.com/babashka/cli#spec">spec</a>:</p><pre><code class="language-clojure">{:aws-region {:desc &quot;AWS region&quot;
              :ref &quot;&lt;region&gt;&quot;
              :default (or (System/getenv &quot;AWS_DEFAULT_REGION&quot;) &quot;eu-west-1&quot;)}
 :bb-version {:desc &quot;Babashka version&quot;
              :ref &quot;&lt;version&gt;&quot;
              :default &quot;0.9.161&quot;}
 :bb-arch {:desc &quot;Architecture to target&quot;
           :ref &quot;&lt;arch&gt;&quot;
           :default &quot;amd64&quot;
           :values [&quot;amd64&quot; &quot;arm64&quot;]}
 :deps-path {:desc &quot;Path to bb.edn or deps.edn containing lambda dependencies&quot;
             :ref &quot;&lt;path&gt;&quot;}
 :deps-layer-name {:desc &quot;Name of dependencies layer in AWS&quot;
                   :ref &quot;&lt;name&gt;&quot;}
 :runtime-layer-name {:desc &quot;Name of custom runtime layer in AWS&quot;
                      :ref &quot;&lt;name&gt;&quot;
                      :default &quot;blambda&quot;}
 :target-dir {:desc &quot;Build output directory&quot;
              :ref &quot;&lt;dir&gt;&quot;
              :default &quot;target&quot;}
 :work-dir {:desc &quot;Working directory&quot;
            :ref &quot;&lt;dir&gt;&quot;
            :default &quot;.work&quot;}}
</code></pre><p>With this, I could create a nice CLI for Blambda:</p><pre><code class="language-clojure">(ns blambda.cli
  (:require [babashka.cli :as cli]))

(def spec
  {
  ;; ...
  })

(defn parse-opts [&amp; _]
  (let [opts (cli/parse-opts *command-line-args* {:spec spec})]
    (if (:help opts)
      (do
        (println (cli/format-opts {:spec spec}))
        (System/exit 0))
      opts)))
</code></pre><p>This is all it takes to get a lovely usage message:</p><pre><code class="language-text">$ bb -m blambda.cli/parse-opts --help
  --aws-region         &lt;region&gt;  eu-west-1 AWS region
  --bb-version         &lt;version&gt; 0.9.161   Babashka version
  --bb-arch            &lt;arch&gt;    amd64     Architecture to target
  --deps-path          &lt;path&gt;              Path to bb.edn or deps.edn containing lambda dependencies
  --deps-layer-name    &lt;name&gt;              Name of dependencies layer in AWS
  --runtime-layer-name &lt;name&gt;    blambda   Name of custom runtime layer in AWS
  --target-dir         &lt;dir&gt;     target    Build output directory
  --work-dir           &lt;dir&gt;     .work     Working directory
</code></pre><p>So that&apos;s Blambda as a library. Now I can use that in s3-log-parser to manage all of the moving parts in one place. In order to do this, all I need to do is add tasks to s3-log-parser&apos;s <code>bb.edn</code>:</p><pre><code class="language-clojure">{:paths [&quot;.&quot;]
 :deps {net.jmglov/blambda
        #_&quot;You use the newest SHA here:&quot;
        {:git/url &quot;https://github.com/jmglov/blambda.git&quot;
         :git/sha &quot;e379410bb6b20bb9cf34acd42cfc65e5f4fd6845&quot;}}
 :tasks
 {:requires ([blambda.api :as blambda])

  build-runtime-layer {:doc &quot;Builds Blambda custom runtime layer&quot;
                       :task (blambda/build-runtime-layer)}

  deploy-runtime-layer {:doc &quot;Deploys Blambda custom runtime layer&quot;
                        :task (blambda/deploy-runtime-layer)}

  build-deps-layer {:doc &quot;Builds dependencies layer&quot;
                    :task (blambda/build-deps-layer)}

  deploy-deps-layer {:doc &quot;Deploys dependencies layer&quot;
                     :task (blambda/deploy-deps-layer)}

  clean {:doc &quot;Deletes target and work directories&quot;
         :task (blambda/clean)}}}
</code></pre><p>Now I can do things like build my dependencies layer:</p><pre><code class="language-text">$ bb build-deps-layer --deps-path src/bb.edn 
Classpath before transforming: src:~/s3-log-parser/.work/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...

Classpath after transforming: src:/opt/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...

Compressing custom runtime layer: ~/s3-log-parser/target/deps.zip
</code></pre><p>It&apos;s a little annoying that I have to add one task per library function, and even more annoying that I have to repeat information that&apos;s already there in <code>blambda.api</code>:</p><pre><code class="language-clojure">(defn build-runtime-layer
  &quot;Builds Blambda custom runtime layer&quot;
  ;; ...
  )

(defn deploy-runtime-layer
  &quot;Deploys Blambda custom runtime layer&quot;
  ;; ...
  )

(defn build-deps-layer
  &quot;Builds dependencies layer&quot;
  ;; ...
  )

(defn deploy-deps-layer
  &quot;Deploys dependencies layer&quot;
  ;; ...
  )

(defn clean
  &quot;Deletes target and work directories&quot;
  ;; ...
  )
</code></pre><p>What I&apos;d like to do is add a single task that delegates all of this stuff to the Blambda CLI. But how to find this holiest of all holy grails?</p><p>Of course the mighty <a href="https://github.com/borkdude">borkdude</a> has already thought of this, and babashka.cli has support for <a href="https://github.com/babashka/cli#subcommands">subcommands</a>. If I expose each Blambda API function as a subcommand, I can interact with Blambda from s3-log-parser as I showed you yesterday:</p><pre><code class="language-text">$ bb blambda build-runtime-layer --bb-arch arm64
Downloading https://github.com/babashka/babashka/releases/download/v0.9.161/babashka-0.9.161-linux-aarch64-static.tar.gz
Decompressing .work/babashka-0.9.161-linux-aarch64-static.tar.gz to .work
Adding file bootstrap
Adding file bootstrap.clj
Compressing custom runtime layer: ~/my-lambda/target/bb.zip

$ bb blambda deploy-runtime-layer --bb-arch arm64
Publishing layer version for layer blambda
Published layer arn:aws:lambda:eu-west-1:289341159200:layer:blambda:1
</code></pre><p>And all this by adding a single line to my <code>bb.edn</code> (actually two lines, since I need to require <code>blambda.cli</code>, or rather three lines, since I want to nicely format the map, but you know what I mean):</p><pre><code class="language-clojure">:tasks
{:requires ([blambda.cli :as blambda])

 blambda {:doc &quot;Controls Blambda runtime and layers&quot;
          :task (blambda/dispatch)}}
</code></pre><p>Wow, now that&apos;s some amazing UX! 🏆</p><p>But how does this subcommand stuff work? babashka.cli&apos;s documentation gives this example:</p><pre><code class="language-clojure">(ns example
  (:require [babashka.cli :as cli]))

(defn copy [m]
  (assoc m :fn :copy))

(defn delete [m]
  (assoc m :fn :delete))

(defn help [m]
  (assoc m :fn :help))

(def table
  [{:cmds [&quot;copy&quot;]   :fn copy   :args-&gt;opts [:file]}
   {:cmds [&quot;delete&quot;] :fn delete :args-&gt;opts [:file]}
   {:cmds []         :fn help}])

(defn -main [&amp; args]
  (cli/dispatch table args {:coerce {:depth :long}}))
</code></pre><p>So it looks like I need to build a table that looks something like this:</p><pre><code class="language-clojure">(def table
  [{:cmds [&quot;build-runtime-layer&quot;]  :fn api/build-runtime-layer}
   {:cmds [&quot;deploy-runtime-layer&quot;] :fn api/deploy-runtime-layer}
   {:cmds [&quot;build-deps-layer&quot;]     :fn api/build-deps-layer}
   {:cmds [&quot;deploy-deps-layer&quot;]    :fn api/deploy-deps-layer}
   {:cmds [&quot;clean&quot;]                :fn api/build-runtime-layer}
   {:cmds []                       :fn print-help}])
</code></pre><p>And according to the docs, I can include other <code>babashka.cli/parse-arg</code> options in a table entry, so I&apos;ll add <code>:spec spec</code> to each.</p><p>Now I can run <code>bb blambda --help</code> from s3-log-parser to get a nice usage message:</p><pre><code class="language-text">  --aws-region         &lt;region&gt;  eu-west-1 AWS region
  --bb-version         &lt;version&gt; 0.9.161   Babashka version
  --bb-arch            &lt;arch&gt;    amd64     Architecture to target
  --deps-path          &lt;path&gt;              Path to bb.edn or deps.edn containing lambda dependencies
  --deps-layer-name    &lt;name&gt;              Name of dependencies layer in AWS
  --runtime-layer-name &lt;name&gt;    blambda   Name of custom runtime layer in AWS
  --target-dir         &lt;dir&gt;     target    Build output directory
  --work-dir           &lt;dir&gt;     .work     Working directory
</code></pre><p>Well, nice-ish. If I run this, I have no idea what subcommands <code>bb blambda</code> has, what they do, and which of these options apply to each command. Let&apos;s see if we can fix this.</p><p>Let&apos;s start by enriching our <code>print-help</code> function a bit and modifying our table to use it:</p><pre><code class="language-clojure">(defn print-help [cmds]
  (println
   (format
    &quot;Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

Subcommands:

%s&quot;
    (-&gt;&gt; cmds
         (map (comp first :cmds))
         (str/join &quot;\n\n&quot;)))))

(def table
  (let [cmds
        [{:cmds [&quot;build-runtime-layer&quot;]  :fn api/build-runtime-layer}
         {:cmds [&quot;deploy-runtime-layer&quot;] :fn api/deploy-runtime-layer}
         {:cmds [&quot;build-deps-layer&quot;]     :fn api/build-deps-layer}
         {:cmds [&quot;deploy-deps-layer&quot;]    :fn api/deploy-deps-layer}
         {:cmds [&quot;clean&quot;]                :fn api/build-runtime-layer}]]
    (conj cmds
          {:cmds [] :fn (fn [_] (print-help cmds))})))
</code></pre><p>Now running <code>bb blambda --help</code> (or <code>bb blambda help</code> or <code>bb blambda</code>, for that matter) produces something a bit nicer:</p><pre><code class="language-text">Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

Subcommands:

build-runtime-layer

deploy-runtime-layer

build-deps-layer

deploy-deps-layer

clean
</code></pre><p>Let&apos;s add a description to each subcommand and then update <code>print-help</code>:</p><pre><code class="language-clojure">(def table
  (let [cmds
        [{:cmds [&quot;build-runtime-layer&quot;]
          :desc &quot;Builds Blambda custom runtime layer&quot;
          :fn api/build-runtime-layer}
         {:cmds [&quot;deploy-runtime-layer&quot;]
          :desc &quot;Deploys Blambda custom runtime layer&quot;
          :fn api/deploy-runtime-layer}
         ;; ...
        ]]
    (conj cmds
          {:cmds [] :fn (fn [_] (print-help cmds))})))

(defn print-help&apos; [cmds]
  (println
   (format
    &quot;Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

Subcommands:

%s&quot;
    (-&gt;&gt; cmds
         (map (fn [{:keys [cmds desc]}]
                (format &quot;%s: %s&quot; (first cmds) desc)))
         (str/join &quot;\n\n&quot;)))))
</code></pre><p>Now we&apos;re getting somewhere!</p><pre><code class="language-text">Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

Subcommands:

build-runtime-layer: Builds Blambda custom runtime layer

deploy-runtime-layer: Deploys Blambda custom runtime layer

build-deps-layer: Builds dependencies layer from bb.edn or deps.edn

deploy-deps-layer: Deploys dependencies layer

clean: Removes work and target folders
</code></pre><p>Now it&apos;s time to bring back our options. If we look at the options we have, <code>--target-dir</code> and <code>--work-dir</code> apply to every command, <code>--aws-region</code> applies to the two deployment commands, and the rest of the options (<code>--bb-arch</code>, <code>--bb-version</code>, <code>--deps-path</code>, <code>--runtime-layer-name</code>, and <code>--deps-layer-name</code>) apply only to specific commands. Let&apos;s see how we can express this in our command table:</p><pre><code class="language-clojure">(def table
  (let [cmds
        [{:cmds [&quot;build-runtime-layer&quot;]
          :desc &quot;Builds Blambda custom runtime layer&quot;
          :fn api/build-runtime-layer
          :opts #{:bb-version :bb-arch}}
         {:cmds [&quot;build-deps-layer&quot;]
          :desc &quot;Builds dependencies layer from bb.edn or deps.edn&quot;
          :fn api/build-deps-layer
          :opts #{:deps-path}}
         {:cmds [&quot;deploy-runtime-layer&quot;]
          :desc &quot;Deploys Blambda custom runtime layer&quot;
          :fn api/deploy-runtime-layer
          :opts #{:aws-region :bb-arch :runtime-layer-name}}
         {:cmds [&quot;deploy-deps-layer&quot;]
          :desc &quot;Deploys dependencies layer&quot;
          :fn api/deploy-deps-layer
          :opts #{:aws-region :bb-arch :deps-layer-name}}
         {:cmds [&quot;clean&quot;]
          :desc &quot;Removes work and target folders&quot;
          :fn api/clean}]]
    (conj cmds
          {:cmds [], :fn (fn [m] (print-help cmds))})))
</code></pre><p>This makes sense, but now we need a way to turn a set of opts into a spec. Whilst we&apos;re at it, let&apos;s add the global options (<code>--target-dir</code> and <code>--work-dir</code>) to every spec:</p><pre><code class="language-clojure">(def specs
  {:aws-region
   {:desc &quot;AWS region&quot;
    :ref &quot;&lt;region&gt;&quot;
    :default (or (System/getenv &quot;AWS_DEFAULT_REGION&quot;) &quot;eu-west-1&quot;)}
   ;; ...
  })

(def global-opts #{:target-dir :work-dir})

(defn mk-spec [default-opts opts]
  (select-keys specs (set/union global-opts opts)))
</code></pre><p>Now we can plug <code>mk-spec</code> into our table:</p><pre><code class="language-clojure">(def table
  (let [cmds
        [{:cmds [&quot;build-runtime-layer&quot;]
          :desc &quot;Builds Blambda custom runtime layer&quot;
          :fn api/build-runtime-layer
          :spec (mk-spec #{:bb-version :bb-arch})}
         {:cmds [&quot;build-deps-layer&quot;]
          :desc &quot;Builds dependencies layer from bb.edn or deps.edn&quot;
          :fn api/build-deps-layer
          :spec (mk-spec #{:deps-path})}
         {:cmds [&quot;deploy-runtime-layer&quot;]
          :desc &quot;Deploys Blambda custom runtime layer&quot;
          :fn api/deploy-runtime-layer
          :spec (mk-spec #{:aws-region :bb-arch :runtime-layer-name})}
         {:cmds [&quot;deploy-deps-layer&quot;]
          :desc &quot;Deploys dependencies layer&quot;
          :fn api/deploy-deps-layer
          :spec (mk-spec #{:aws-region :deps-layer-name})}
         {:cmds [&quot;clean&quot;]
          :desc &quot;Removes work and target folders&quot;
          :fn api/clean}]]
    (conj cmds
          {:cmds [], :fn (fn [m] (print-help cmds))})))
</code></pre><p>And since we have the spec for each subcommand, we can use that in our help message:</p><pre><code class="language-clojure">(defn -&gt;subcommand-help [{:keys [cmd desc spec]}]
  (format &quot;%s: %s\n%s&quot; cmd desc
          (cli/format-opts {:spec spec})))

(defn print-help [cmds]
  (println
   (format
    &quot;Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

All subcommands support the options:

%s

Subcommands:

%s&quot;
    (cli/format-opts {:spec (select-keys specs global-opts)})
    (-&gt;&gt; cmds
         (map -&gt;subcommand-help)
         (str/join &quot;\n\n&quot;))))
  (System/exit 0))
</code></pre><p>Running <code>bb blambda</code> now is very satisfying:</p><pre><code class="language-text">Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

All subcommands support the options:

  --work-dir   &lt;dir&gt; .work  Working directory
  --target-dir &lt;dir&gt; target Build output directory

Subcommands:

build-runtime-layer: Builds Blambda custom runtime layer
  --bb-arch    &lt;arch&gt;    amd64   Architecture to target (use amd64 if you don&apos;t care)
  --work-dir   &lt;dir&gt;     .work   Working directory
  --target-dir &lt;dir&gt;     target  Build output directory
  --bb-version &lt;version&gt; 0.9.161 Babashka version

build-deps-layer: Builds dependencies layer from bb.edn or deps.edn
  --work-dir   &lt;dir&gt;  .work  Working directory
  --deps-path  &lt;path&gt;        Path to bb.edn or deps.edn containing lambda deps
  --target-dir &lt;dir&gt;  target Build output directory

deploy-runtime-layer: Deploys Blambda custom runtime layer
  --bb-arch            &lt;arch&gt;   amd64     Architecture to target (use amd64 if you don&apos;t care)
  --runtime-layer-name &lt;name&gt;   blambda   Name of custom runtime layer in AWS
  --work-dir           &lt;dir&gt;    .work     Working directory
  --aws-region         &lt;region&gt; eu-west-1 AWS region
  --target-dir         &lt;dir&gt;    target    Build output directory

deploy-deps-layer: Deploys dependencies layer
  --work-dir        &lt;dir&gt;    .work     Working directory
  --aws-region      &lt;region&gt; eu-west-1 AWS region
  --target-dir      &lt;dir&gt;    target    Build output directory
  --deps-layer-name &lt;name&gt;             Name of dependencies layer in AWS

clean: Removes work and target folders
</code></pre><p>There&apos;s one tiny annoyance, though. The usage message says that all subcommands support <code>--work-dir</code> and <code>--target-dir</code>, but then those options are repeated for every subcommand, which is a bit unnecessary and distracting. What we need to do is suppress the global options in <code>-&gt;subcommand-help</code>:</p><pre><code class="language-clojure">(defn -&gt;subcommand-help [{:keys [cmd desc spec]}]
  (let [spec (apply dissoc spec global-opts)]
    (format &quot;%s: %s\n%s&quot; cmd desc
            (cli/format-opts {:spec spec}))))
</code></pre><p><code>dissoc</code> is normally used to remove one key from a map:</p><pre><code class="language-clojure">(dissoc {:a 1, :b 2, :c 3} :a)  ;; =&gt; {:b 2, :c 3}
</code></pre><p>but you can also give it more keys:</p><pre><code class="language-clojure">(dissoc {:a 1, :b 2, :c 3} :a :b)  ;; =&gt; {:c 3}
</code></pre><p>We have a set, <code>global-opts</code>, which is seqable, so we can use <code>apply</code> to splat it onto the end of the list of arguments to <code>dissoc</code>:</p><pre><code class="language-clojure">(let [spec (apply dissoc spec global-opts)]
  ;; Now spec has all of the opts except the global ones
  )
</code></pre><p>Let&apos;s see what we&apos;ve accomplished:</p><pre><code class="language-text">$ bb blambda
Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

All subcommands support the options:

  --work-dir   &lt;dir&gt; .work  Working directory
  --target-dir &lt;dir&gt; target Build output directory

Subcommands:

build-runtime-layer: Builds Blambda custom runtime layer
  --bb-arch    &lt;arch&gt;    amd64   Architecture to target (use amd64 if you don&apos;t care)
  --bb-version &lt;version&gt; 0.9.161 Babashka version

build-deps-layer: Builds dependencies layer from bb.edn or deps.edn
  --deps-path &lt;path&gt; Path to bb.edn or deps.edn containing lambda deps

deploy-runtime-layer: Deploys Blambda custom runtime layer
  --bb-arch            &lt;arch&gt;   amd64     Architecture to target (use amd64 if you don&apos;t care)
  --runtime-layer-name &lt;name&gt;   blambda   Name of custom runtime layer in AWS
  --aws-region         &lt;region&gt; eu-west-1 AWS region

deploy-deps-layer: Deploys dependencies layer
  --aws-region      &lt;region&gt; eu-west-1 AWS region
  --deps-layer-name &lt;name&gt;             Name of dependencies layer in AWS

clean: Removes work and target folders
</code></pre><p>Excellent!</p><p>We&apos;re still missing one thing that I showed off yesterday, though: the ability for a client to override Blambda&apos;s defaults. In the case of s3-log-parser, I want to make sure I&apos;m building Blambda for the ARM64 architecture, and set my deps path and deps layer name so that I don&apos;t have to remember to type the args every time.</p><p>Let&apos;s start out by wishing the feature into existence in s3-log-parser&apos;s <code>bb.edn</code>:</p><pre><code class="language-clojure">:tasks
{:requires ([blambda.cli :as blambda])

 blambda {:doc &quot;Controls Blambda runtime and layers&quot;
          :task (blambda/dispatch
                 {:bb-arch &quot;arm64&quot;
                  :deps-path &quot;src/bb.edn&quot;
                  :deps-layer-name &quot;s3-log-parser-deps&quot;})}}
</code></pre><p>So we want the client to be able to pass defaults to <code>blambda.cli/dispatch</code>. Let&apos;s make it happen:</p><pre><code class="language-clojure">(defn dispatch
  ([]
   (dispatch {}))
  ([default-opts &amp; args]
   (cli/dispatch (mk-table default-opts)
                 (or args
                     (seq *command-line-args*)))))
</code></pre><p>Because we&apos;re good Clojurists, we maintain backwards compatibility by keeping the 0-arity version of <code>dispatch</code>, and just have it send an empty <code>default-opts</code> map into the new 1-arity version.</p><p>We&apos;re not going to be able to keep our static version of <code>table</code> anymore either, so we&apos;ll wrap it in a function called <code>mk-table</code> that incorporates our defaults:</p><pre><code class="language-clojure">(defn mk-table [default-opts]
  (let [cmds
        [{:cmds [&quot;build-runtime-layer&quot;]
          :desc &quot;Builds Blambda custom runtime layer&quot;
          :fn api/build-runtime-layer
          :spec (mk-spec default-opts #{:bb-version :bb-arch})}
         ;; ...
         ]]
    (conj cmds
          {:cmds [], :fn (fn [m] (print-help default-opts cmds))})))
</code></pre><p>We need to pass the <code>default-opts</code> along to <code>mk-spec</code> and <code>print-help</code> as well:</p><pre><code class="language-clojure">(defn mk-spec [default-opts opts]
  (-&gt;&gt; (select-keys specs (set/union global-opts opts))
       (apply-defaults default-opts)))

(defn -&gt;subcommand-help [default-opts {:keys [cmd desc spec]}]
  (let [spec (apply dissoc spec global-opts)]
    (format &quot;%s: %s\n%s&quot; cmd desc
            (cli/format-opts {:spec
                              (apply-defaults default-opts spec)}))))

(defn print-help [default-opts cmds]
  (println
   (format
    &quot;Usage: bb blambda &lt;subcommand&gt; &lt;options&gt; ...&quot;
    (cli/format-opts {:spec (select-keys specs global-opts)})
    (-&gt;&gt; cmds
         (map (partial -&gt;subcommand-help default-opts))
         (str/join &quot;\n\n&quot;))))
  (System/exit 0))
</code></pre><p>And finally, let&apos;s look at this mysterious new <code>apply-defaults</code> function:</p><pre><code class="language-clojure">(defn apply-defaults [default-opts spec]
  (-&gt;&gt; spec
       (map (fn [[k v]]
              (if-let [default-val (default-opts k)]
                [k (assoc v :default default-val)]
                [k v])))
       (into {})))
</code></pre><p>If we run <code>bb blambda help</code> now, we can see the effects of our changes:</p><pre><code class="language-text">Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;
[...]
Subcommands:

build-runtime-layer: Builds Blambda custom runtime layer
  --bb-arch    &lt;arch&gt;    arm64   Architecture to target (use amd64 if you don&apos;t care)
  --bb-version &lt;version&gt; 0.9.161 Babashka version

build-deps-layer: Builds dependencies layer from bb.edn or deps.edn
  --deps-path &lt;path&gt; src/bb.edn Path to bb.edn or deps.edn containing lambda deps

deploy-deps-layer: Deploys dependencies layer
  --aws-region      &lt;region&gt; eu-west-1          AWS region
  --deps-layer-name &lt;name&gt;   s3-log-parser-deps Name of dependencies layer in AWS
</code></pre><p>Note that <code>--bb-arch</code> now defaults to <code>arm64</code>, and <code>--deps-path</code> and <code>--deps-layer-name</code> now have default values, which they didn&apos;t before! 🎉</p><p>I realise I&apos;m quite a few words into this post now, but I do want to add one more tiny feature. With a subcommand setup, you expect <code>bb blambda build-runtime-layer --help</code> to give you help on the <code>build-runtime-layer</code> subcommand, but at the moment, our code just ignores the <code>--help</code> flag and calls the <code>api/build-runtime-layer</code> function, which is definitely not what we want.</p><p>In order to support this, let&apos;s wrap the <code>api/build-runtime-layer</code> in a function that checks for <code>--help</code> and does the right thing:</p><pre><code class="language-clojure">(defn mk-table [default-opts]
  (let [cmds
        [{:cmds [&quot;build-runtime-layer&quot;]
          :desc &quot;Builds Blambda custom runtime layer&quot;
          :fn (fn [opts]
                (when (:help opts)
                  (print-command-help cmd spec)
                  (System/exit 0))
                (api/build-runtime-layer))
          :spec (mk-spec default-opts #{:bb-version :bb-arch})}
         ;; ...
         ]]
    (conj cmds
          {:cmds [], :fn (fn [m] (print-help default-opts cmds))})))
</code></pre><p>We can define <code>print-command-help</code> as follows:</p><pre><code class="language-clojure">(defn print-command-help [cmd spec]
  (println
   (format &quot;Usage: bb blambda %s &lt;options&gt;\n\nOptions:\n%s&quot;
           cmd (cli/format-opts {:spec spec}))))
</code></pre><p>Now things work as expected:</p><pre><code class="language-text">$ bb blambda build-runtime-layer --help
Usage: bb blambda build-runtime-layer &lt;options&gt;

Options:
  --bb-arch    &lt;arch&gt;    arm64   Architecture to target (use amd64 if you don&apos;t care)
  --work-dir   &lt;dir&gt;     .work   Working directory
  --target-dir &lt;dir&gt;     target  Build output directory
  --bb-version &lt;version&gt; 0.9.161 Babashka version
</code></pre><p>Of course, now we&apos;re in the somewhat unpleasant situation of having to copy and paste our wrapper for all of the other subcommands, so let&apos;s create a function to do this for us:</p><pre><code class="language-clojure">(defn mk-cmd [default-opts {:keys [cmd spec] :as cmd-opts}]
  (merge
   cmd-opts
   {:cmds [cmd]
    :fn (fn [{:keys [opts]}]
          (when (:help opts)
            (print-command-help cmd spec)
            (System/exit 0))
          ((:fn cmd-opts) opts))}))
</code></pre><p>Now we can use this function in <code>mk-table</code>:</p><pre><code class="language-clojure">(defn mk-table [default-opts]
  (let [cmds
        [{:cmd &quot;build-runtime-layer&quot;
          :desc &quot;Builds Blambda custom runtime layer&quot;
          :fn api/build-runtime-layer
          :spec (mk-spec default-opts #{:bb-version :bb-arch})}
         ;; ...
         ]]
    (conj (mapv (partial mk-cmd default-opts) cmds)
          {:cmds [], :fn (fn [m] (print-help default-opts cmds))})))
</code></pre><p>So <code>--help</code> now works for all subcommands. And since we now have <code>mk-cmd</code> wrapping our subcommand function for us, let&apos;s also ensure that all options are set (we have no optional options here):</p><pre><code class="language-clojure">(defn mk-cmd [default-opts {:keys [cmd spec] :as cmd-opts}]
  (merge
   cmd-opts
   {:cmds [cmd]
    :fn (fn [{:keys [opts]}]
          (let [missing-args (-&gt;&gt; (set (keys opts))
                                  (set/difference (set (keys spec)))
                                  (map #(format &quot;--%s&quot; (name %)))
                                  (str/join &quot;, &quot;))]
            (when (:help opts)
              (print-command-help cmd spec)
              (System/exit 0))
            (when-not (empty? missing-args)
              (error {:cmd cmd, :spec spec}
                     (format &quot;Missing required arguments: %s&quot; missing-args)))
            ((:fn cmd-opts) opts)))}))
</code></pre><p>The <code>error</code> function just formats a nice error message and exits:</p><pre><code class="language-clojure">(defn error [{:keys [cmd spec]} msg]
  (println (format &quot;%s\n&quot; msg))
  (print-command-help cmd spec)
  (System/exit 1))
</code></pre><p>We can test this by commenting out the <code>:deps-path</code> key-value pair in s3-log-parser&apos;s <code>bb.edn</code>:</p><pre><code class="language-clojure">:tasks
{:requires ([blambda.cli :as blambda])

 blambda {:doc &quot;Controls Blambda runtime and layers&quot;
          :task (blambda/dispatch
                 {:bb-arch &quot;arm64&quot;
;;                  :deps-path &quot;src/bb.edn&quot;
                  :deps-layer-name &quot;s3-log-parser-deps&quot;})}}
</code></pre><p>and then not mentioning <code>--deps-path</code> on the command line:</p><pre><code class="language-text">$ bb blambda build-deps-layer
Missing required arguments: --deps-path

Usage: bb blambda build-deps-layer &lt;options&gt;

Options:
  --work-dir   &lt;dir&gt;  .work  Working directory
  --deps-path  &lt;path&gt;        Path to bb.edn or deps.edn containing lambda deps
  --target-dir &lt;dir&gt;  target Build output directory
</code></pre><p>With that, we have achieved a great victory and can now move onto another activity (in my case, sleeping).</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-08-10-dogfooding-blambda-cli.html</id>
    <link href="https://jmglov.net/blog/2022-08-10-dogfooding-blambda-cli.html"/>
    <title>Dogfooding Blambda 3: CLIify this!</title>
    <updated>2022-08-10T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>When <a href="2022-08-09-dogfooding-blambda-2.html">last we left</a> the epic tale of me trying to use a thing that I made myself and then being outraged at how poorly made the thing was, I had just gotten dependencies stuffed in a lambda layer and proved that it worked by deploying a lambda that listed some files from an S3 bucket. Hurrah!</p><p>Of course, I ended that post by complaining about the incredibly bad UX of the thing I had built, and a vague promise to make it less incredibly bad (never let good be the enemy of less bad!). Since last we spoke, I did just that. Check it out!</p><p>So I create a directory called <code>my-lambda</code>, then add a <code>bb.edn</code> like this:</p><pre><code class="language-clojure">{:deps {net.jmglov/blambda
        #_&quot;You use the newest SHA here:&quot;
        {:git/url &quot;https://github.com/jmglov/blambda.git&quot;
         :git/sha &quot;2453e15cf75c03b2b02de5ca89c76081bba40251&quot;}}
 :tasks
 {:requires ([blambda.cli :as blambda])
  blambda {:doc &quot;Controls Blambda runtime and layers&quot;
           :task (blambda/dispatch)}}}
</code></pre><p>This is enough to let me use Blambda:</p><pre><code class="language-text">$ bb blambda
Usage: bb blambda &lt;subcommand&gt; &lt;options&gt;

All subcommands support the options:

  --target-dir &lt;dir&gt; target Build output directory
  --work-dir   &lt;dir&gt; .work  Working directory

Subcommands:

build-runtime-layer: Builds Blambda custom runtime layer
  --bb-version &lt;version&gt; 0.9.161 Babashka version
  --bb-arch    &lt;arch&gt;            Architecture to target (use amd64 if you don&apos;t care)

build-deps-layer: Builds dependencies layer from bb.edn or deps.edn
  --deps-path &lt;path&gt; Path to bb.edn or deps.edn containing lambda deps

deploy-runtime-layer: Deploys Blambda custom runtime layer
  --aws-region         &lt;region&gt; eu-west-1 AWS region
  --runtime-layer-name &lt;name&gt;   blambda   Name of custom runtime layer in AWS
  --bb-arch            &lt;arch&gt;   amd64     Architecture to target

deploy-deps-layer: Deploys dependencies layer
  --aws-region      &lt;region&gt; eu-west-1 AWS region
  --deps-layer-name &lt;name&gt;             Name of dependencies layer in AWS

clean: Removes work and target folders
</code></pre><p>I can create a Blambda runtime:</p><pre><code class="language-text">$ bb blambda build-runtime-layer --help
Usage: bb blambda build-runtime-layer &lt;options&gt;

Options:
  --target-dir &lt;dir&gt;     target  Build output directory
  --work-dir   &lt;dir&gt;     .work   Working directory
  --bb-version &lt;version&gt; 0.9.161 Babashka version
  --bb-arch    &lt;arch&gt;            Architecture to target

$ bb blambda build-runtime-layer --bb-arch arm64
Downloading https://github.com/babashka/babashka/releases/download/v0.9.161/babashka-0.9.161-linux-aarch64-static.tar.gz
Decompressing .work/babashka-0.9.161-linux-aarch64-static.tar.gz to .work
Adding file bootstrap
Adding file bootstrap.clj
Compressing custom runtime layer: ~/my-lambda/target/bb.zip
</code></pre><p>And deploy it:</p><pre><code class="language-text">$ bb blambda deploy-runtime-layer --bb-arch arm64
Publishing layer version for layer blambda
Published layer arn:aws:lambda:eu-west-1:289341159200:layer:blambda:1
</code></pre><p>Now, let&apos;s say I want my lambda to do S3 stuff using <a href="https://github.com/grzm/awyeah-api">awyeah-api</a>. I&apos;ll create a <code>src</code> directory and drop a <code>bb.edn</code> in there:</p><pre><code class="language-clojure">{:paths [&quot;.&quot;]
 :deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.206&quot;}
        com.cognitect.aws/s3 {:mvn/version &quot;822.2.1109.0&quot;}
        com.grzm/awyeah-api {:git/url &quot;https://github.com/grzm/awyeah-api&quot;
                             :git/sha &quot;0fa7dd51f801dba615e317651efda8c597465af6&quot;}
        org.babashka/spec.alpha {:git/url &quot;https://github.com/babashka/spec.alpha&quot;
                                 :git/sha &quot;433b0778e2c32f4bb5d0b48e5a33520bee28b906&quot;}}}
</code></pre><p>I can now use Blambda to create a lambda layer containing all my dependencies:</p><pre><code class="language-text">$ bb blambda build-deps-layer
Missing required arguments: --deps-path

Usage: bb blambda build-deps-layer &lt;options&gt;

Options:
  --target-dir &lt;dir&gt;  target Build output directory
  --work-dir   &lt;dir&gt;  .work  Working directory
  --deps-path  &lt;path&gt;        Path to bb.edn or deps.edn containing lambda deps
</code></pre><p>Oops! Looks like I forgot the <code>--deps-path</code> argument. Let&apos;s try that again:</p><pre><code class="language-text">$ bb blambda build-deps-layer --deps-path src/bb.edn 
Cloning: https://github.com/grzm/awyeah-api
Downloading: com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.pom from central
Downloading: org/clojure/clojure/1.11.1/clojure-1.11.1.pom from central
Downloading: com/cognitect/aws/s3/822.2.1109.0/s3-822.2.1109.0.pom from central
Checking out: https://github.com/grzm/awyeah-api at 0fa7dd51f801dba615e317651efda8c597465af6
Cloning: https://github.com/babashka/spec.alpha
Checking out: https://github.com/babashka/spec.alpha at 433b0778e2c32f4bb5d0b48e5a33520bee28b906
Downloading: org/clojure/spec.alpha/0.3.218/spec.alpha-0.3.218.pom from central
Downloading: org/clojure/core.specs.alpha/0.2.62/core.specs.alpha-0.2.62.pom from central
Downloading: org/clojure/pom.contrib/1.1.0/pom.contrib-1.1.0.pom from central
Downloading: com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar from central
Downloading: com/cognitect/aws/s3/822.2.1109.0/s3-822.2.1109.0.jar from central
Downloading: org/clojure/spec.alpha/0.3.218/spec.alpha-0.3.218.jar from central
Downloading: org/clojure/clojure/1.11.1/clojure-1.11.1.jar from central
Downloading: org/clojure/core.specs.alpha/0.2.62/core.specs.alpha-0.2.62.jar from central
Classpath before transforming: src:~/my-lambda/.work/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...

Classpath after transforming: src:/opt/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...

Compressing custom runtime layer: ~/my-lambda/target/deps.zip
</code></pre><p>What that wall of text (sorry about that!) is saying is that Blambda is downloading all of the dependencies my lambda has declared in <code>bb.edn</code> and zipping them up into a layer, which I can deploy like this:</p><pre><code class="language-text">$ bb blambda deploy-deps-layer --deps-layer-name my-lambda-deps
Publishing layer version for layer my-lambda-deps
Published layer arn:aws:lambda:eu-west-1:289341159200:layer:my-lambda-deps:1
</code></pre><p>It is a little annoying to have to remember those arguments every time, so let&apos;s see what we can do about that. If I go back to my top-level <code>bb.edn</code>, I can specify some defaults for my lambda:</p><pre><code class="language-clojure">{:deps {net.jmglov/blambda
        #_&quot;You use the newest SHA here:&quot;
        {:git/url &quot;https://github.com/jmglov/blambda.git&quot;
         :git/sha &quot;2453e15cf75c03b2b02de5ca89c76081bba40251&quot;}}
 :tasks
 {:requires ([blambda.cli :as blambda])
  :init (def opts {:deps-path &quot;src/bb.edn&quot;
                   :deps-layer-name &quot;my-lambda-deps&quot;
                   :bb-arch &quot;arm64&quot;})
  blambda {:doc &quot;Controls Blambda runtime and layers&quot;
           :task (blambda/dispatch opts)}}}
</code></pre><p>By adding the <code>opts</code> there, I&apos;ve saved myself the trouble of typing <code>--bb-arch</code>, <code>--deps-path</code>, and <code>--deps-layer-name</code>:</p><pre><code class="language-text">$ bb blambda build-deps-layer
Classpath before transforming: src:~/my-lambda/.work/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...

Classpath after transforming: src:/opt/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...

Compressing custom runtime layer: ~/my-lambda/target/deps.zip
</code></pre><p>I can now create a lambda in the AWS console that uses Blambda and my deps layer.</p><p>![AWS Lambda console showing create function dialog][create]</p><p>Now I need to add the custom runtime layer:</p><p>![AWS Lambda console showing add layer dialog with Blambda layer selected][runtime]</p><p>And the deps layer:</p><p>![AWS Lambda console showing add layer dialog with deps layer selected][deps]</p><p>Looks nice! Now how about some Clojure code that does something exciting?</p><p>We can delete the files that AWS has put there and replace them with a <code>my_lambda.clj</code> that looks like this:</p><pre><code class="language-clojure">(ns my-lambda
  (:require [cheshire.core :as json]))

(defn handler [event _context]
  (let [body {:msg &quot;Lambda handler invoked&quot;
              :data {:event event}}]
    (prn body)
    {:status 200
     :body (json/generate-string body)}))
</code></pre><p>The Cheshire JSON library is included free of charge by <a href="https://github.com/babashka/babashka">Babashka</a>, so we can play with JSON despite not mentioning it in our <code>src/bb.edn</code>. Amazing!</p><p>We also need to change <strong>Runtime settings &gt; Handler</strong> to <code>my-lambda/handler</code>, then click the <strong>Deploy</strong> button to get our lambda out there in the world!</p><p>![AWS Lambda console showing the code described above][code]</p><p>After deploying, we excitedly click the <strong>Test</strong> button, only to be told that we need to configure a test event! 😭 No matter, we&apos;ll just go with the hello-world template and hope for the best.</p><p>![AWS Lambda console showing a simple JSON test event][test]</p><p>Now that we have a test event configured, let&apos;s click <strong>Test</strong> again... and celebrate a job well done! 🎉</p><p>![AWS Lambda console showing a successful lambda execution][victory]</p><p>I had actually intended to explain the CLI stuff in this post, but this is already a bit long and my dog is starting to give me meaningful looks, so I&apos;d better end this thrilling instalment of <a href="tags/blambda.html">Dogfooding Blambda</a> here and take him out for a walk.</p><p>[create]:[assets/2022-08-10-create-lambda.png &quot;Click the button!&quot;] [runtime]:[assets/2022-08-10-add-runtime.png &quot;Click the button!&quot;] [deps]:[assets/2022-08-10-add-deps.png &quot;Click the button!&quot;] [code]:[assets/2022-08-10-code.png &quot;Such succinctness!&quot;] [test]:[assets/2022-08-10-test-event.png &quot;There&apos;s nothing like JSON to delight a crowd!&quot;] [victory]:[assets/2022-08-10-victory.png &quot;Victory!&quot;]</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-08-09-dogfooding-blambda-2.html</id>
    <link href="https://jmglov.net/blog/2022-08-09-dogfooding-blambda-2.html"/>
    <title>Dogfooding Blambda : I heard you liked layers</title>
    <updated>2022-08-09T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>After a brief detour to port my blog to <a href="https://github.com/borkdude/quickblog">quickblog</a> and enjoy some sun in Málaga, I&apos;m back to eating yummy dogfood by trying to use <a href="https://github.com/jmglov/blambda">Blambda</a> to parse my HTTP access logs: <a href="https://github.com/jmglov/s3-log-parser">jmglov/s3-log-parser</a>.</p><p>I didn&apos;t realise it until I started writing this post, but it has actually been a month since I last used Blambda; I&apos;m sure you all remember the wacky hijinks that ensued when <a href="2022-07-04-dogfooding-blambda-1.html">I tried to make Blambda work with Babashka
pods</a>. Well, more wacky hijinks ensued when I came back to the project and realised that the released version of the <a href="https://github.com/babashka/pod-babashka-aws">babasha-aws pod</a> was compiled for AMD64, and my lambda is of course ARM64 because I want to be cool. Instead of doing what a reasonable person would do and switch to an AMD64 lambda, I decided instead to use <a href="https://github.com/grzm/awyeah-api">awyeah-api</a>, which is a port of Cognitect&apos;s <a href="https://github.com/cognitect-labs/aws-api">aws-api</a> to Babashka. You know, because it&apos;s cool to not have to rely on an external binary and bbencode and all of that stuff. 😉</p><p>Of course, Blambda didn&apos;t actually support dependencies outside of pods, so the first step to switching to awyeah-api was implementing regular deps in Blambda. How hard could it be, right?</p><p>Just like I did for pods, I wanted to keep all deps in a layer so that it would be fast to deploy new versions of the lambda itself, and deps typically don&apos;t change very often. This should be pretty straightforward: just get Babashka to download my deps and zip them up into a layer.</p><p>I created a <code>bb.edn</code> with all of the awyeah-api stuff:</p><pre><code class="language-clojure">{:paths [&quot;.&quot;]
 :deps {com.cognitect.aws/endpoints {:mvn/version &quot;1.1.12.206&quot;}
        com.cognitect.aws/s3 {:mvn/version &quot;822.2.1109.0&quot;}
        com.grzm/awyeah-api {:git/url &quot;https://github.com/grzm/awyeah-api&quot;
                             :git/sha &quot;0fa7dd51f801dba615e317651efda8c597465af6&quot;}
        org.babashka/spec.alpha {:git/url &quot;https://github.com/babashka/spec.alpha&quot;
                                 :git/sha &quot;433b0778e2c32f4bb5d0b48e5a33520bee28b906&quot;}}}
</code></pre><p>Now, running <code>bb tasks</code> in that directory downloaded all of the dependencies into my local Maven cache, <code>~/.m2/repository</code>, so I just need to grab them and stuff them into a zip file. Except there seem to be about a million Java libraries in that directory, and I definitely don&apos;t want more than I actually need, since I want to keep my layer zipfile as small as possible. So what I would like to do is create a new directory and tell Babashka to use that as the Maven cache, so I know that everything downloaded there belongs to my lambda. But how to tell Babashka where I want my deps?</p><p>Searching the web wasn&apos;t much help, mainly because I couldn&apos;t find the right magic phrase, so I turned to Clojurians Slack for help. <a href="https://github.com/borkdude">borkdude</a> himself stopped by and told me that Babashka uses the <a href="https://clojure.org/reference/deps_and_cli">Clojure CLI</a> to resolve dependencies, and then Alex Miller (who must have a Slack alert for any mention of <code>-Sdeps</code>) told me about the <a href="https://clojure.org/reference/deps_and_cli#_dependencies"><code>:mvn/local-repo</code>
key</a>, which does exactly what I want. Excellent!</p><p>And then I ran into the next issue: in addition to Maven dependencies, I also have Git dependencies, and these are handled differently. Going back to the <a href="https://clojure.org/reference/deps_and_cli#_configuration_and_debugging">Deps and CLI
Reference</a>, I found that one can set the <code>GITLIBS</code> environment variable to tell the CLI where to cache Git deps.</p><p>So now I knew how to get all of my deps right where I wanted them, so it was time to automate things with Babashka. I created a new <code>build-deps</code> task in Blamba&apos;s <code>bb.edn</code>. The first step was to consume the lambda&apos;s <code>bb.edn</code> and add the <code>:mvn/local-repo</code> key to it:</p><pre><code class="language-clojure">build-deps {:docs &quot;Builds a layer for dependencies&quot;
            :requires ([clojure.edn :as edn])
            :task (let [{:keys [deps-path work-dir]} (th/parse-args)]
                    (when-not deps-path
                      (th/error &quot;Mising required argument: --deps-path&quot;))
                    (fs/create-dirs work-dir)
                    (let [m2-dir &quot;m2-repo&quot;
                          deps (-&gt;&gt; deps-path slurp edn/read-string :deps)]
                      (spit (fs/file work-dir &quot;deps.edn&quot;)
                            {:deps deps
                             :mvn/local-repo (str m2-dir)})))}
</code></pre><p>This will create a <code>.work/deps.edn</code> file that contains all of the lambda&apos;s dependency, plus the magic <code>:mvn/local-repo</code> key to tell <code>tools.deps</code> to use <code>.work/m2-repo</code> for my Maven deps.</p><p>Now I need to run <code>clojure</code> somehow to download the deps into the right place. Chatting to borkdude revealed that there&apos;s a <code>babashka.deps/clojure</code> function that invokes the Clojure CLI. Awesome, so I can use that! I just need to not forget to set the <code>GITLIBS</code> env var to <code>.work/gitlibs</code> to make sure the Git deps end up in the right place.</p><pre><code class="language-clojure">build-deps {:docs &quot;Builds a layer for dependencies&quot;
            :requires ([clojure.edn :as edn]
                       [babashka.deps :refer [clojure]])
            :task (let [{:keys [deps-path work-dir]} (th/parse-args)]
                    ;; ...
                    (let [gitlibs-dir &quot;gitlibs&quot;
                          m2-dir &quot;m2-repo&quot;
                          deps (-&gt;&gt; deps-path slurp edn/read-string :deps)]
                      ;; ...
                      (clojure [&quot;-Spath&quot;]
                               {:dir work-dir
                                :env (assoc (into {} (System/getenv))
                                            &quot;GITLIBS&quot; (str gitlibs-dir))})))}
</code></pre><p>And now that I have all the deps, I just need to zip them up:</p><pre><code class="language-clojure">build-deps {:docs &quot;Builds a layer for dependencies&quot;
            :requires ([clojure.java.shell :refer [sh]]
                       [clojure.edn :as edn]
                       [babashka.deps :refer [clojure]])
            :task (let [{:keys [deps-path target-dir work-dir]} (th/parse-args)
                        deps-zipfile (th/deps-zipfile target-dir)]
                    ;; ...
                    (fs/create-dirs target-dir work-dir)
                    (let [gitlibs-dir &quot;gitlibs&quot;
                          m2-dir &quot;m2-repo&quot;
                          deps (-&gt;&gt; deps-path slurp edn/read-string :deps)]
                      ;; ...
                      (println &quot;Compressing custom runtime layer:&quot; deps-zipfile)
                      (let [{:keys [exit err]}
                            (sh &quot;zip&quot; &quot;-r&quot; deps-zipfile
                                (fs/file-name gitlibs-dir)
                                (fs/file-name m2-dir)
                                :dir work-dir)]
                        (when (not= 0 exit)
                          (println &quot;Error:&quot; err)))))}
</code></pre><p>This gives me a <code>target/deps.zip</code> that I can use as a layer. Lambda layers unzip to <code>/opt</code>, so I&apos;ll need to update the Blambda runtime to add <code>GITLIBS=/opt/gitlibs</code> to my Babashka invocation and update my lambda&apos;s <code>bb.edn</code> to include <code>:mvn/local-repo &quot;/opt/m2-repo&quot;</code>, and then of course add the deps layer to my lambda function.</p><p>Once all this was done, I took a deep breath and pressed the <strong>Test</strong> button in the AWS Lambda console. And of course got an error. 😭</p><pre><code class="language-text">Exception in thread &quot;main&quot; java.lang.Exception: Couldn&apos;t find &apos;java&apos;.
Please set JAVA_HOME.
  at borkdude.deps$_main.invokeStatic(deps.clj:436)
  at borkdude.deps$_main.doInvoke(deps.clj:425)
  at clojure.lang.RestFn.applyTo(RestFn.java:137)
  at clojure.core$apply.invokeStatic(core.clj:667)
  at babashka.impl.deps$add_deps$fn__26630$fn__26631.invoke(deps.clj:92)
  at babashka.impl.deps$add_deps$fn__26630.invoke(deps.clj:92)
  at babashka.impl.deps$add_deps.invokeStatic(deps.clj:92)
  at babashka.main$exec.invokeStatic(main.clj:789)
  at babashka.main$main.invokeStatic(main.clj:1052)
  at babashka.main$main.doInvoke(main.clj:1027)
  at clojure.lang.RestFn.applyTo(RestFn.java:137)
  at clojure.core$apply.invokeStatic(core.clj:667)
  at babashka.main$_main.invokeStatic(main.clj:1085)
  at babashka.main$_main.doInvoke(main.clj:1077)
  at clojure.lang.RestFn.applyTo(RestFn.java:137)
  at babashka.main.main(Unknown Source)
</code></pre><p>Yikes! I guess this makes sense, though. Babashka is using the Clojure CLI to resolve dependencies, and the Clojure CLI needs a JVM. Unfortunately, this won&apos;t work for me, because the lambda container doesn&apos;t have Java installed.</p><p>At this point, having learned a lot about what&apos;s going on under the hood in Babashka, I decided to cheat and see how <a href="https://github.com/FieryCod/holy-lambda">Holy
Lambda</a> solved this problem for the Babashka backend. Here&apos;s what <a href="https://github.com/FieryCod/holy-lambda/blob/master/modules/holy-lambda-babashka-layer/bootstrap">HL&apos;s bootstrap
script</a> looks like:</p><pre><code class="language-bash">#!/bin/sh

set -e

export BABASHKA_DISABLE_SIGNAL_HANDLERS=&quot;true&quot;

export XDG_CACHE_HOME=/opt
export XDG_CONFIG_HOME=/opt
export XDG_DATA_HOME=/opt
export HOME=/var/task
export GITLIBS=/opt
export CLOJURE_TOOLS_DIR=/opt
export CLJ_CACHE=/opt
export CLJ_CONFIG=/opt

export BABASHKA_CLASSPATH=&quot;/opt/.m2:var/task/src:/var/task/.m2:/var/task:/var/task/src/clj:/var/task/src/cljc:src/cljc:src/clj:/var/task/resources&quot;
export BABASHKA_PRELOADS=&apos;(load-file &quot;/opt/hacks.clj&quot;)&apos;

if [ -z &quot;$HL_ENTRYPOINT&quot; ]; then
  echo &quot;Environment variable \&quot;HL_ENTRYPOINT\&quot; is not set. See https://fierycod.github.io/holy-lambda/#/babashka-backend-tutorial&quot;
fi;

/opt/bb -Duser.home=/var/task -m &quot;$HL_ENTRYPOINT&quot;
</code></pre><p>Aha! HL sets the Babashka classpath explicitly so that Babashka won&apos;t need to do any resolution, and furthermore, that exciting looking <a href="https://github.com/FieryCod/holy-lambda/blob/master/modules/holy-lambda-babashka-layer/hacks.clj"><code>hacks.clj</code></a> actually disables dependency resolution altogether:</p><pre><code class="language-clojure">(require &apos;[babashka.deps])

(alter-var-root
 #&apos;babashka.deps/add-deps
 (fn [f]
   (fn [m]
     (println &quot;[holy-lambda] Dependencies should not be added via add-deps. Move your dependencies to a layer!&quot;)
     (System/exit 1))))
</code></pre><p>Sneaky but awesome! I&apos;ll have to copy this later, but for now, let me see if I can just make things work.</p><p>I&apos;ll take inspiration from Holy Lambda and set the classpath explicitly, so the first thing to do is figure out what the classpath should be. Luckily, I know how to calculate a classpath: <code>clj -Spath</code>. In fact, my <code>build-deps</code> code is already using for its side effect of downloading dependencies, so all I have to do is capture its output. I already noticed that <code>babashka.deps/clojure</code> is printing the classpath to standard output, so if I wrap this in a <a href="https://clojuredocs.org/clojure.core/with-out-str"><code>with-out-str</code></a>, I&apos;m all good:</p><pre><code class="language-clojure">(let [classpath
      (with-out-str
        (clojure [&quot;-Spath&quot;]
                 {:dir work-dir
                  :env (assoc (into {} (System/getenv))
                              &quot;GITLIBS&quot; (str gitlibs-dir))}))]
  (println &quot;Classpath:&quot; classpath)
  ;; ...
)
</code></pre><p>Running <code>bb build-deps --deps-path ../s3-log-parser/src/bb.edn</code>, I see:</p><pre><code class="language-text">Classpath: src:~/.work/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...
</code></pre><p>and so on. Cool! Now I have a classpath. The only problem with this is that it is an absolute path to my <code>.work</code> directory, and my dependencies are going to end up in <code>/opt</code> when I add my deps layer to my lambda. So I&apos;ll need to rewrite the classpath to say <code>/opt</code> everywhere it currently says <code>~/.work</code>. No worries, Clojure can do that:</p><pre><code class="language-clojure">(let [deps-base-dir (str (fs/path (fs/cwd) work-dir))
      classpath
      (with-out-str
        (clojure [&quot;-Spath&quot;]
                 {:dir work-dir
                  :env (assoc (into {} (System/getenv))
                              &quot;GITLIBS&quot; (str gitlibs-dir))}))
      deps-classpath (str/replace classpath deps-base-dir &quot;/opt&quot;)]
  (println &quot;Classpath before transforming:&quot; classpath)
  (println &quot;Classpath after transforming:&quot; deps-classpath)
  ;; ...
)
</code></pre><p>Running this gives me what I&apos;m looking for:</p><pre><code class="language-text">Classpath before transforming: src:~/.work/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...
Classpath after transforming: src:/opt/m2-repo/com/cognitect/aws/endpoints/1.1.12.206/endpoints-1.1.12.206.jar:...
</code></pre><p>Victory! 🎉</p><p>The next step is to pass that classpath along to Blambda so that it can set it when invoking <code>bb</code> in the custom runtime. I decided to write the classpath to a file that can be included in the deps layer, which Blambda will read when initialising the runtime:</p><pre><code class="language-clojure">(let [classpath-file (fs/file work-dir &quot;deps-classpath&quot;)
      deps-base-dir (str (fs/path (fs/cwd) work-dir))
      classpath
      (with-out-str
        (clojure [&quot;-Spath&quot;]
                 {:dir work-dir
                  :env (assoc (into {} (System/getenv))
                              &quot;GITLIBS&quot; (str gitlibs-dir))}))
      deps-classpath (str/replace classpath deps-base-dir &quot;/opt&quot;)]
  (println &quot;Classpath before transforming:&quot; classpath)
  (println &quot;Classpath after transforming:&quot; deps-classpath)
  (spit classpath-file deps-classpath)

  (println &quot;Compressing custom runtime layer:&quot; deps-zipfile)
  (let [{:keys [exit err]}
        (sh &quot;zip&quot; &quot;-r&quot; deps-zipfile
            (fs/file-name gitlibs-dir)
            (fs/file-name m2-dir)
            (fs/file-name classpath-file)
            :dir work-dir)]
    (when (not= 0 exit)
      (println &quot;Error:&quot; err))))
</code></pre><p>When the deps layer is unzipped on the lambda instance, I&apos;ll have a file named <code>/opts/deps-classpath</code> containing the transformed classpath. Now all I have to do is update Blambda&apos;s <code>bootstrap</code> script to use the file if it&apos;s there:</p><pre><code class="language-bash">#!/bin/sh

set -e

LAYERS_DIR=/opt
DEPS_CLASSPATH_FILE=&quot;$LAYERS_DIR/deps-classpath&quot;

CLASSPATH=$LAMBDA_TASK_ROOT
if [ -e $DEPS_CLASSPATH_FILE ]; then
  CLASSPATH=&quot;$CLASSPATH:`cat $DEPS_CLASSPATH_FILE`&quot;
fi

export BABASHKA_DISABLE_SIGNAL_HANDLERS=&quot;true&quot;
export BABASHKA_PODS_DIR=$LAYERS_DIR/.babashka/pods
export GITLIBS=$LAYERS_DIR/gitlibs

echo &quot;Starting Babashka:&quot;
echo &quot;$LAYERS_DIR/bb -cp $CLASSPATH $LAYERS_DIR/bootstrap.clj&quot;

$LAYERS_DIR/bb -cp $CLASSPATH $LAYERS_DIR/bootstrap.clj
</code></pre><p>Now the classpath will always start with <code>$LAMBDA_TASK_ROOT</code>, which is the directory where the lambda zipfile is extracted (<code>/var/task</code>), and then if there exists an <code>/opt/deps-classpath</code> file, its contents will be appended to the classpath.</p><p>Invoking <code>bb</code> with the <code>-cp</code> flag overrides the default classpath and stops Babashka from building the classpath from <code>bb.edn</code>. This also means that there&apos;s no need to include a <code>bb.edn</code> in the lambda archive, which saves precious bytes! 😉</p><p>After running <code>bb deploy</code> to deploy the new version of the Blambda custom runtime and creating a new version of my deps layer with <code>target/deps.zip</code>, I held my breath and clicked the <strong>Test</strong> button once again:</p><p>![The lambda console showing a successful test result][blambda]</p><p>Victory! 🎉</p><p>Of course, there&apos;s a lot that is pretty yucky about this. The yuckiest bit is probably that I have to build and deploy Blambda from the Blambda repo, build the deps layer from the Blambda repo, but deploy the deps layer and build and deploy the lambda archive itself from the s3-log-parser repo. Gross. Will fix.</p><p>[blambda]:[assets/2022-08-09-blambda.png &quot;Such logs!&quot;]</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-16-portrait-of-the-coder.html</id>
    <link href="https://jmglov.net/blog/2022-07-16-portrait-of-the-coder.html"/>
    <title>A portrait of the coder as a young(-ish) man</title>
    <updated>2022-07-16T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>It&apos;s gonna be another short one today (#📞-it-📥), as I have 55 minutes to write this post, take a shower, and walk to the bus stop so I can head into town to meet my friend Jordan for a visit to <a href="https://www.fotografiska.com/sto">Fotografiska</a>, a cool museum of photography.</p><p>I&apos;ve been <a href="tags/blog.html">hacking quite a bit on my blog</a> over the last few days, but it&apos;s been behind the scenes stuff that speeds things up for me when I publish a new post, so it&apos;s probably not very exciting unless you&apos;re a Clojure programmer, in which case it&apos;s absolutely gripping stuff. Maybe. Probably not. But perhaps.</p><p>Clojure impressario <a href="https://github.com/borkdude">borkdude</a> (borkiest of all dudes, let me assure you) got sick and tired of less borky dudes like myself forking <a href="https://github.com/borkdude/blog">his blog</a>, so he wrapped it up as a library and dubbed it <a href="https://github.com/borkdude/quickblog">quickblog</a>!</p><p><a href="https://twitter.com/borkdude/status/1547912740156583936"><img alt="Tweet with demo of blog rendering. Tweet reads: Announcing quickblog, a
light-weight static blog engine for Clojure and Babashka!" src="assets/2022-07-16-quickblog.png" title="Like a blog, but quicker!" /></a></p><p>Since I&apos;ve done various things to the blog since forking it, I&apos;ve been hard at work folding the useful stuff back into quickblog so that it will render this blog and I can flush my hacky hacks down the toilet of history where they belong. 😉</p><p>It&apos;s been loads of fun working with borkdude on this. I haven&apos;t really collaborated on code with someone else since my friend Joanna and I wrote version 2 of the components system for the Core Banking Platform at work a year and a half or so ago, and it&apos;s something that I didn&apos;t know I was missing until I started doing it again.</p><p>I like Clojure the programming language, but I don&apos;t think I would have stuck with it for 10 years or however long it&apos;s been (I bought the first edition of &quot;[Programming
Clojure]&quot;(<a href="https://pragprog.com/titles/shcloj3/programming-clojure-third-edition/">https://pragprog.com/titles/shcloj3/programming-clojure-third-edition/</a>) when it was published back in 2008, but I didn&apos;t start using Clojure for anything more than playing around in the REPL--mainly translating exercises from &quot;<a href="https://mitpress.mit.edu/books/little-schemer-fourth-edition">The Little
Schemer</a>&quot; to Clojure, truth be told--until around 2012, when I write a terribly awful system test framework for an adserver at work) if it wasn&apos;t for Clojure the community, especially the amazing European Clojurists who I used to run into at various conferences around the continent before The End Times. Speaking of which, <a href="https://clojuredays.org/">Dutch
Clojure Days</a> is back this year at the end of October, so I hope to see some of you in Amsterdam! 😀</p><p>Anyway, I&apos;ll let y&apos;all know when quickblog is successfully rendering this blog, and until then, I&apos;ll let y&apos;all go.</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-15-hacking-blog-actually-caching.html</id>
    <link href="https://jmglov.net/blog/2022-07-15-hacking-blog-actually-caching.html"/>
    <title>Hacking the blog: actually caching</title>
    <updated>2022-07-15T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>When last we left our intrepid blogger (me), he (I) had just <a href="2022-07-14-hacking-blog-repl.html">admitted that
there was a bug</a> in his (my) caching code. 😢</p><p>But never fear! He (I) grabbed some <a href="https://melreams.com/2017/05/rich-hickey-hammock-driven-development/">hammock
time</a>, then grabbed his (my) trusty REPL, then set about decomplecting the caching code to make it Rich compliant. This post will detail the outcome of that decomplecting.</p><p>OK, I&apos;m getting tired of switching from third to first person, so let me settle on one from here on out: second person! No, that would be horribly confusing to you (me), so perhaps first person would be the right person.</p><p>To explain the caching strategy I landed on, let me recap the three categories of staleness that I identified:</p><ol start="1"><li>Files that only depend on themselves: assets and stylesheet</li><li>Files that depend on themselves, the templates, and the rendering system: post pages</li><li>Files that depend on posts, templates, and the rendering system: archive page, index page, tag pages, and RSS feeds</li></ol><p>Let&apos;s start at the top of <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/render_blog.clj"><code>render_blog.clj</code></a> and walk through how we handle each of these.</p><div class="markdown-heading"><h2 id="assets-and-stylesheet">Assets and stylesheet</h2><a href="#assets-and-stylesheet" class="anchor" aria-label="Permalink: Assets and stylesheet"><img src="assets/link.svg" /></a></div><p>This has not changed from my <a href="2022-07-11-hacking-blog-caching.html">original caching
strategy</a>:</p><pre><code class="language-clojure">(lib/copy-tree-modified (fs/file blog-dir &quot;assets&quot;)
                        asset-dir
                        (.getParent out-dir))

(let [style-src (fs/file templates-dir &quot;style.css&quot;)
      style-target (fs/file out-dir &quot;style.css&quot;)]
  (lib/copy-modified style-src style-target))
</code></pre><div class="markdown-heading"><h2 id="posts">Posts</h2><a href="#posts" class="anchor" aria-label="Permalink: Posts"><img src="assets/link.svg" /></a></div><p>Now that we don&apos;t use <code>posts.edn</code> anymore, posts are loaded like this:</p><pre><code class="language-clojure">(def posts (-&gt;&gt; (lib/load-posts posts-dir default-metadata)
                (lib/add-modified-metadata posts-dir out-dir)))
</code></pre><p><a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L114"><code>lib/load-posts</code></a> is similar to how it worked <a href="https://github.com/jmglov/jmglov.net/blob/54f030bbb04e4f07f9e6fb512bdf99ae28753fd7/lib.clj#L114">back in the <code>posts.edn</code>
days</a>, except instead of returning a list of post metadata, it returns a list of maps containing both the metadata and the actual rendered markdown for each post. Let&apos;s have a look:</p><pre><code class="language-clojure">(defn load-posts
  &quot;Returns all posts from `post-dir` in descending date order&quot;
  [posts-dir default-metadata]
  (-&gt;&gt; (fs/glob posts-dir &quot;*.md&quot;)
       (map #(load-post (.toFile %) default-metadata))
       (remove
        (fn [{:keys [metadata]}]
          (when-let [missing-keys
                     (seq (set/difference required-metadata
                                          (set (keys metadata))))]
            (println &quot;Skipping&quot; (:file metadata)
                     &quot;due to missing required metadata:&quot;
                     (str/join &quot;, &quot; (map name missing-keys)))
            :skipping)))
       (sort-by (comp :date :metadata) (comp - compare))))
</code></pre><p>So instead of reading <code>posts.edn</code>, we now do the following:</p><ul><li>Call <a href="https://babashka.org/fs/codox/babashka.fs.html#var-glob"><code>fs/glob</code></a> to list all Markdown files in the posts directory</li><li>Map over these with <code>load-post</code>, which we&apos;ll look at in a minute (note that <code>fs/glob</code> returns a list of <code>sun.nio.fs.UnixPath</code> objects, and <code>load-file</code> wants a <code>java.io.File</code>, so we need to call <code>.toFile</code> here)</li><li>Remove the posts that don&apos;t have the required metadata keys (<code>:date</code> and <code>:title</code>), since we won&apos;t be able to render them</li><li>Sort by date, reversing the order so that we get the most recent posts first</li></ul><p>Now let&apos;s look into <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L102"><code>lib/load-post</code></a> to see what this new post data structure looks like:</p><pre><code class="language-clojure">(defn load-post
  [file default-metadata]
  {:html (delay (markdown-&gt;html file))
   :metadata (do
               (println &quot;Reading metadata for file:&quot; (str file))
               (-&gt; (slurp file)
                   md/md-to-meta
                   (transform-metadata default-metadata)
                   (assoc :file (.getName file))))})
</code></pre><p>The first thing that stands out here is that we&apos;re returning a map with keys <code>:html</code> and <code>:metadata</code>, rather than returning the metadata map directly like <code>posts.edn</code> did. Let&apos;s look first at the value of the <code>:metadata</code> key:</p><pre><code class="language-clojure">(do
  (println &quot;Reading metadata for file:&quot; (str file))
  (-&gt; (slurp file)
      md/md-to-meta
      (transform-metadata default-metadata)
      (assoc :file (.getName file))))
</code></pre><p>We&apos;re reading in the file with <a href="https://clojuredocs.org/clojure.core/slurp"><code>slurp</code></a>, then feeding it to markdown-clj&apos;s <a href="https://github.com/yogthos/markdown-clj#metadata"><code>md-to-meta</code></a> function. If you recall from <a href="2022-07-14-hacking-blog-repl.html">Hacking the blog: REPLing to
victory</a>, we are now <a href="https://github.com/fletcher/MultiMarkdown/wiki/MultiMarkdown-Syntax-Guide#metadata">adding
metadata</a> to our Markdown files by starting the files like this:</p><pre><code class="language-markdown">Title: Hacking the blog: REPLing to victory
Date: 2022-07-14
Tags: clojure,blog,babashka

One of the [things I learned on Tuesday](2022-07-12-stuff-i-learned.html) was...
</code></pre><p>The <code>md-to-meta</code> function just reads in and parses the metadata, without rendering the Markdown itself. The reason why we&apos;re decomplecting parsing metadata from rendering Markdown here is that parsing metadata is ⚡fast⚡, whereas rendering Markdown is (relatively) 🐢slow🐢. Also cuz Rich Hickey sez so, of course. 😉</p><p>After reading in the metadata, we transform it with <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L63"><code>transform-metadata</code></a>:</p><pre><code class="language-clojure">(def metadata-transformers
  {:default first
   :tags #(-&gt; % first (str/split #&quot;,\s*&quot;) set)})

(defn transform-metadata
  [metadata default-metadata]
  (-&gt;&gt; metadata
       (map (fn [[k v]]
              (let [transformer (or (metadata-transformers k)
                                    (metadata-transformers :default))]
                [k (transformer v)])))
       (into {})
       (merge default-metadata)))
</code></pre><p><code>md-to-meta</code> returns a list of values for each key, since MultiMarkdown allows including a key multiple times, so you can say something like:</p><pre><code class="language-markdown">Author: Some Awesome Person
Author: Some Equally Awesome Person
</code></pre><p>That&apos;s why our default metadata transformer is <a href="https://clojuredocs.org/clojure.core/first"><code>first</code></a>, so it turns a list of one value into just the value.</p><p>Tags are slightly more complicated, since the way I have chosen to represent them is a comma-delimited list. That&apos;s why the transformer first uses <code>first</code> to get the value, then uses <a href="https://clojuredocs.org/clojure.string/split"><code>clojure.string/split</code></a> to turn the comma-delimited string into a list of tags, then uses <a href="https://clojuredocs.org/clojure.core/set"><code>set</code></a> to turn that list into a set, since the order of tags doesn&apos;t matter.</p><p>Finally, <code>transform-metadata</code> turns the list of pairs returned by <a href="https://clojuredocs.org/clojure.core/map"><code>map</code></a> back into a hashmap, then merges it with <code>default-metadata</code>, which I haven&apos;t talked about before, but is passed in from <code>render_blog.clj</code> and looks like this:</p><pre><code class="language-clojure">(def default-metadata
  {:author &quot;Josh Glover&quot;
   :copyright &quot;cc/by-nc/4.0&quot;})
</code></pre><p>The point of this is so that I don&apos;t have to include the author and copyright at the top of every file.</p><p>The last thing that <code>load-post</code> needs to do to the metadata is to add the post&apos;s filename, which is useful for all sorts of reasons that we&apos;ll see later on.</p><p>OK, that covers building the metadata for a post, so now let&apos;s turn our roving eye to the content:</p><pre><code class="language-clojure">(defn load-post
  [file default-metadata]
  {:html (delay (markdown-&gt;html file))
   :metadata (do :stuff)})
</code></pre><p>This <a href="https://clojuredocs.org/clojure.core/delay"><code>delay</code></a> looks kind of interesting, but let&apos;s ignore it for now and look at <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L93"><code>markdown-&gt;html</code></a> first:</p><pre><code class="language-clojure">(defn markdown-&gt;html [file]
  (let [markdown (slurp file)]
    (println &quot;Processing markdown for file:&quot; (str file))
    (-&gt; markdown
        pre-process-markdown
        (md/md-to-html-string-with-meta :reference-links? true)
        :html
        post-process-markdown)))
</code></pre><p>After we slurp in the file, we feed it to the <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L75"><code>pre-process-markdown</code></a> function:</p><pre><code class="language-clojure">(defn pre-process-markdown [markdown]
  (-&gt; markdown
      h/highlight-clojure
      ;; make links without markup clickable
      (str/replace #&quot;http[A-Za-z0-9/:.=#?_-]+([\s])&quot;
                   (fn [[match ws]]
                     (format &quot;[%s](%s)%s&quot;
                             (str/trim match)
                             (str/trim match)
                             ws)))
      ;; allow links with markup over multiple lines
      (str/replace #&quot;\[[^\]]+\n&quot;
                   (fn [match]
                     (str/replace match &quot;\n&quot; &quot;$$RET$$&quot;)))))
</code></pre><p>This is some super-duper <a href="https://github.com/borkdude">borkdude</a> magic which I copied with pride that adds syntax highlighting to Clojure code blocks like the one above, and also makes links a bit nicer.</p><p>After enriching the Markdown, we render it to HTML by using markdown-clj&apos;s <code>md-to-html-string-with-meta</code> function, which returns a map with keys <code>:metadata</code> and <code>:html</code>. Since we handle the metadata separately, all we care about is the value of the <code>:html</code> key. The final thing we need to do is to send it on to <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L90"><code>post-process-markdown</code></a> to finish the job that <code>pre-process-markdown</code> started:</p><pre><code class="language-clojure">(defn post-process-markdown [html]
  (str/replace html &quot;$$RET$$&quot; &quot;\n&quot;))
</code></pre><p>OK, back to that mysterious <code>delay</code> (as an aside, my wife&apos;s name is Delyana, so whenever I try to type &quot;delay&quot;, my fingers produce &quot;delya&quot; instead, kind of like when I try to type my friend Linus&apos;s name and always type &quot;Linux&quot; instead). What <code>delay</code> does is:</p><blockquote><p>Takes a body of expressions and yields a <code>Delay</code> object that will invoke the body only the first time it is forced (with <code>force</code> or <code>deref</code>/<code>@</code>), and will cache the result and return it on all subsequent <code>force</code> calls.</p></blockquote><p>The reason we want to delay evaluation of <code>markdown-&gt;html</code> is that rendering Markdown is two orders of magnitude more expensive than simply parsing the metadata:</p><pre><code class="language-clojure">(let [file (fs/file &quot;blog&quot; &quot;posts&quot; &quot;2022-07-15-hacking-blog-actually-caching.md&quot;)]
  (time
   (do
     (println &quot;Processing metadata for file&quot; (str file))
     (-&gt; (slurp file)
         md/md-to-meta
         (transform-metadata {})
         (assoc :file (.getName file)))))

  (time (markdown-&gt;html file)))

;; Processing metadata for file blog/posts/2022-07-15-hacking-blog-actually-caching.md
;; &quot;Elapsed time: 1.210838 msecs&quot;
;; Processing markdown for file: blog/posts/2022-07-15-hacking-blog-actually-caching.md
;; &quot;Elapsed time: 841.44889 msecs&quot;
</code></pre><p>If the post hasn&apos;t changed since last it was rendered, we won&apos;t need to render it (this is a tiny lie, but more on that later), so delaying evaluation lets us return right away but allow access to the rendered HTML when needed, as we shall see.</p><p>Whew, that was a lot! The reason that we wanted to look at how posts are loaded is so that we can understand how they can be cached. If we look back at <code>render.clj</code>, we&apos;ll see that there&apos;s a second step in loading the posts:</p><pre><code class="language-clojure">(def posts (-&gt;&gt; (lib/load-posts posts-dir default-metadata)
                (lib/add-modified-metadata posts-dir out-dir)))
</code></pre><p>Let&apos;s look at what <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L132"><code>lib/add-modified-metadata</code></a> is doing:</p><pre><code class="language-clojure">(defn add-modified-metadata
  &quot;Adds :modified? to each post showing if it is new or modified more recently than `out-dir`&quot;
  [posts-dir out-dir posts]
  (let [post-files (map #(fs/file posts-dir (get-in % [:metadata :file])) posts)
        html-file-exists? #(-&gt;&gt; (get-in % [:metadata :file])
                                lib/html-file
                                (fs/file out-dir)
                                fs/exists?)
        new-posts (-&gt;&gt; (remove html-file-exists? posts)
                       (map (comp :file :metadata))
                       set)
        modified-posts (-&gt;&gt; post-files
                            (fs/modified-since out-dir)
                            (map #(str (.getFileName %)))
                            set)
        new-or-modified-posts (set/union new-posts modified-posts)]
    (map #(assoc-in %
                    [:metadata :modified?]
                    (contains? new-or-modified-posts
                               (get-in % [:metadata :file])))
         posts)))
</code></pre><p>OK, there is a lot going on here at first glance, but it isn&apos;t really as complicated as it might look. Let&apos;s walk through it step by step:</p><ol start="1"><li>Get the filenames of each post by grabbing the <code>:file</code> key from its metadata</li><li>Define a function <code>html-file-exists?</code> that constructs the filename of the HTML file that will be written once the post is rendered and processed by the <a href="https://github.com/yogthos/Selmer">Selmer</a> templating system, then checks if that file exists</li><li>Create a set of new posts by removing the posts for which <code>html-file-exists?</code> is true</li><li>Create a set of modified posts by using <code>fs/modified-since</code> to grab the posts that have been modified more recently than the output directory, then map them over <code>#(str (.getFilename %))</code> to turn the path into a regular old filename</li><li>Create a set of new or modified posts by taking the union of the two sets</li><li>Map over the posts with a function that checks whether each post&apos;s filename exists in the set of new or modified files and saves the result in the post&apos;s metadata under the <code>:modified</code> key</li></ol><p>So running this on a list of posts would yield something like this:</p><pre><code class="language-clojure">(-&gt;&gt; (lib/load-posts posts-dir default-metadata)
     (take 2)
     (lib/add-modified-metadata posts-dir out-dir))
;; =&gt; ({:html #&lt;Delay@78c390f1: :not-delivered&gt;,
;;      :metadata
;;      {:author &quot;Josh Glover&quot;,
;;       :copyright &quot;cc/by-nc/4.0&quot;,
;;       :tags #{&quot;clojure&quot; &quot;blog&quot; &quot;babashka&quot;},
;;       :preview &quot;true&quot;,
;;       :title &quot;Hacking the blog: actually caching&quot;,
;;       :date &quot;2022-07-15&quot;,
;;       :file &quot;2022-07-15-hacking-blog-actually-caching.md&quot;,
;;       :modified? true}}
;;     {:html #&lt;Delay@7393dd51: :not-delivered&gt;,
;;      :metadata
;;      {:author &quot;Josh Glover&quot;,
;;       :copyright &quot;cc/by-nc/4.0&quot;,
;;       :tags #{&quot;clojure&quot; &quot;blog&quot; &quot;babashka&quot;},
;;       :title &quot;Hacking the blog: REPLing to victory&quot;,
;;       :date &quot;2022-07-14&quot;,
;;       :file &quot;2022-07-14-hacking-blog-repl.md&quot;,
;;       :modified? false}})
</code></pre><p>Nice! Now that we have a list of posts with metadata telling us whether they have been modified, let&apos;s look at how the posts are rendered:</p><pre><code class="language-clojure">(def bodies (atom {}))  ; re-used when generating atom.xml

(doseq [post posts]
  (lib/write-post! {:page-template page-template
                    :bodies bodies
                    :discuss-fallback discuss-fallback
                    :out-dir out-dir
                    :post-template post-template
                    :posts-dir posts-dir
                    :rendering-system-files rendering-system-files}
                   post))
</code></pre><p>The important section of <a href="https://github.com/jmglov/jmglov.net/blob/6cc42e6927b1c0c2bd8621a01a774d5185608fa1/lib.clj#L199"><code>lib/write-post!</code></a> looks like this:</p><pre><code class="language-clojure">(if (or modified?
        (rendering-modified? rendering-system-files out-file))
  (let [body (selmer/render post-template {:body @html
                                           :title title
                                           :date date
                                           :discuss discuss
                                           :tags tags})
        rendered-html (render-page config page-template
                                   {:title title
                                    :body body})]
    (println &quot;Writing post:&quot; (str out-file))
    (spit out-file rendered-html)
    (let [legacy-dir (fs/file out-dir
                              (str/replace date &quot;-&quot; &quot;/&quot;)
                              (str/replace file &quot;.md&quot; &quot;&quot;))]))
  (println file &quot;not modified; using cached version&quot;))
</code></pre><p>If the post file itself has been modified or the rendering system has been modified, we call <code>selmer/render</code> with the <code>:body</code> template variable set to the result of <strong>dereferencing</strong> the post&apos;s <code>:html</code> key. Dereferencing forces the delayed evaluation to happen and gives us back the result, which in this case is calling <code>markdown-&gt;html</code> on the file contents of the post.</p><p>If the post hasn&apos;t been modified, there&apos;s no need to re-render the template, so we&apos;ll just notify the user of this fact, leave it alone, and move on with our life.</p><p>Alright, that covers posts, so now we can move onto...</p><div class="markdown-heading"><h2 id="archive-file">Archive file</h2><a href="#archive-file" class="anchor" aria-label="Permalink: Archive file"><img src="assets/link.svg" /></a></div><p>This one is quite a bit more straightforward: we only need to re-render the archive page if any post has changed or the rendering system has been modified more recently than the archive file was last rendered. Here&apos;s the code:</p><pre><code class="language-clojure">(let [archive-file (fs/file out-dir &quot;archive.html&quot;)
      rendering-modified? (lib/rendering-modified? rendering-system-files
                                                   archive-file)]
  (if (or rendering-modified? (lib/some-post-modified posts))
    (do
      (println &quot;Writing archive page&quot; (str archive-file))
      (spit archive-file
            (selmer/render page-template
                           {:skip-archive true
                            :title (str blog-title &quot; - Archive&quot;)
                            :body (hiccup/html (lib/post-links {} &quot;Archive&quot; posts))})))
    (println &quot;No posts modified; skipping archive file&quot;)))
</code></pre><p>The cool thing to note here is that the archive page doesn&apos;t use the contents of posts at all, only their metadata, so we never deference <code>:html</code>, thus never force a re-render of posts. This covers the case where we&apos;ve changed the name, date, or tags of a post, since those are the only things that appear in the archive page.</p><div class="markdown-heading"><h2 id="tags">Tags</h2><a href="#tags" class="anchor" aria-label="Permalink: Tags"><img src="assets/link.svg" /></a></div><p>For tags, we generate a page for each tag linking to all of the posts with that tag, and an index file linking to each tag:</p><pre><code class="language-clojure">(def posts-by-tag (lib/posts-by-tag posts))
(def tags-dir (fs/create-dirs (fs/file out-dir &quot;tags&quot;)))

(let [tags-file (fs/file tags-dir &quot;index.html&quot;)
      rendering-modified? (lib/rendering-modified? rendering-system-files
                                                   tags-dir)]
  (if (or rendering-modified? (lib/some-post-modified posts))
    (do
      (println &quot;Writing tags page&quot; (str tags-file))
      (spit tags-file
            (selmer/render page-template
                           {:skip-archive true
                            :title (str blog-title &quot; - Tags&quot;)
                            :relative-path &quot;../&quot;
                            :body (hiccup/html (lib/tag-links &quot;Tags&quot; posts-by-tag))}))
      (doseq [tag-and-posts posts-by-tag]
        (lib/write-tag! {:page-template page-template
                         :blog-title blog-title
                         :tags-dir tags-dir}
                        tag-and-posts)))
    (println &quot;No posts modified; skipping tag files&quot;)))
</code></pre><p>These pages only need to be written if any posts have changed or if the rendering system has been modified more recently than the <code>tags/</code> subdirectory of the output directory. Just like with the archive page, the tags pages only use the posts&apos; metadata, so re-rendering these pages won&apos;t force the posts themselves to be re-rendered.</p><div class="markdown-heading"><h2 id="index-page">Index page</h2><p>The top-level <code>index.html</code> page contains the <em>n</em> most recent posts (where <em>n = 3</em> for my blog), so it needs to be re-rendered if any of the <em>n</em> most recent posts have changed or the rendering system has been modified more recently than the index page was last written. The index page <strong>does</strong> use the rendered HTML from each post, but as <code>delay</code> caches its result, posts that have been modified will already have been written by <code>lib/write-post!</code>, so at least we won&apos;t double-render a post. 🎉</p><h2 id="rss-feeds">RSS feeds</h2><a href="#index-page">Index page</h2><p>The top-level <code>index.html</code> page contains the <em>n</em> most recent posts (where <em>n = 3</em> for my blog), so it needs to be re-rendered if any of the <em>n</em> most recent posts have changed or the rendering system has been modified more recently than the index page was last written. The index page <strong>does</strong> use the rendered HTML from each post, but as <code>delay</code> caches its result, posts that have been modified will already have been written by <code>lib/write-post!</code>, so at least we won&apos;t double-render a post. 🎉</p><h2 id="rss-feeds" class="anchor" aria-label="Permalink: RSS feeds"><img src="assets/link.svg" /></a></div><p>We write two RSS feeds for the blog, one specific to <a href="http://planet.clojure.in/">Planet
Clojure</a> which contains only posts tagged with &quot;clojure&quot; or &quot;clojurescript&quot;, and one containing all posts.</p><p>These feeds are just like the archive, tag, and index pages in that they only need to be regenerated when any post has changed or when the rendering system has been modified more recently than each RSS feed file:</p><pre><code class="language-clojure">(let [feed-file (fs/file out-dir &quot;atom.xml&quot;)
      clojure-feed-file (fs/file out-dir &quot;planetclojure.xml&quot;)
      clojure-posts (filter
                     (fn [{:keys [metadata]}]
                       (some (:tags metadata) [&quot;clojure&quot; &quot;clojurescript&quot;]))
                     posts)]
  (if (or (lib/rendering-modified? rendering-system-files clojure-feed-file)
          (lib/some-post-modified clojure-posts))
    (do
      (println &quot;Writing Clojure feed&quot; (str clojure-feed-file))
      (spit clojure-feed-file
            (atom-feed clojure-posts)))
    (println &quot;No Clojure posts modified; skipping Clojure feed&quot;))
  (if (or (lib/rendering-modified? rendering-system-files feed-file)
          (lib/some-post-modified posts))
    (do
      (println &quot;Writing feed&quot; (str feed-file))
      (spit feed-file
            (atom-feed posts)))
    (println &quot;No posts modified; skipping main feed&quot;)))
</code></pre><p>Note that the Clojure feed is only re-rendered when one of the Clojure posts changes, so me writing a post about the <a href="2022-07-10-hands-off-womens-football.html">Women&apos;s EURO
2022</a> won&apos;t cause the Clojure feed to be regenerated.</p><p>And that&apos;s all there is to it! Let&apos;s see what happens if we render our blog from scratch:</p><pre><code>[jmglov@laurana:~/Documents/code/jmglov.net]$ bb clean
[jmglov@laurana:~/Documents/code/jmglov.net]$ time bb render-blog
Reading metadata for file: blog/posts/2022-07-06-hacking-blog-categories.md
Reading metadata for file: blog/posts/2022-06-17-creating-a-blog-with-clojure.md
Reading metadata for file: blog/posts/2022-07-12-stuff-i-learned.md
[...]
Writing public/blog/assets/2022-06-29-rover-cake.jpg
Writing public/blog/assets/2022-07-10-reverse-sexism.png
Writing public/blog/assets/2022-07-10-all-for-it.png
[...]
Writing public/blog/style.css
Processing markdown for file: blog/posts/2022-07-15-hacking-blog-actually-caching.md
Writing post: public/blog/2022-07-15-hacking-blog-actually-caching.html
Processing markdown for file: blog/posts/2022-07-14-hacking-blog-repl.md
Writing post: public/blog/2022-07-14-hacking-blog-repl.html
Processing markdown for file: blog/posts/2022-07-13-omg-what-have-i-done.md
Writing post: public/blog/2022-07-13-omg-what-have-i-done.html
[...]
Writing archive page public/blog/archive.html
Writing tags page public/blog/tags/index.html
Writing tag page: public/blog/tags/football.html
Writing tag page: public/blog/tags/euro2022.html
[...]
Writing index page public/blog/index.html
Writing Clojure feed public/blog/planetclojure.xml
Writing feed public/blog/atom.xml

real	0m9.766s
user	0m8.987s
sys	0m0.116s
</code></pre><p>Ten whole seconds! 😭 But let&apos;s try rendering it again without making any changes:</p><pre><code>[jmglov@laurana:~/Documents/code/jmglov.net]$ time bb render-blog
Reading metadata for file: blog/posts/2022-07-06-hacking-blog-categories.md
Reading metadata for file: blog/posts/2022-06-17-creating-a-blog-with-clojure.md
Reading metadata for file: blog/posts/2022-07-12-stuff-i-learned.md
[...]
2022-07-15-hacking-blog-actually-caching.md not modified; using cached version
2022-07-14-hacking-blog-repl.md not modified; using cached version
2022-07-13-omg-what-have-i-done.md not modified; using cached version
[...]
No posts modified; skipping archive file
No posts modified; skipping tag files
None of the 3 most recent posts modified; skipping index page
No Clojure posts modified; skipping Clojure feed
No posts modified; skipping main feed

real	0m0.211s
user	0m0.153s
sys	0m0.058s
</code></pre><p>Even an impatient person like me is willing to wait 200 milliseconds for my blog to render. 😉</p><p>Let&apos;s try re-running it again with changes to just one post (the one I&apos;m typing right now):</p><pre><code>[jmglov@laurana:~/Documents/code/jmglov.net]$ time bb render-blog
Reading metadata for file: blog/posts/2022-07-06-hacking-blog-categories.md
Reading metadata for file: blog/posts/2022-06-17-creating-a-blog-with-clojure.md
Reading metadata for file: blog/posts/2022-07-12-stuff-i-learned.md
[...]
Processing markdown for file: blog/posts/2022-07-15-hacking-blog-actually-caching.md
Writing post: public/blog/2022-07-15-hacking-blog-actually-caching.html
2022-07-14-hacking-blog-repl.md not modified; using cached version
2022-07-13-omg-what-have-i-done.md not modified; using cached version
2022-07-12-stuff-i-learned.md not modified; using cached version
[...]
Writing archive page public/blog/archive.html
Writing tags page public/blog/tags/index.html
Writing tag page: public/blog/tags/football.html
Writing tag page: public/blog/tags/euro2022.html
[...]
Writing index page public/blog/index.html
Processing markdown for file: blog/posts/2022-07-14-hacking-blog-repl.md
Processing markdown for file: blog/posts/2022-07-13-omg-what-have-i-done.md
Writing Clojure feed public/blog/planetclojure.xml
Processing markdown for file: blog/posts/2022-07-11-hacking-blog-caching.md
Processing markdown for file: blog/posts/2022-07-06-hacking-blog-categories.md
Processing markdown for file: blog/posts/2022-07-05-hacking-blog-favicon.md
[...]
Writing feed public/blog/atom.xml
Processing markdown for file: blog/posts/2022-07-12-stuff-i-learned.md
Processing markdown for file: blog/posts/2022-07-10-hands-off-womens-football.md
Processing markdown for file: blog/posts/2022-07-09-story-of-a-mediocre-fan-4.md
[...]
Processing markdown for file: blog/posts/2022-06-15-summertime.md

real	0m9.701s
user	0m8.912s
sys	0m0.123s
</code></pre><p>Well 💩! Why is it taking nearly 10 seconds to render one post? I mean, things start out so well:</p><pre><code>[jmglov@laurana:~/Documents/code/jmglov.net]$ time bb render-blog
Reading metadata for file: blog/posts/2022-07-06-hacking-blog-categories.md
Reading metadata for file: blog/posts/2022-06-17-creating-a-blog-with-clojure.md
Reading metadata for file: blog/posts/2022-07-12-stuff-i-learned.md
[...]
Processing markdown for file: blog/posts/2022-07-15-hacking-blog-actually-caching.md
Writing post: public/blog/2022-07-15-hacking-blog-actually-caching.html
2022-07-14-hacking-blog-repl.md not modified; using cached version
2022-07-13-omg-what-have-i-done.md not modified; using cached version
2022-07-12-stuff-i-learned.md not modified; using cached version
</code></pre><p>but then devolve into sadness:</p><pre><code>Writing index page public/blog/index.html
Processing markdown for file: blog/posts/2022-07-14-hacking-blog-repl.md
Processing markdown for file: blog/posts/2022-07-13-omg-what-have-i-done.md
Writing Clojure feed public/blog/planetclojure.xml
Processing markdown for file: blog/posts/2022-07-11-hacking-blog-caching.md
Processing markdown for file: blog/posts/2022-07-06-hacking-blog-categories.md
Processing markdown for file: blog/posts/2022-07-05-hacking-blog-favicon.md
[...]
Writing feed public/blog/atom.xml
Processing markdown for file: blog/posts/2022-07-12-stuff-i-learned.md
Processing markdown for file: blog/posts/2022-07-10-hands-off-womens-football.md
Processing markdown for file: blog/posts/2022-07-09-story-of-a-mediocre-fan-4.md
[...]
Processing markdown for file: blog/posts/2022-06-15-summertime.md
</code></pre><p>Oh yeah, like I said, the index page needs the rendered HTML for the three most recent posts, which were <code>2022-07-15-hacking-blog-actually-caching.md</code>, <code>2022-07-14-hacking-blog-repl.md</code>, and <code>2022-07-13-omg-what-have-i-done</code>. Since <code>2022-07-15-hacking-blog-actually-caching.md</code> was actually modified, it was rendered by <code>lib/write-post!</code>, whereas the other two files weren&apos;t modified and thus weren&apos;t rendered until the index page tried to use them.</p><p>And then the Clojure feed needs all of the Clojure posts, which causes those to render, and then the main feed needs all of the posts, which causes them to render, meaning we&apos;ve now rendered all of our posts. 😭</p><p>But never fear! Since we succeeded in simplifying things, we have all of the pieces we need to fix this problem as well. However, I&apos;ve been writing and you&apos;ve been reading for quite some time now, so let&apos;s leave that for another day (and maybe another post, who knows?).</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-14-hacking-blog-repl.html</id>
    <link href="https://jmglov.net/blog/2022-07-14-hacking-blog-repl.html"/>
    <title>Hacking the blog: REPLing to victory</title>
    <updated>2022-07-14T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>One of the <a href="2022-07-12-stuff-i-learned.html">things I learned on Tuesday</a> was that I had a bug in the caching code on my blog (of course there&apos;s a bug in caching code; that is one of the few things you can count on in life). As any Clojure programmer would, I meditated upon the words of Rich Hickey and became enlightened. I must decomplect!</p><p>Let&apos;s look at what files are produced by my blog and what could cause them to become stale.</p><ul><li>Static assets (for example, images): the file itself is modified</li><li>Stylesheet: the file itself is modified</li><li>Posts: one of the following is modified:<ul><li>The entry in <a href="https://github.com/jmglov/jmglov.net/blob/575a12cf2a87a4fd2a46dc131ed3a51f864ba57f/blog/posts.edn"><code>posts.edn</code></a>, corresponding to a given post, since that means that some post metadata such as title, date, tags, or filename may have changed</li><li>The Markdown file for a given post</li><li>A template file</li><li>Any Clojure file that is responsible for rendering:<ul><li><a href="https://github.com/jmglov/jmglov.net/blob/main/render_blog.clj"><code>render_blog.clj</code></a></li><li><a href="https://github.com/jmglov/jmglov.net/blob/main/lib.clj"><code>lib.clj</code></a></li><li>The version of <a href="https://github.com/weavejester/hiccup">Hiccup</a>, <a href="https://github.com/yogthos/markdown-clj">markdown-clj</a>, or <a href="https://github.com/yogthos/Selmer">Selmer</a>. I had not thought of this before. Since this is a bit tricky, let&apos;s just use <a href="https://github.com/jmglov/jmglov.net/blob/main/deps.edn"><code>deps.edn</code></a> as a proxy for this, since all of these dependencies are specified there.</li></ul></li></ul></li><li>Archive page:<ul><li>A template file</li><li>The Markdown file for any post, since the title or filename may have changed</li><li>Any Clojure file that is responsible for rendering</li></ul></li><li>Tags index and tag-specific pages:<ul><li>A template file</li><li>The Markdown file for any post, since the title, filename, or tags may have changed</li><li>Any Clojure file that is responsible for rendering</li></ul></li><li>Archive page:<ul><li>A template file</li><li>The Markdown file for any post, since the title or filename may have changed</li><li>Any Clojure file that is responsible for rendering</li></ul></li></ul><p>This simplifies matters quite a bit, because we only have three categories here:</p><ol start="1"><li>Files that only depend on themselves</li><li>Files that depend on themselves, the templates, and the rendering system</li><li>Files that depend on posts, templates, and the rendering system</li></ol><p>Category 1 is already simple (in the Hickian sense of the word), and in fact already works with my initial approach. Category 2 only applies to posts, which in fact category 3 depends on, so let&apos;s focus on getting category 2 working before we turn our attention to category 3.</p><p>Category 2 is definitely complex, since there are four separate things that should trigger a re-render for a given post:</p><ol start="1"><li>Its entry in <code>posts.edn</code></li><li>Its Markdown file</li><li>Any template (to be on the safe side)</li><li>The rendering system</li></ol><p>One obvious irritation is that the post&apos;s metadata and content come from different files. It would be simpler if the metadata was contained in the same file as the post, so that all we have to do to determine if the post needs to be re-rendered is to check if the Markdown file has been modified.</p><p>Luckily, there is a solution for this! <a href="https://github.com/fletcher/MultiMarkdown/wiki/MultiMarkdown-Syntax-Guide">MultiMarkdown</a>—which is the flavour of Markdown implemented by markdown-clj—has an affordance for including <a href="https://github.com/fletcher/MultiMarkdown/wiki/MultiMarkdown-Syntax-Guide#metadata">metadata</a> in a Markdown file. If you start your Markdown file like this:</p><pre><code>Title: Hacking the blog: REPLing to victory
Date: 2022-07-14
Tags: clojure,blog,babashka

Content starts here.
</code></pre><p>you are defining <code>Title</code>, <code>Date</code>, and <code>Tags</code> metadata.</p><p>markdown-clj supports this through the gloriously named <a href="https://github.com/yogthos/markdown-clj#metadata"><code>md-to-html-string-with-meta</code></a> function. Whereas the normal <code>md-to-html-string</code> function returns an HTML string, <code>md-to-html-string-with-meta</code> returns a map with keys <code>:metadata</code> and <code>:html</code>. I&apos;ll go into more details on this in a future post, but for now, I want to focus on the problem of moving the metadata from <code>posts.edn</code> to each Markdown file.</p><p>There is the obvious approach of doing it manually, which I would have chosen if I had just a few posts, but since I have 31 now, that would both take more time than I care to spend and also be rife with opportunities for manual errors.</p><p>So automation it is! Since <a href="https://github.com/babashka/babashka">Babashka</a> was initially developed to allow us to write shell scripts in Clojure instead of Bash (or some other icky language like Python), it&apos;s an obvious choice for automating this. And since I&apos;m using Clojure, I can skip the whole trial and error thing by using a technique we call REPL-driven development.</p><p>REPL-driven development basically boils down to constantly evaluating code in the context of our running program to try things out, rather than writing some code, running the program, watching it fail, scratching our heads, adding some debug print statements, re-running the program, watching it fail, reading the debug output, realising that we need a debug print in a place we didn&apos;t think of, adding it, re-running the program, reading the debug output, scratching our heads, changing the code, re-running the program, watching it fail in a different way...</p><p>If that last paragraph was tedious to read, you can imagine how tedious it is to actually do things this way! Or more likely, you don&apos;t have to imagine, because you&apos;ve done things this way many many times.</p><p>So let me walk you through the actual REPL session I used to transform my files.</p><p>Since I&apos;m using Emacs and <a href="https://docs.cider.mx/cider/index.html">CIDER</a>, I&apos;ll be REPLing right in my editor, which is the superpower of the Clojure ecosystem. Many languages have a primitive REPL where you can execute code, but most don&apos;t integrate with your editor in any meaningful way (Elixir is an absolutely delightful exception to this rule 💜).</p><p>In order to enable this goodness, I need to start a Babashka REPL:</p><pre><code>bb nrepl-server 1667
</code></pre><p>Now, I open <code>lib.clj</code> in Emacs and run the <code>cider-connect</code> function, entering <code>localhost</code> and <code>1667</code> when prompted for host and port. CIDER will then open a REPL buffer and print something like this:</p><pre><code>;; Connected to nREPL server - nrepl://localhost:1667
;; CIDER 1.3.0 (Ukraine), babashka.nrepl 0.0.6-SNAPSHOT
;; Babashka 0.8.156
;;     Docs: (doc function-name)
;;           (find-doc part-of-name)
;;   Source: (source function-name)
;;  Javadoc: (javadoc java-object-or-class)
;;     Exit: &lt;C-c C-q&gt;
;;  Results: Stored in vars *1, *2, *3, an exception in *e;
WARNING: Can&apos;t determine Clojure version.  The refactor-nrepl middleware requires clojure 1.8.0 (or newer)WARNING: clj-refactor and refactor-nrepl are out of sync.
Their versions are 3.5.2 and n/a, respectively.
You can mute this warning by changing cljr-suppress-middleware-warnings.
user&gt; 
</code></pre><p>Now I can evaluate Clojure forms in the REPL!</p><pre><code>user&gt; (+ 1 2)
;; =&gt; 3
</code></pre><p>This is cool, but no cooler than the REPLs that I called &quot;primitive&quot; a minute ago. To move from merely cool to totally awesome, I&apos;ll switch back to my <code>lib.clj</code> file and hit <code>C-c C-k</code> (that&apos;s Emacs-speak for Control + c followed by Control + k), which runs the <code>cider-load-buffer</code> Emacs function, which evaluates the entire file in your running REPL process. Now I can write code in the file and evaluate it straight away!</p><p>I&apos;ll start by writing a so-called <a href="https://betweentwoparens.com/blog/rich-comment-blocks/#rich-comment">Rich
comment</a>:</p><pre><code class="language-clojure">(comment

  )
</code></pre><p>The <code>comment</code> macro is a nice way to comment out some code in a way that allows for <a href="https://practical.li/spacemacs/structural-editing/">structural editing</a>, but it has a hidden superpower when combined with a REPL: you can evaluate code inside the comment block, safe in the knowledge that it won&apos;t be evaluated when the file is loaded in a real program (or when you press <code>C-c C-k</code> to re-evaluate the entire file).</p><p>So now I&apos;m ready to rapidly iterate. Let me just remember what I&apos;m trying to do again... oh yeah, move the metadata in the <code>posts.edn</code> file to the file for each post.</p><p>I can start by loading <code>posts.edn</code> and seeing what it looks like. I have a function called <code>load-posts</code> that loads the <code>posts.edn</code> file, so let&apos;s call it and see what it returns. What I can do is write some code inside my comment block:</p><pre><code class="language-clojure">(comment
  (-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
       first)

  )
</code></pre><p>and then put my cursor at the end of the line ending with <code>first)</code> and press <code>C-c C-v f c e</code>, which runs the Emacs function <code>cider-pprint-eval-last-sexp-to-comment</code>, which does this:</p><pre><code class="language-clojure">(comment
  (-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
       first)
  ;; =&gt; {:title &quot;Some stuff I learned today&quot;,
  ;;     :file &quot;2022-07-12-stuff-i-learned.md&quot;,
  ;;     :tags #{&quot;waffle&quot;},
  ;;     :date &quot;2022-07-12&quot;}

  )
</code></pre><p>What I&apos;ve done here is evaluated code in a file in my editor and had the result written right back to the file. No need to change windows, no need to copy and paste, no need to move my eyes or engage my brain; it&apos;s all just muscle memory!</p><p>OK, so now I know what a post metadata entry looks like. In order to write that metadata to the top of a file, I&apos;m going to need to read in the file. Let me try that out in my comment block and evaluate it:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map (fn [{:keys [file] :as post}]
            (let [contents (-&gt;&gt; file
                                (fs/file &quot;blog&quot; &quot;posts&quot;)
                                slurp)]
              (assoc post :contents contents))))
     first)
;; =&gt; {:title &quot;Some stuff I learned today&quot;,
;;     :file &quot;2022-07-12-stuff-i-learned.md&quot;,
;;     :tags #{&quot;waffle&quot;},
;;     :date &quot;2022-07-12&quot;,
;;     :contents
;;     &quot;Title: Some stuff I learned today\nTags: waffle\nDate: 2022-07-12\n\nToday...&quot;}
</code></pre><p>Cool, that worked! Now I need to figure out which metadata I want to write to the top of the file. From my example above, I want the title, the date, and the tags, so let me grab them and put them into the post data structure under a <code>:metadata</code> key:</p><pre><code class="language-clojure">(-&gt; (-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
         (map (fn [{:keys [file] :as post}]
                (let [contents (-&gt;&gt; file
                                    (fs/file &quot;blog&quot; &quot;posts&quot;)
                                    slurp)
                      metadata (dissoc post :file)]
                  (assoc post
                         :contents contents
                         :metadata metadata))))
         first
         :metadata))
;; =&gt; {:title &quot;Some stuff I learned today&quot;, :tags #{&quot;waffle&quot;}, :date &quot;2022-07-12&quot;}
</code></pre><p>Looking good! Now, according to the MultiMarkdown spec, metadata keys should look like <code>Title: Some title here</code> instead of <code>:title &quot;Some title here&quot;</code>. I&apos;ll try transforming the metadata to this format:</p><pre><code class="language-clojure">(-&gt; (-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
         (map (fn [{:keys [file] :as post}]
                (let [contents (-&gt;&gt; file
                                    (fs/file &quot;blog&quot; &quot;posts&quot;)
                                    slurp)
                      metadata (dissoc post :file)]
                  (assoc post
                         :contents contents
                         :metadata metadata))))
         first
         :metadata
         (map (fn [[k v]] (format &quot;%s: %s&quot; (str/capitalize (name k)) v)))))
;; =&gt; (&quot;Title: Some stuff I learned today&quot; &quot;Tags: #{\&quot;waffle\&quot;}&quot; &quot;Date: 2022-07-12&quot;)
</code></pre><p>Looks pretty good except for that <code>&quot;Tags: #{\&quot;waffle\&quot;}&quot;</code> bit, which is the result of Clojure stringifying the set of tags that were in <code>posts.edn</code>. I decide that if I encounter a metadata value that is a list or set like <code>#{&quot;thing1&quot; &quot;thing2&quot; &quot;thing3&quot;}</code>, I&apos;ll transform it into a comma-delimited string like <code>&quot;thing1,thing2,thing3&quot;</code>. Of course, I can never remember which function in Clojure to use for seeing if a thing is a list or a set, so I&apos;ll try a few things in the REPL until I find the right one:</p><pre><code class="language-clojure">(sequential? #{})
;; =&gt; false

(coll? #{})
;; =&gt; true
</code></pre><p>Oh right, it&apos;s <code>coll?</code> that I&apos;m after. Armed with this knowledge, I can try my metadata transformation once more:</p><pre><code class="language-clojure">(-&gt; (-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
         (map (fn [{:keys [file] :as post}]
                (let [contents (-&gt;&gt; file
                                    (fs/file &quot;blog&quot; &quot;posts&quot;)
                                    slurp)
                      metadata (dissoc post :file)]
                  (assoc post
                         :contents contents
                         :metadata metadata))))
         first
         :metadata
         (map (fn [[k v]]
                (let [v (if (coll? v) (str/join &quot;,&quot; v) v)]
                  (format &quot;%s: %s&quot; (str/capitalize (name k)) v))))))
;; =&gt; (&quot;Title: Some stuff I learned today&quot; &quot;Tags: waffle&quot; &quot;Date: 2022-07-12&quot;)
</code></pre><p>Looks better than before, but I&apos;d really like to see what it does to a post with more than one tag. Let me see if I have any such posts:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map #(count (:tags %))))
;; =&gt; (1 3 2 2 3 2 3 3 6 5 1 1 2 1 1 1 5 1 2 2 1 3 3 2 1 4 2 1)
</code></pre><p>Sure do! Now I&apos;ll grab the first such post:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (some #(and (&gt; (count (:tags %)) 1) %)))
;; =&gt; {:title &quot;Hacking the blog: caching&quot;,
;;     :file &quot;2022-07-11-hacking-blog-caching.md&quot;,
;;     :tags #{&quot;clojure&quot; &quot;blog&quot; &quot;babashka&quot;},
;;     :date &quot;2022-07-11&quot;}
</code></pre><p>This <code>(some #(and (&gt; (count (:tags %)) 1) %))</code> is a trick to get back the first item in a collection that matches a predicate. The <a href="https://clojuredocs.org/clojure.core/some"><code>some</code>
function</a> is somewhat odd in that it:</p><blockquote><p>Returns the first logical true value of (pred x) for any x in coll, else nil.</p></blockquote><p>If I just use the predicate, I get this:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (some #(&gt; (count (:tags %)) 1)))
;; =&gt; true
</code></pre><p>This is not very helpful, since it just tells me what I already know, that I have a post with more than one tag. Using <code>and</code> gives me a way to return the thing that I found, since I know that the thing I found (a post, in this case) is logically true in Clojure since it is not <code>nil</code> or <code>false</code>.</p><p>OK, now that I have a post with more than one tag, let me try my transformation logic on it and make sure it works:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map (fn [{:keys [file] :as post}]
            (let [contents (-&gt;&gt; file
                                (fs/file &quot;blog&quot; &quot;posts&quot;)
                                slurp)
                  metadata (dissoc post :file)]
              (assoc post
                     :contents contents
                     :metadata metadata))))
     (some #(and (&gt; (count (:tags %)) 1) %))
     :metadata
     (map (fn [[k v]]
            (let [v (if (coll? v) (str/join &quot;,&quot; v) v)]
              (format &quot;%s: %s&quot; (str/capitalize (name k)) v)))))
;; =&gt; (&quot;Title: Hacking the blog: caching&quot;
;;     &quot;Tags: clojure,blog,babashka&quot;
;;     &quot;Date: 2022-07-11&quot;)
</code></pre><p>Nice stuff! The next wrinkle is that some of my posts already contain metadata (because I started adding it to my last couple of posts in preparation for this switch), so I shouldn&apos;t overwrite it if it&apos;s already there. Let&apos;s see how I can detect such posts:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map (fn [{:keys [file] :as post}]
            (let [contents (-&gt;&gt; file
                                (fs/file &quot;blog&quot; &quot;posts&quot;)
                                slurp)
                  metadata (dissoc post :file)]
              (assoc post
                     :contents contents
                     :metadata metadata))))
     (some #(and (not (re-find #&quot;^[A-z]+: &quot; (:contents %))) %)))
;; =&gt; {:title &quot;Hacking the blog: caching&quot;,
;;     :file &quot;2022-07-11-hacking-blog-caching.md&quot;,
;;     :tags #{&quot;clojure&quot; &quot;blog&quot; &quot;babashka&quot;},
;;     :date &quot;2022-07-11&quot;,
;;     :contents
;;     &quot;Well, it had to come to this, didn&apos;t it? At some point in the life...&quot;,
;;     :metadata
;;     {:title &quot;Hacking the blog: caching&quot;,
;;      :tags #{&quot;clojure&quot; &quot;blog&quot; &quot;babashka&quot;},
;;      :date &quot;2022-07-11&quot;}}
</code></pre><p>OK, I know how to find posts that already have metadata, so now I&apos;m ready to prepend metadata to the file content only if it&apos;s not already there. I&apos;ll go ahead and do it, and then pick a random post and have a look at it to make sure it looks good:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map (fn [{:keys [file] :as post}]
            (let [contents (-&gt;&gt; file
                                (fs/file &quot;blog&quot; &quot;posts&quot;)
                                slurp)
                  metadata (dissoc post :file)
                  metadata-str
                  (-&gt;&gt; metadata
                       (map (fn [[k v]]
                              (let [v (if (coll? v) (str/join &quot;,&quot; v) v)]
                                (format &quot;%s: %s&quot; (str/capitalize (name k)) v))))
                       (str/join &quot;\n&quot;))
                  contents (if (re-find #&quot;^[A-z]+: &quot; contents)
                             contents
                             (format &quot;%s\n\n%s&quot; metadata-str contents))]
              (assoc post
                     :contents contents
                     :metadata metadata))))
     shuffle
     first)
;; =&gt; {:title &quot;Story of a mediocre fan&quot;,
;;     :file &quot;2022-06-16-story-of-a-mediocre-fan.md&quot;,
;;     :tags #{&quot;arsenal&quot; &quot;stories&quot;},
;;     :date &quot;2022-06-16&quot;,
;;     :contents
;;     &quot;Title: Story of a mediocre fan\nTags: arsenal,stories\nDate: 2022-06-16\n\nThe winter...&quot;,
;;     :metadata
;;     {:title &quot;Story of a mediocre fan&quot;,
;;      :tags #{&quot;arsenal&quot; &quot;stories&quot;},
;;      :date &quot;2022-06-16&quot;}}
</code></pre><p>Sure enough, <code>:contents</code> begins with my metadata! Out of a surfeit of caution, I&apos;ll make sure that no posts would remain that don&apos;t have metadata at the beginning of their content:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map (fn [{:keys [file] :as post}]
            (let [contents (-&gt;&gt; file
                                (fs/file &quot;blog&quot; &quot;posts&quot;)
                                slurp)
                  metadata (dissoc post :file)
                  metadata-str
                  (-&gt;&gt; metadata
                       (map (fn [[k v]]
                              (let [v (if (coll? v) (str/join &quot;,&quot; v) v)]
                                (format &quot;%s: %s&quot; (str/capitalize (name k)) v))))
                       (str/join &quot;\n&quot;))
                  contents (if (re-find #&quot;^[A-z]+: &quot; contents)
                             contents
                             (format &quot;%s\n\n%s&quot; metadata-str contents))]
              (assoc post
                     :contents contents
                     :metadata metadata))))
     (some #(and (not (re-find #&quot;^[A-z]+: &quot; (:contents %))) %)))
;; =&gt; nil
</code></pre><p>All the pieces are now in place. The only thing left to do is actually write the updated file contents back to the file:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map (fn [{:keys [file] :as post}]
            (let [contents (-&gt;&gt; file
                                (fs/file &quot;blog&quot; &quot;posts&quot;)
                                slurp)
                  metadata (dissoc post :file)
                  metadata-str
                  (-&gt;&gt; metadata
                       (map (fn [[k v]]
                              (let [v (if (coll? v) (str/join &quot;,&quot; v) v)]
                                (format &quot;%s: %s&quot; (str/capitalize (name k)) v))))
                       (str/join &quot;\n&quot;))
                  contents (if (re-find #&quot;^[A-z]+: &quot; contents)
                             contents
                             (format &quot;%s\n\n%s&quot; metadata-str contents))]
              (assoc post
                     :contents contents
                     :metadata metadata))))
     (map (fn [{:keys [file contents]}]
            (spit (fs/file &quot;blog&quot; &quot;posts&quot; file) contents)))
     doall)
;; =&gt; (nil
;;     nil
;;     ...
;;     nil)
</code></pre><p>OK, something happened, but it&apos;s a little hard to tell exactly what, given that the <a href="https://clojuredocs.org/clojure.core/spit"><code>spit</code></a> function returns <code>nil</code>. By the way, the reason that I added the <code>doall</code> to the end of my pipeline is that CIDER will abbreviate the result of evaluating the expression in order to avoid possibly writing millions of lines of text to your file if you&apos;re processing a lot of data, and <a href="https://clojuredocs.org/clojure.core/map"><code>map</code></a> is a lazy function, meaning that it will only execute the mapping function when the result needs to be used. In my case, it will be used when the REPL tries to print it out, but if CIDER truncates the result of my evaluation such that not all results will be printed, some of my files won&apos;t be processed. That&apos;s where <a href="https://clojuredocs.org/clojure.core/doall"><code>doall</code></a> comes in: it walks the lazy sequence returned by <code>map</code> and forces evaluation of each value in the sequence.</p><p>This is why you shouldn&apos;t have side effects in mapping functions in real production code. You should use something like <a href="https://clojuredocs.org/clojure.core/doseq"><code>doseq</code></a> instead, which exists specifically to execute expressions with side effects. But hey, I&apos;m experimenting here, so I&apos;ll take the convenience of being able to shove <code>map</code> in a pipeline and have my effects on the side, thank you very much! If I wanted to be told what to do by my programming language, I&apos;d be writing Haskell. 😜</p><p>OK, now that I&apos;ve updated my files (in theory, anyway), let me check a few to make sure they actually start with metadata like they should:</p><pre><code class="language-clojure">(-&gt;&gt; (load-posts (fs/file &quot;blog&quot; &quot;posts.edn&quot;))
     (map (fn [{:keys [file] :as post}]
            (let [contents (-&gt;&gt; file
                                (fs/file &quot;blog&quot; &quot;posts&quot;)
                                slurp)]
              (subs contents 0 80))))
     (take 3))
;; =&gt; (&quot;Title: Some stuff I learned today\nTags: waffle\nDate: 2022-07-12\n\nToday was a hig&quot;
;;     &quot;Title: Hacking the blog: caching\nTags: clojure,blog,babashka\nDate: 2022-07-11\n\nW&quot;
;;     &quot;Title: Hands off women&apos;s football\nTags: football,euro2022\nDate: 2022-07-10\n\nThe &quot;)
</code></pre><p>Yes they do, and now I can declare victory, thanks to my trusty REPL and my wonderful CIDER! 🏆</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-11-hacking-blog-caching.html</id>
    <link href="https://jmglov.net/blog/2022-07-11-hacking-blog-caching.html"/>
    <title>Hacking the blog: caching</title>
    <updated>2022-07-11T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>Well, it had to come to this, didn&apos;t it? At some point in the life of every programmer, you have to take a deep sigh, realise that you have a problem where caching is the least bad solution, and get to it. That point in my life was today, when I finally got tired of waiting 30 seconds for my blog to publish, and knew that the reason it was taking so long is that my rendering process was repeating work that had already been done every time I ran it, and that resulted in rewriting files that made my publishing process think they had changes, and upload them to S3. The horror!</p><p>Let me quickly sketch out how publishing my blog works. I use <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html">S3 static website
hosting</a>, which means that publishing my website is nothing more than uploading files to my <code>jmglov.net</code> S3 bucket. I&apos;m using <a href="https://github.com/babashka/babashka">Babashka</a> to manage all this, so I have a task like this in my <a href="https://github.com/jmglov/jmglov.net/blob/main/bb.edn"><code>bb.edn</code></a>:</p><pre><code class="language-clojure">{:tasks
 {publish-blog {:doc &quot;Publish blog&quot;
                :depends [render-blog]
                :task (shell &quot;aws s3 sync --delete public/blog/ s3://jmglov.net/blog/&quot;)}}}
</code></pre><p>The <code>aws sync</code> uses some <code>rsync</code>-like logic to only upload files that have changed. This is good for me, as I have a bunch of images, and I don&apos;t want to upload them over and over again, as it takes time, and eventually AWS will charge me for the bandwidth.</p><p>Let&apos;s take a look at <a href="https://github.com/jmglov/jmglov.net/blob/main/render_blog.clj">how the blog is
rendered</a>:</p><ol start="1"><li>Copy all of the images from <code>assets/</code> to <code>public/blog/assets/</code></li><li>Copy the <code>style.css</code> file to <code>public/blog/</code></li><li>Read in all of the posts from <code>posts.edn</code></li><li>For each post, read the markdown source file, render it to HTML, insert it as the body into the <a href="https://github.com/jmglov/jmglov.net/blob/main/blog/templates/base.html">page
   template</a> template with <a href="https://github.com/yogthos/Selmer">Selmer</a>, and write the resulting HTML file to <code>public/blog/</code></li><li>Create an <code>archive.html</code> page with links to all the posts</li><li>Create a <code>tags/index.html</code> page with links to all of the tags</li><li>For each tag, create a page with links to all the posts with that tag</li><li>Create a top-level <code>index.html</code> page with the last three posts</li><li>Create an <code>atom.xml</code> RSS feed with all of the posts</li><li>Create a <code>planetclojure.xml</code> RSS feed with posts tagged &quot;clojure&quot; or &quot;clojurescript&quot;</li></ol><p>Each one of these steps is creating a file in <code>public/blog</code> that will be uploaded to S3 if the local file is newer than the file on S3. Without any caching, all of these files will be created every time I render the blog, which means they will always be uploaded, and this was what I was running into.</p><p>Here&apos;s how the asset files <a href="https://github.com/jmglov/jmglov.net/blob/a9f05b17f2459257e48c6807622df5fbc8951d5f/render_blog.clj#L32">used to be
handled</a>:</p><pre><code class="language-clojure">(ns render-blog
  (:require
   [babashka.fs :as fs]
   [lib]))

(def blog-dir (fs/file &quot;blog&quot;))
(def out-dir (fs/file &quot;public&quot; &quot;blog&quot;))
(def asset-dir (fs/create-dirs (fs/file out-dir &quot;assets&quot;)))

(fs/copy-tree (fs/file blog-dir &quot;assets&quot;) asset-dir
              {:replace-existing true})
</code></pre><p><code>fs/copy-tree</code> is basically the same thing as <code>cp -r</code>: it copies all of the files from <code>blog/assets</code> to <code>public/blog/assets</code>. The problem is that changes the modification timestamp on the file, thus making <code>s3 sync</code> think it&apos;s a newer file and upload it. What I would like to do instead is only copy the new and modified asset files to <code>public/blog/assets</code>.</p><p>In order to do this, I wrote a new function, <a href="https://github.com/jmglov/jmglov.net/blob/fb1d1d28c9ef1289309cb539bd85e1ddb9400916/lib.clj#L23"><code>copy-tree-modified</code></a>, and used it like this:</p><pre><code class="language-clojure">(lib/copy-tree-modified (fs/file blog-dir &quot;assets&quot;)
                        asset-dir
                        (.getParent out-dir))
</code></pre><p>Here&apos;s what the function looks like:</p><pre><code class="language-clojure">(defn copy-tree-modified [src-dir target-dir out-dir]
  (let [modified-paths (fs/modified-since (fs/file target-dir)
                                          (fs/file src-dir))
        new-paths (-&gt;&gt; (fs/glob src-dir &quot;**&quot;)
                       (remove #(fs/exists? (fs/file out-dir %))))]
    (doseq [path (concat modified-paths new-paths)
            :let [target-path (fs/file out-dir path)]]
      (fs/create-dirs (.getParent target-path))
      (println &quot;Writing&quot; (str target-path))
      (fs/copy (fs/file path) target-path))))
</code></pre><p>I&apos;ll walk you through what&apos;s going on here:</p><ol start="1"><li><a href="https://babashka.org/fs/codox/babashka.fs.html#var-modified-since"><code>fs/modified-since</code></a> returns a list of the files in <code>src-dir</code> (which in the case of my assets, is <code>blog/assets</code>) which have been modified since the time <code>target-dir</code> (<code>public/blog/assets</code>) was last modifed.</li><li>Since this will not pick up files that have been added to <code>src-dir</code> after <code>target-dir</code> was last modified, I do an <a href="https://babashka.org/fs/codox/babashka.fs.html#var-glob"><code>fs/glob</code></a> to get a list of all of the files in <code>src-dir</code>, then remove the ones that already exist in <code>target-dir</code>.</li><li>I concatenate the modified files and the new files and then <code>doseq</code> over them, creating subdirectories as needed, and then copy them into <code>out-dir</code> (<code>public/blog</code>).</li></ol><p>This handles recursively copying directories, but how about single files? We can take a look at how the <code>style.css</code> used to be handled:</p><pre><code class="language-clojure">(let [style-src (fs/file templates-dir &quot;style.css&quot;)
      style-target (fs/file out-dir &quot;style.css&quot;)]
  (fs/copy style-src style-target))
</code></pre><p>Now it&apos;s subtly changed to use a new <code>copy-modified</code> library function:</p><pre><code class="language-clojure">(let [style-src (fs/file templates-dir &quot;style.css&quot;)
      style-target (fs/file out-dir &quot;style.css&quot;)]
  (lib/copy-modified style-src style-target))
</code></pre><p>The <a href="https://github.com/jmglov/jmglov.net/blob/fb1d1d28c9ef1289309cb539bd85e1ddb9400916/lib.clj#L14"><code>copy-modified</code></a> function looks like this:</p><pre><code class="language-clojure">(defn stale? [src target]
  (seq (fs/modified-since target src)))

(defn copy-modified [src target]
  (when (stale? src target)
    (println &quot;Writing&quot; (str target))
    (fs/create-dirs (.getParent (fs/file target)))
    (fs/copy src target)))
</code></pre><p>We&apos;re using <code>fs/modified-since</code> in a slightly different way here. When both the <code>target</code> and the <code>src</code> are files, <code>fs/modified-since</code> will notice when <code>src</code> exists but <code>target</code> doesn&apos;t (meaning that <code>src</code> has been added since last time we rendered). Wrapping it in a <code>seq</code> will make it return <code>nil</code> when the list of modified files is empty, which we use as a truthy value.</p><p>The final piece of the puzzle is how to handle things like posts and archives and tags, which should only be written when there is a new post, an updated post, or something has changed with the rendering code or templates. I&apos;ll illustrate this by showing how the archive page is handled:</p><pre><code class="language-clojure">(def posts-file &quot;posts.edn&quot;)
(def rendering-system-files [&quot;render_blog.clj&quot; templates-dir])

(let [archive-file (fs/file out-dir &quot;archive.html&quot;)
      new-posts? (lib/stale? posts-file archive-file)
      rendering-modified? (lib/rendering-modified? rendering-system-files
                                                   archive-file)]
  (when (or rendering-modified? new-posts?)
    (println &quot;Writing archive page&quot; (str archive-file))
    (spit archive-file
          (selmer/render base-html
                         {:skip-archive true
                          :title (str blog-title &quot; - Archive&quot;)
                          :body (hiccup/html (lib/post-links {} &quot;Archive&quot; posts))}))))
</code></pre><p>To determine if there are new posts, we check if the archive file is stale with respect to the posts file, meaning that the posts file has changed since we last wrote the archive file.</p><p>To determine if any of the rendering code has changed, we use <a href="https://github.com/jmglov/jmglov.net/blob/fb1d1d28c9ef1289309cb539bd85e1ddb9400916/lib.clj#L11"><code>lib/rendering-modified?</code></a>:</p><pre><code class="language-clojure">(defn rendering-modified? [rendering-system-files target-file]
  (seq (fs/modified-since target-file rendering-system-files)))
</code></pre><p>What we&apos;re asking here is if <code>render_blog.clj</code> or any of the template files have changed since we last wrote the archive file. If so, we want to re-render the archive file.</p><p>If you&apos;re interested in seeing this in action, take a look at <a href="https://github.com/jmglov/jmglov.net/blob/main/render_blog.clj"><code>render_blog.clj</code></a> and <a href="https://github.com/jmglov/jmglov.net/blob/main/lib.clj"><code>lib.clj</code></a>. Just note that things are not very polished, and there are likely to be bugs. 😬</p><p><strong>Update:</strong> shortly after writing this code (<a href="2022-07-12-stuff-i-learned.md">the next
morning</a> on my dog walk, in fact), I realised that my caching was horribly broken. To see how I fixed it, check out <a href="2022-07-15-hacking-blog-actually-caching.html">Hacking
the blog: actually caching</a>.</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-06-hacking-blog-categories.html</id>
    <link href="https://jmglov.net/blog/2022-07-06-hacking-blog-categories.html"/>
    <title>Hacking the blog: categories</title>
    <updated>2022-07-06T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>Today&apos;s post is coming pretty late in the day due to me spending a few hours working on the final chapter of &quot;<a href="2022-06-16-story-of-a-mediocre-fan.html">Story of a mediocre
fan</a>&quot; (not quite finished, but I&apos;ll wrap it up in the morning), playing some Civ V (I&apos;m running the Mongol empire these days), actually doing the thing I&apos;m about to write about, then watching the last two episodes of season 2 of <a href="https://www.imdb.com/title/tt8806524/">Star Trek:
Picard</a>, and then watching the first half of the opening match of the <a href="https://www.uefa.com/womenseuro/">Women&apos;s Euro 2022
tournament</a>. England (boo!) are leading Austria 1-0, but at least the goalscorer was Arsenal&apos;s own Beth Mead, so I can&apos;t be too mad. My approach to the tournament is to cheer for Sweden and then whatever team has the most Arsenal players (with ties being broken by which team has the most former Arsenal players). In this particular match, England have two current players (Leah Williamson and Beth Mead), and Austria do as well (Manu Zinsberger and Laura Wienroither), but then Austria also have a former Arsenal player (Viki Schnaderbeck), so I&apos;m for them in this match.</p><p>But I&apos;m not writing about football today (or at least, doing my best not to), I&apos;m writing about the latest hacking I&apos;ve done on the blog.</p><p>Though you can&apos;t currently tell this, each blog post has one or more categories associated with it. This post, for example, is categorised as &quot;clojure&quot; and &quot;blog&quot;. These categories are currently only used to determine which posts should be included in the <a href="http://planet.clojure.in/">Planet Clojure</a> feed, but I thought it would be cool to be able to browse all posts from a given category, so I hacked it together this afternoon.</p><p>This blog already has an <a href="archive.html">archive page</a> which lists all of the posts, so my idea was to create a similar page for each category, called something like <a href="category/aws.html"><code>category/aws.html</code></a>.</p><p>The first step was to build a data structure which contains all of the posts for each category. The post metadata lives in <a href="https://github.com/jmglov/jmglov.net/blob/575a12cf2a87a4fd2a46dc131ed3a51f864ba57f/blog/posts.edn"><code>posts.edn</code></a>, which looks like this:</p><pre><code class="language-clojure">{:title &quot;Blambda!&quot;
 :file &quot;2022-07-03-blambda.md&quot;
 :categories #{&quot;aws&quot; &quot;s3&quot; &quot;lambda&quot; &quot;clojure&quot;}
 :date &quot;2022-07-03&quot;}
{:title &quot;Dogfooding Blambda! : revenge of the pod people&quot;
 :file &quot;2022-07-04-dogfooding-blambda-1.md&quot;
 :categories #{&quot;aws&quot; &quot;s3&quot; &quot;lambda&quot; &quot;clojure&quot; &quot;blambda&quot;}
 :date &quot;2022-07-04&quot;}
{:title &quot;Hacking the blog: favicon&quot;
 :file &quot;2022-07-05-hacking-blog-favicon.md&quot;
 :categories #{&quot;clojure&quot; &quot;blog&quot;}
 :date &quot;2022-07-05&quot;}
{:title &quot;Hacking the blog: categories&quot;
 :file &quot;2022-07-06-hacking-blog-categories.md&quot;
 :categories #{&quot;clojure&quot; &quot;blog&quot;}
 :date &quot;2022-07-06&quot;}
</code></pre><p>The post metadata is loaded in <a href="https://github.com/jmglov/jmglov.net/blob/main/blog/render.clj"><code>render.clj</code></a> like this:</p><pre><code class="language-clojure">(def posts (sort-by :date (comp - compare)
                    (edn/read-string (format &quot;[%s]&quot;
                                             (slurp &quot;posts.edn&quot;)))))
</code></pre><p>This gives me a list of posts, with each post having one or more categories. What I need for my category pages, however, is a map like this:</p><pre><code class="language-clojure">{&quot;aws&quot; [{:title &quot;Blambda!&quot;
         :file &quot;2022-07-03-blambda.md&quot;
         :categories #{&quot;aws&quot; &quot;s3&quot; &quot;lambda&quot; &quot;clojure&quot;}
         :date &quot;2022-07-03&quot;}
        {:title &quot;Dogfooding Blambda! : revenge of the pod people&quot;
         :file &quot;2022-07-04-dogfooding-blambda-1.md&quot;
         :categories #{&quot;aws&quot; &quot;s3&quot; &quot;lambda&quot; &quot;clojure&quot; &quot;blambda&quot;}
         :date &quot;2022-07-04&quot;}]
 &quot;clojure&quot; [{:title &quot;Blambda!&quot;
             :file &quot;2022-07-03-blambda.md&quot;
             :categories #{&quot;aws&quot; &quot;s3&quot; &quot;lambda&quot; &quot;clojure&quot;}
             :date &quot;2022-07-03&quot;}
            {:title &quot;Dogfooding Blambda! : revenge of the pod people&quot;
             :file &quot;2022-07-04-dogfooding-blambda-1.md&quot;
             :categories #{&quot;aws&quot; &quot;s3&quot; &quot;lambda&quot; &quot;clojure&quot; &quot;blambda&quot;}
             :date &quot;2022-07-04&quot;}
            {:title &quot;Hacking the blog: favicon&quot;
             :file &quot;2022-07-05-hacking-blog-favicon.md&quot;
             :categories #{&quot;clojure&quot; &quot;blog&quot;}
             :date &quot;2022-07-05&quot;}
            {:title &quot;Hacking the blog: categories&quot;
             :file &quot;2022-07-06-hacking-blog-categories.md&quot;
             :categories #{&quot;clojure&quot; &quot;blog&quot;}
             :date &quot;2022-07-06&quot;}]}
</code></pre><p>Here&apos;s how we can achieve that:</p><pre><code class="language-clojure">(def posts-by-category
  (-&gt;&gt; posts
       (sort-by :date)
       (mapcat (fn [{:keys [categories] :as post}]
                 (map (fn [category] [category post]) categories)))
       (reduce (fn [acc [category post]]
                 (update acc category #(conj % post)))
               {})))
</code></pre><p>The <code>mapcat</code> step takes each post, which looks like this:</p><pre><code class="language-clojure">{:title &quot;Hacking the blog: categories&quot;
 :file &quot;2022-07-06-hacking-blog-categories.md&quot;
 :categories #{&quot;clojure&quot; &quot;blog&quot;}
 :date &quot;2022-07-06&quot;}
</code></pre><p>and maps over the <code>:categories</code> list (that <code>{:keys [categories]}</code> bit is <a href="https://clojure.org/guides/destructuring#_associative_destructuring">key
destructuring</a>, if you haven&apos;t seen it before), turning each category into a tuple of <code>[category
post]</code>. For this specific post, this would yield:</p><pre><code class="language-clojure">[[&quot;clojure&quot; {:title &quot;Hacking the blog: categories&quot;
             :file &quot;2022-07-06-hacking-blog-categories.md&quot;
             :categories #{&quot;clojure&quot; &quot;blog&quot;}
             :date &quot;2022-07-06&quot;}]
 [&quot;blog&quot; {:title &quot;Hacking the blog: categories&quot;
          :file &quot;2022-07-06-hacking-blog-categories.md&quot;
          :categories #{&quot;clojure&quot; &quot;blog&quot;}
          :date &quot;2022-07-06&quot;}]]
</code></pre><p>Each post is turned inside out like this, yielding a list of lists of tuples, or at least before the &quot;cat&quot; part of <code>mapcat</code> goes to work. The difference between <code>map</code> and <code>mapcat</code> is that <code>mapcat</code> flattens the resulting list (according to <a href="https://clojuredocs.org/clojure.core/mapcat">the docs</a>, it &quot;returns the result of applying concat to the result of applying <code>map</code> to <code>f</code> and <code>colls</code>&quot;, but I like my explanation better), so instead of a list of lists of tuples, I get a list of tuples.</p><p>I reduce that list with this function, initialising <code>acc</code> to an empty map:</p><pre><code class="language-clojure">(fn [acc [category post]]
  (update acc category #(conj % post)))
</code></pre><p>For each entry in the list, the key in <code>acc</code> corresponding to the category is updated by adding the current post to the end of the list of posts with that category.</p><p>Now that I have the data structure I need, let&apos;s see how the archive page is currently built:</p><pre><code class="language-clojure">;;;; Generate archive page

(defn post-links []
  [:div {:style &quot;width: 600px;&quot;}
   [:h1 &quot;Archive&quot;]
   [:ul.index
    (for [{:keys [file title date preview]} posts
          :when (not preview)]
      [:li [:span
            [:a {:href (str/replace file &quot;.md&quot; &quot;.html&quot;)}
             title]
            &quot; - &quot;
            date]])]])

(spit (fs/file out-dir &quot;archive.html&quot;)
      (selmer/render base-html
                     {:skip-archive true
                      :title (str blog-title &quot; - Archive&quot;)
                      :body (hiccup/html (post-links))}))
</code></pre><p>I can do something very similar to build my category pages:</p><pre><code class="language-clojure">(defn category-links [category posts]
  [:div {:style &quot;width: 600px;&quot;}
   [:h1 (str &quot;Category - &quot; category)]
   [:ul.index
    (for [{:keys [file title date preview]} posts
          :when (not preview)]
      [:li [:span
            [:a {:href (str &quot;../&quot; (str/replace file &quot;.md&quot; &quot;.html&quot;))}
             title]
            &quot; - &quot;
            date]])]])

(def categories-dir (fs/create-dirs (fs/file out-dir &quot;category&quot;)))

(doseq [[category posts] posts-by-category
        :let [category-slug (str/replace category #&quot;[^A-z0-9]&quot; &quot;-&quot;)]]
  (spit (fs/file categories-dir (str category-slug &quot;.html&quot;))
        (selmer/render base-html
                       {:skip-archive true
                        :title (str blog-title &quot; - Category - &quot; category)
                        :relative-path &quot;../&quot;
                        :body (hiccup/html (category-links category posts))})))
</code></pre><p>Since I decided to put my category pages under the <code>category/</code> path, I need to adjust all of the links to go up one level. This required adding the <code>:relative-path &quot;../&quot;</code> to the list of variables passed to <a href="https://github.com/yogthos/Selmer">Selmer</a> when rendering <a href="https://github.com/jmglov/jmglov.net/blob/main/blog/templates/base.html"><code>templates/base.html</code></a> and updating the template with stuff like:</p><pre><code class="language-html">&lt;link rel=&quot;stylesheet&quot; href=&quot;{{relative-path | safe}}style.css&quot;&gt;
</code></pre><p>Once I did that, all that was left to do was <code>bb publish</code>, and now you can enjoy all of the posts about this blog here: <a href="https://jmglov.net/blog/category/blog.html">https://jmglov.net/blog/category/blog.html</a></p><p>You can see all of the changes required to implement this here: <a href="https://github.com/jmglov/jmglov.net/commit/6ea911d2b4c0418d01e74e4aceb2686a3f1b86a3">https://github.com/jmglov/jmglov.net/commit/6ea911d2b4c0418d01e74e4aceb2686a3f1b86a3</a></p><p>This is obviously a work in progress feature. It would be nice to do the following:</p><ul><li>Display the categories each post is tagged with</li><li>Rename &quot;category&quot; to &quot;tag&quot;, since that more properly describes the concept</li><li>Link the tags on the post to each tag&apos;s archive page</li><li>Add a page somewhere listing all of the tags and linking to the archive pages for each</li></ul><p>We&apos;ll see what I get around to that stuff. 😉</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-05-hacking-blog-favicon.html</id>
    <link href="https://jmglov.net/blog/2022-07-05-hacking-blog-favicon.html"/>
    <title>Hacking the blog: favicon</title>
    <updated>2022-07-05T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>The fun thing about having a blog which is built with a <a href="https://github.com/jmglov/jmglov.net">static site
generator</a> is that you get to <s>waste</s> spend time customising it. In today&apos;s instalment of &quot;Hacking the blog&quot;, we&apos;ll see how to add a &quot;<a href="https://en.wikipedia.org/wiki/Favicon">favicon</a>&quot;, which is that little icon thingy on your tab title.</p><p>My first order of business was to figure out what I wanted to use for my favicon. I decided that I really love this drawing that my friend Sebastian did on a whiteboard way back in 2016, so why not use it?</p><p><img alt="A cartoon drawing of me wearing a t-shirt that says &apos;I love Virginia&apos;" src="assets/josh-right-on-transparent.png" title="Virginia is for hustlers" /></p><div class="markdown-heading"><h2 id="building-the-favicon">Building the favicon</h2><a href="#building-the-favicon" class="anchor" aria-label="Permalink: Building the favicon"><img src="assets/link.svg" /></a></div><p>The first step (after I remembered what a &quot;favicon&quot; was actually called) was making a clean version of this image that would scale down nicely to the various sizes used by browsers. Courtesy of <a href="https://stackoverflow.com/a/19590415/58994">a really thorough
answer</a> to a question on Stack Overflow, I found a really cool site called <a href="https://realfavicongenerator.net/">RealFaviconGenerator</a>, which would take an image (recommended to be at least 260x206 pixels) and spit out a zipfile containing a bunch of files:</p><ul><li>android-chrome-192x192.png</li><li>android-chrome-256x256.png</li><li>apple-touch-icon.png</li><li>browserconfig.xml</li><li>favicon-16x16.png</li><li>favicon-32x32.png</li><li>favicon.ico</li><li>mstile-150x150.png</li><li>safari-pinned-tab.svg</li><li>site.webmanifest</li></ul><p>These files, if placed at the root of your website and combined with a chunk of HTML in your <code>&lt;head&gt;</code> section, would do the right thing for All the Browsers and All the Smartphones.</p><p>So I opened up my image in <a href="https://gimp.org/">the GIMP</a>, cropped it so only my head was visible, and removed the speech bubble, resulting in the following:</p><p><img alt="A cartoon drawing of my head" src="assets/josh-right-on-260x260.png" title="Virginia is for favicons" /></p><p>I fed this image into RealFaviconGenerator, which gave me back the zipfile described above and the following HTML fragment:</p><pre><code class="language-html">&lt;link rel=&quot;apple-touch-icon&quot; sizes=&quot;180x180&quot; href=&quot;/apple-touch-icon.png&quot;&gt;
&lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;32x32&quot; href=&quot;/favicon-32x32.png&quot;&gt;
&lt;link rel=&quot;icon&quot; type=&quot;image/png&quot; sizes=&quot;16x16&quot; href=&quot;/favicon-16x16.png&quot;&gt;
&lt;link rel=&quot;manifest&quot; href=&quot;/site.webmanifest&quot;&gt;
&lt;link rel=&quot;mask-icon&quot; href=&quot;/safari-pinned-tab.svg&quot; color=&quot;#5bbad5&quot;&gt;
&lt;meta name=&quot;msapplication-TileColor&quot; content=&quot;#da532c&quot;&gt;
&lt;meta name=&quot;theme-color&quot; content=&quot;#ffffff&quot;&gt;
</code></pre><div class="markdown-heading"><h2 id="hacking-the-blog">Hacking the blog</h2><a href="#hacking-the-blog" class="anchor" aria-label="Permalink: Hacking the blog"><img src="assets/link.svg" /></a></div><p>The next order of business was to get the favicon onto my site. If you remember from the <a href="2022-06-19-actually-blogging-with-clojure.html">Actually blogging with
Clojure</a> post, the way the blog works is this:</p><ol start="1"><li>There&apos;s a <a href="https://github.com/babashka/babashka">Babashka</a> <a href="https://github.com/jmglov/jmglov.net/blob/main/blog/bb.edn"><code>bb.edn</code></a> which defines a <code>render</code> task that looks like this:<pre><code class="language-clojure"></code></pre></li></ol><p>render {:doc &quot;Render blog&quot; :task (load-file &quot;render.clj&quot;)}</p><pre><code>2. [`render.clj`](https://github.com/jmglov/jmglov.net/blob/main/blog/render.clj)
does stuff like converting Markdown to HTML, then uses the
[Selmer](https://github.com/yogthos/Selmer) templating system to shove blog
posts into the
[`templates/base.html`](https://github.com/jmglov/jmglov.net/blob/main/blog/templates/base.html)
template
3. `render.clj` then copies the resulting HTML files to a `public/` directory
4. There&apos;s another task called `publish` in `bb.edn` that uses the AWS CLI to
sync everything in the `public/` to the S3 bucket that contains my blog:
``` clojure
publish {:doc &quot;Publish to jmglov.net&quot;
      :depends [render]
      :task (shell &quot;aws s3 sync --delete public/ s3://jmglov.net/blog/&quot;)}
</code></pre><p>So getting the favicon injected into every page was as simple as blasting the HTML fragment into <code>templates/base.html</code>.</p><p>Almost.</p><p>You see, I also need to put the content being referenced in all of those <code>&lt;link&gt;</code> tags up on the website. My website itself uses the exact same machinery as the blog, meaning I need to add the HTML fragment to the top-level <a href="https://github.com/jmglov/jmglov.net/blob/main/templates/base.html"><code>templates/base.html</code></a>, and in order to get the favicon stuff onto the website, I need to hack up the top-level <a href="https://github.com/jmglov/jmglov.net/blob/main/render.clj"><code>render.clj</code></a>.</p><p>Looking at the way the existing <code>render.clj</code> (which I stole with pride from <a href="https://github.com/borkdude/blog">borkdude’s blog</a>) handles images and CSS is most instructive:</p><pre><code class="language-clojure">(def out-dir &quot;public&quot;)

;;;; Sync images and CSS

(def asset-dir (fs/create-dirs (fs/file out-dir &quot;assets&quot;)))

(fs/copy-tree &quot;assets&quot; asset-dir {:replace-existing true})

(spit (fs/file out-dir &quot;style.css&quot;)
      (slurp &quot;templates/style.css&quot;))
</code></pre><p>Since the <code>deploy</code> task will sync everything from the <code>public/</code> directory to my website, I just need to put the contents of the favicon zipfile in <code>public/</code> and I win!</p><p>I unzipped the favicon zipfile into a top-level <a href="https://github.com/jmglov/jmglov.net/tree/main/favicon"><code>favicon/</code></a> directory, then added the following to <code>render.clj</code>:</p><pre><code class="language-clojure">;;;; Sync favicon

(def favicon-dir (fs/create-dirs (fs/file out-dir)))

(fs/copy-tree &quot;favicon&quot; favicon-dir {:replace-existing true})
</code></pre><p>And that&apos;s all it took to display my little cartoon face on your browser&apos;s tab! 🏆</p><p>If you&apos;re interested, you can check out <a href="https://github.com/jmglov/jmglov.net/commit/e9196e65568e5ba211c87f855e06d83a8fb20619">this
commit</a> to see everything I did, all wrapped up into one cute little package.</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-04-dogfooding-blambda-1.html</id>
    <link href="https://jmglov.net/blog/2022-07-04-dogfooding-blambda-1.html"/>
    <title>Dogfooding Blambda! : revenge of the pod people</title>
    <updated>2022-07-04T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>Today I finally tried to use <a href="https://github.com/jmglov/blambda">Blambda!</a> for something real: a log parser for my HTTP access logs that S3 and Cloudfront write to <a href="2022-06-24-s3-https.html">my logs bucket</a>. You can follow along with my fun on Github: <a href="https://github.com/jmglov/s3-log-parser">jmglov/s3-log-parser</a>.</p><p>Here&apos;s what I&apos;m trying to do:</p><ol start="1"><li>Create a lambda function that downloads access logs from S3 for a certain date range, parses them, and then returns some useful information</li><li>Save that useful information to a database</li><li>Write another function that provides some cool analytics on traffic going to my blog and use a <a href="https://aws.amazon.com/blogs/aws/announcing-aws-lambda-function-urls-built-in-https-endpoints-for-single-function-microservices/">Lambda Function
   URL</a> to serve it up over HTTPS</li></ol><p>I&apos;m sure this will change quite drastically as I go, but it seems like a fun problem that will find the rough edges with Blambda!</p><p>Here&apos;s how I proceeded.</p><div class="markdown-heading"><h2 id="creating-a-lambda-handler">Creating a lambda handler</h2><a href="#creating-a-lambda-handler" class="anchor" aria-label="Permalink: Creating a lambda handler"><img src="assets/link.svg" /></a></div><p>In my project, I created a simple handler in <a href="https://github.com/jmglov/s3-log-parser/blob/main/src/s3_log_parser.clj"><code>src/s3_log_parser.clj</code></a>:</p><pre><code class="language-clojure">(ns s3-log-parser)

(defn handler [event context]
  (prn {:msg &quot;Invoked with event&quot;,
        :data {:event event}})
  {})
</code></pre><p>This will just log the event it was invoked with and then return an empty map (or JSON object, if you must).</p><p>Since this lambda will eventually interact with S3, I decided to bite the bullet and include the <a href="https://github.com/babashka/pod-babashka-aws">babashka-aws</a> pod. I created a <a href="https://github.com/jmglov/s3-log-parser/blob/main/src/bb.edn"><code>src/bb.edn</code></a> like this:</p><pre><code class="language-clojure">{:paths [&quot;.&quot;]
 :pods {org.babashka/aws {:version &quot;0.1.2&quot;}}}
</code></pre><p>This <code>bb.edn</code> will be picked up by <a href="https://github.com/babashka/babashka">Babashka</a> when it is executing my lambda, since Blambda! runs <code>bb</code> from the directory where my lambda archive is unpacked (<code>$LAMBDA_TASK_ROOT</code>, for those of you familiar with building custom runtimes).</p><div class="markdown-heading"><h2 id="packaging-my-lambda">Packaging my lambda</h2><a href="#packaging-my-lambda" class="anchor" aria-label="Permalink: Packaging my lambda"><img src="assets/link.svg" /></a></div><p>I created a top-level <a href="https://github.com/jmglov/s3-log-parser/blob/main/bb.edn"><code>bb.edn</code></a>, which is used for defining Babashka tasks to build and deploy my function (not to be confused with <code>src/bb.edn</code>, which will be used at lambda runtime). The build task looks like this:</p><pre><code class="language-clojure">build {:doc &quot;Builds lambda artifact&quot;
       :requires ([clojure.java.shell :refer [sh]])
       :task (let [{:keys [target-dir work-dir]} (th/parse-args)
                   work-dir (str work-dir &quot;/lambda&quot;)
                   src-dir &quot;src&quot;
                   lambda-zipfile (th/target-file target-dir &quot;function.zip&quot;)]
               (doseq [dir [target-dir work-dir]]
                 (fs/create-dirs dir))

               (doseq [f [&quot;bb.edn&quot; &quot;s3_log_parser.clj&quot;]]
                 (println &quot;Adding file&quot; f)
                 (fs/delete-if-exists (format &quot;%s/%s&quot; work-dir f))
                 (fs/copy (format &quot;%s/%s&quot; src-dir f) work-dir))

               (println &quot;Compressing lambda archive:&quot; lambda-zipfile)
               (let [{:keys [exit err]}
                     (sh &quot;zip&quot; &quot;-r&quot; lambda-zipfile &quot;.&quot;
                         :dir work-dir)]
                 (when (not= 0 exit)
                   (println &quot;Error:&quot; err))))}
</code></pre><p>You can read the source for the <code>th</code> namespace in <a href="https://github.com/jmglov/s3-log-parser/blob/main/task_helper.clj"><code>task_helper.clj</code></a> if you like, but basically, what the <code>build</code> task is doing is:</p><ol start="1"><li>Creating work and target directories</li><li>Copying the <code>bb.edn</code> and <code>s3_log_parser.clj</code> files from the <code>src</code> directory to the work directory</li><li>Zipping all the files in the work directory into <code>target/function.zip</code></li></ol><div class="markdown-heading"><h2 id="deploying-my-lambda">Deploying my lambda</h2><a href="#deploying-my-lambda" class="anchor" aria-label="Permalink: Deploying my lambda"><img src="assets/link.svg" /></a></div><p>My <code>deploy</code> task is pretty straightforward:</p><pre><code class="language-clojure">deploy {:doc &quot;Deploys lambda using babashka-aws.&quot;
        :depends [build]
        :requires ([pod.babashka.aws :as aws])
        :task (let [{:keys [target-dir] :as args}
                    (th/parse-args)

                    lambda-zipfile (th/target-file target-dir &quot;function.zip&quot;)
                    zipfile (fs/read-all-bytes lambda-zipfile)]
                (th/create-or-update-lambda (assoc args :zipfile zipfile)))}
</code></pre><p>It reads in <code>target/function.zip</code> and passes it along to <code>task-helper/create-or-update-lambda</code>, which is a little more interesting:</p><pre><code class="language-clojure">(defn create-or-update-lambda [{:keys [aws-region bb-arch
                                       lambda-handler lambda-name lambda-role
                                       runtime-layer zipfile]
                                :as args}]
  (let [lambda (aws/client {:api :lambda
                            :region aws-region})
        _ (println &quot;Checking to see if lambda exists:&quot; lambda-name)
        lambda-exists? (-&gt; (aws/invoke lambda {:op :GetFunction
                                               :request {:FunctionName lambda-name}})
                           (contains? :Configuration))]
    (if lambda-exists?
      (update-lambda lambda args)
      (create-lambda lambda args))))
</code></pre><p>If no lambda with the name we&apos;ve specified exists, we call <code>create-lambda</code>:</p><pre><code class="language-clojure">(defn create-lambda [lambda
                     {:keys [aws-region bb-arch
                             lambda-handler lambda-name lambda-role
                             runtime-layer zipfile]}]
  (let [lambda-arch (if (= &quot;amd64&quot; bb-arch) &quot;x86_64&quot; &quot;arm64&quot;)
        runtime (if (= &quot;amd64&quot; bb-arch) &quot;provided&quot; &quot;provided.al2&quot;)
        sts (aws/client {:api :sts
                         :region aws-region})
        account-id (-&gt; (aws/invoke sts {:op :GetCallerIdentity}) :Account)
        layer-arns (-&gt;&gt; [runtime-layer]
                        (map #(format &quot;arn:aws:lambda:%s:%s:layer:%s&quot;
                                      aws-region account-id
                                      (latest-layer-version lambda %))))
        role-arn (format &quot;arn:aws:iam::%s:role/%s&quot;
                         account-id lambda-role)
        req {:FunctionName lambda-name
             :Runtime runtime
             :Role role-arn
             :Code {:ZipFile zipfile}
             :Handler lambda-handler
             :Layers layer-arns
             :Architectures [lambda-arch]}
        _ (println &quot;Creating lambda:&quot; (pr-str req))
        res (aws/invoke lambda {:op :CreateFunction
                                :request req})]
    (when (contains? res :cognitect.anomalies/category)
      (println &quot;Error:&quot; (pr-str res)))))
</code></pre><p>If you&apos;re interested in this <code>aws/client</code> and <code>aws/invoke</code> stuff, this is the <a href="https://github.com/cognitect-labs/aws-api">aws-api</a> library provided by the babashka-aws pod.</p><p><code>latest-layer-version</code> is a simple function that checks if our layer name includes a version (like <code>blambda:5</code>), or if not, uses Lambda&apos;s ListLayerVersions API to select the latest version:</p><pre><code class="language-clojure">(defn latest-layer-version [lambda layer-name]
  (if (string/includes? layer-name &quot;:&quot;)
    layer-name
    (let [latest-version (-&gt;&gt; (aws/invoke lambda {:op :ListLayerVersions
                                                  :request {:LayerName layer-name}})
                              :LayerVersions
                              (sort-by :Version)
                              last
                              :Version)]
      (format &quot;%s:%s&quot; layer-name latest-version))))
</code></pre><p>I can now deploy this by running <code>bb deploy</code> (I&apos;ve pre-baked the IAM role required for this lambda, but it&apos;s basically the same as the one from the <a href="https://github.com/jmglov/blambda#using-blambda">Blambda! example</a>).</p><div class="markdown-heading"><h2 id="roadblock-the-first">Roadblock the first</h2><a href="#roadblock-the-first" class="anchor" aria-label="Permalink: Roadblock the first"><img src="assets/link.svg" /></a></div><p>The problem is, when I invoke this lambda using a test event in the console, I get an error:</p><pre><code>Test Event Name
test

Response
{
  &quot;errorMessage&quot;: &quot;RequestId: 8292cbcf-2862-4189-97c2-757bc58a4ed8 Error: Runtime exited with error: exit status 1&quot;,
  &quot;errorType&quot;: &quot;Runtime.ExitError&quot;
}

Function Logs
ashka.pods.impl.resolver$download.invokeStatic(resolver.clj:105)
at babashka.pods.impl.resolver$pod_manifest.invokeStatic(resolver.clj:123)
at babashka.pods.impl.resolver$resolve.invokeStatic(resolver.clj:175)
at babashka.pods.impl$resolve_pod.invokeStatic(impl.clj:327)
[...]
Exception in thread &quot;main&quot; java.io.FileNotFoundException: /home/sbx_user1051/.babashka/pods/repository/org.babashka/aws/0.1.2/manifest.edn (No such file or directory)
at com.oracle.svm.jni.JNIJavaCallWrappers.jniInvoke_VA_LIST_FileNotFoundException_constructor_970c509c6abfd3f98898b9a7521945418b90b270(JNIJavaCallWrappers.java:0)
[...]
END RequestId: 8292cbcf-2862-4189-97c2-757bc58a4ed8
REPORT RequestId: 8292cbcf-2862-4189-97c2-757bc58a4ed8	Duration: 594.19 ms	Billed Duration: 595 ms	Memory Size: 128 MB	Max Memory Used: 21 MB	
RequestId: 8292cbcf-2862-4189-97c2-757bc58a4ed8 Error: Runtime exited with error: exit status 1
Runtime.ExitError

Request ID
8292cbcf-2862-4189-97c2-757bc58a4ed8
</code></pre><p>Oops! Babashka is trying to load the babashka-aws pod that I specified in my <code>src/bb.edn</code>, but I haven&apos;t provided that pod. I could use <code>babashka.pods/load-pod</code> at runtime to grab the pod, but that would mean that my lambda would have a slow cold start. A better idea is to pub the pod on the lambda instance&apos;s filesystem, but how can we do that?</p><p>The hint is in this line:</p><pre><code>Exception in thread &quot;main&quot; java.io.FileNotFoundException: /home/sbx_user1051/.babashka/pods/repository/org.babashka/aws/0.1.2/manifest.edn (No such file or directory)
</code></pre><p>If I can create a <code>.babashka</code> directory in the lambda instance&apos;s home directory, Babashka should find any pods I put there. Of course, Lambda doesn&apos;t let you do that, but it does let you put stuff in <code>/opt</code>, by using a layer. Searching on Clojurians Slack yielded <a href="https://github.com/borkdude">borkdude</a> mentioning an environment variable, <code>$BABASHKA_PODS_DIR</code>, which Babashka will use for the <a href="https://github.com/babashka/pods">pods repository</a>.</p><p>Now I have all the pieces I need. The first step is...</p><div class="markdown-heading"><h2 id="packaging-pods-into-a-layer">Packaging pods into a layer</h2><a href="#packaging-pods-into-a-layer" class="anchor" aria-label="Permalink: Packaging pods into a layer"><img src="assets/link.svg" /></a></div><p>I added a <code>build-pods</code> task to my top-level <code>bb.edn</code>:</p><pre><code class="language-clojure">build-pods {:doc &quot;Builds pods layer&quot;
            :requires ([clojure.java.shell :refer [sh]])
            :task (let [{:keys [target-dir work-dir]} (th/parse-args)
                        work-dir (str work-dir &quot;/pods&quot;)
                        pods-dir (str (fs/home) &quot;/.babashka/pods&quot;)
                        pods-zipfile (th/target-file target-dir &quot;pods.zip&quot;)]
                    (doseq [dir [target-dir work-dir]]
                      (fs/create-dirs dir))

                    (doseq [pod [&quot;org.babashka/aws/0.1.2&quot;]
                            :let [dst (format &quot;%s/.babashka/pods/repository/%s&quot; work-dir pod)]]
                      (when-not (fs/exists? dst)
                        (println &quot;Adding pod&quot; pod)
                        (fs/copy-tree (format &quot;%s/repository/%s&quot; pods-dir pod) dst)))

                    (println &quot;Compressing pods layer&quot; pods-zipfile
                             &quot;from dir:&quot; work-dir)
                    (let [{:keys [exit err]}
                          (sh &quot;zip&quot; &quot;-r&quot; pods-zipfile &quot;.&quot;
                              :dir work-dir)]
                      (when (not= 0 exit)
                        (println &quot;Error:&quot; err))))}
</code></pre><p>What it&apos;s doing is copying the <code>~/.babashka/pods/repository/org.babashka/aws/0.1.2</code> directory into the work dir, then adding it to <code>target/pods.zip</code>.</p><p>Deploying the layer looks like this:</p><pre><code class="language-clojure">deploy-pods {:doc &quot;Deploys pods layer using babashka-aws.&quot;
             :depends [build-pods]
             :requires ([pod.babashka.aws :as aws])
             :task (let [{:keys [pods-layer aws-region target-dir]} (th/parse-args)
                         pods-zipfile (th/target-file target-dir &quot;pods.zip&quot;)
                         client (aws/client {:api :lambda
                                             :region aws-region})
                         zipfile (fs/read-all-bytes pods-zipfile)
                         _ (println &quot;Publishing layer version for layer&quot; pods-layer)
                         res (aws/invoke client {:op :PublishLayerVersion
                                                 :request {:LayerName pods-layer
                                                           :Content {:ZipFile zipfile}}})]
                     (if (:cognitect.anomalies/category res)
                       (prn &quot;Error:&quot; res)
                       (println &quot;Published layer&quot; (:LayerVersionArn res))))}
</code></pre><div class="markdown-heading"><h2 id="adding-the-pods-layer-to-my-lambda">Adding the pods layer to my lambda</h2><a href="#adding-the-pods-layer-to-my-lambda" class="anchor" aria-label="Permalink: Adding the pods layer to my lambda"><img src="assets/link.svg" /></a></div><p>Since I&apos;m already using the Blambda! layer in my lambda, adding a new layer only requires making minor changes to <code>task-helper/create-lambda</code>:</p><ul><li>Add <code>pods-layer</code> to the function arguments<pre><code class="language-clojure"></code></pre></li></ul><p>(defn create-lambda [lambda
                     {:keys [aws-region bb-arch
                             lambda-handler lambda-name lambda-role
                             pods-layer runtime-layer zipfile]}] ;; ... )</p><pre><code>- Add `pods-layer` to `layer-arns`
``` clojure
(let [layer-arns (-&gt;&gt; [runtime-layer]
                    (map #(format &quot;arn:aws:lambda:%s:%s:layer:%s&quot;
                                  aws-region account-id
                                  (latest-layer-version lambda %))))
    ;; ...
    ]
;; ...
)
</code></pre><div class="markdown-heading"><h2 id="making-blambda!-find-my-pods">Making Blambda! find my pods</h2><a href="#making-blambda!-find-my-pods" class="anchor" aria-label="Permalink: Making Blambda! find my pods"><img src="assets/link.svg" /></a></div><p>The only problem left is having Blambda! set <code>BABASHKA_PODS_DIR</code> when starting <code>bb</code>. This is a simple matter of updating the <a href="https://github.com/jmglov/blambda/blob/main/bootstrap"><code>bootstrap</code></a> script in Blambda! itself:</p><pre><code class="language-sh">#!/bin/sh

export BABASHKA_PODS_DIR=/opt/.babashka/pods

cd $LAMBDA_TASK_ROOT
/opt/bb -cp $LAMBDA_TASK_ROOT /opt/bootstrap.clj
</code></pre><p>Now when I test my lambda, I get a much more satisfying result:</p><pre><code>Test Event Name
test

Response
{}

Function Logs
START RequestId: e0d573c2-5afa-4567-af74-592f12efa094 Version: $LATEST
Loading babashka lambda handler:  s3-log-parser/handler
Starting babashka lambda event loop
{:msg &quot;Invoked with event&quot;, :data {:event {:key1 &quot;value1&quot;, :key2 &quot;value2&quot;, :key3 &quot;value3&quot;}}}
END RequestId: e0d573c2-5afa-4567-af74-592f12efa094
REPORT RequestId: e0d573c2-5afa-4567-af74-592f12efa094	Duration: 109.60 ms	Billed Duration: 559 ms	Memory Size: 128 MB	Max Memory Used: 117 MB	Init Duration: 448.61 ms

Request ID
e0d573c2-5afa-4567-af74-592f12efa094
</code></pre><div class="markdown-heading"><h2 id="where-to-next?">Where to next?</h2><a href="#where-to-next?" class="anchor" aria-label="Permalink: Where to next?"><img src="assets/link.svg" /></a></div><p>There is so much wrong and gross here:</p><ul><li>I&apos;m hardcoding the pods that my function needs, rather than resolving them from the function&apos;s <code>bb.edn</code></li><li>I&apos;m assuming that the pod will be in the repo instead of loading it first</li><li>This deployment stuff is kinda neat since it doesn&apos;t require external tools, but also kinda sucks because it doesn&apos;t provide all the goodness that external tools like <a href="https://www.terraform.io/">Terraform</a> do</li><li>This function doesn&apos;t actually do anything, so I don&apos;t know if the pod is actually working</li></ul><p>Stay tuned for more thrilling adventures as I eat my own dogfood!</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-07-03-blambda.html</id>
    <link href="https://jmglov.net/blog/2022-07-03-blambda.html"/>
    <title>Blambda!</title>
    <updated>2022-07-03T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>A couple of weeks ago, I made a <a href="2022-06-21-todo-list.html">todo list</a> for the summer. One of the items on there was to create an AWS Lambda custom runtime for <a href="https://github.com/babashka/babashka">Babashka</a>. I actually accomplished that a few days later, and today I want to walk through the what, the why, and the how of that project.</p><p>Let&apos;s start by answering the question of what a custom runtime is. For anyone not familiar with <a href="https://aws.amazon.com/lambda/">AWS Lambda</a>, it is basically a way to run a function in the AWS cloud without having to worry about how or where the function is actually executed. For me, cloud functions are the next natural step along the path of computing without caring about machines. First came servers that you had to host yourself, then came VMs that you could run on servers you hosted yourself, then came EC2, which gave you a VM hosted by somebody else, then came containers, then came managed container environments like Kubernetes, then came function as a service, which allowed you to provide a zip file that just ran somewhere. You can nitpick the order if you want, but this is more or less accurate. I&apos;m also not claiming that serverless is right for all workloads, but when it is, it&apos;s pretty great.</p><p>So having explained what Lambda is, I&apos;ll crack on with explaining custom runtimes. Lambda comes out of the box with runtimes that support a great variety of programming languages: Python, Golang, .Net, Ruby, JavaScript, and Java. Those last two are of interest to Clojure programmers, since they allow us to write ClojureScript functions and execute them on the NodeJS runtime, or Clojure proper on the Java runtime (you could technically also execute Clojure programs on the .Net runtime using <a href="https://clojure.org/about/clojureclr">Clojure CLR</a>, but I doubt many people are doing that). This is great, unless you need predictably low-ish latency, because the first time you invoke a lambda function, AWS need to spin up an execution environment, then execute your function. This is called a &quot;cold start&quot;, and for the JVM, it can take a few thousand milliseconds, and that&apos;s <strong>before</strong> starting the Clojure runtime, which can take a few thousand more.</p><p>Clojure programmers have long known about this JVM startup delay, of course, which is why we tend not to write command line utilities in Clojure, since it is quite annoying for your utility to take 2-3 seconds just to tell you that you&apos;ve misspelled one of the options (was it <code>--dry-run</code> or <code>--dryrun</code>?). And of course we&apos;ve had ways around that for awhile as well, mostly based on ClojureScript (<a href="https://github.com/anmonteiro/lumo">Lumo</a> is one example). So one could write lambdas in ClojureScript and run them on the NodeJS runtime and not have to wait around for the JVM to start up (the NodeJS runtime has a cold start of a few hundred milliseconds instead of a few <strong>thousand</strong> for the JVM), though there are a few drawbacks with that as well:</p><ol start="1"><li>In order for the NodeJS runtime to execute ClojureScript, it needs to be transpiled to JavaScript, which means you can&apos;t edit it in the lambda console, which makes troubleshooting those annoying problems that only seem to happen when you deploy the thing harder, since you have to add your <code>println</code> statements locally and then compile and then upload and then try again and then realise you need another <code>println</code> somewhere else... ugh! To be fair, JVM Clojure has the same issue.</li><li>You have to use NodeJS. Yuck.</li></ol><p>Luckily, AWS has provided the ability to specify a <a href="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html">custom
runtime</a>, which can be written in any language and just needs to be executable on a Linux system and implement a simple local invocation API. This means that you can now write lambda functions in any language!</p><p>Getting back to Clojure, the wonderful <a href="https://github.com/borkdude">borkdude</a> realised that if one could compile a Clojure program using <a href="https://www.graalvm.org/">GraalVM</a>, it would start up fast, thus enabling command line programs in Clojure that didn&apos;t make you want to pull your hair out. &quot;But why stop there?&quot; borkdude presumably thought to himself. &quot;Writing shell scripts in Bash kinda sucks, so what about writing them in Clojure instead? All I&apos;d have to do is write a program that can interpret Clojure and compile it with GraalVM and then it could execute Clojure scripts or Clojure code passed on the command line and then my life would be complete.&quot; And this magical program, my friends, is called Babashka.</p><p>Since Babashka starts fast and can evaluate Clojure source code, we can build a custom runtime for Lambda that uses Babashka to execute our lambda functions, thus gaining the ability to edit source code in the lambda console <strong>and</strong> use Clojure instead of ClojureScript, both of which are very important to me.</p><p>This was the motivation behind building <a href="https://github.com/jmglov/blambda">Blambda!</a>, which is a custom runtime that can be deployed as a <a href="https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-layer">Lambda
layer</a>. Let&apos;s talk about how it works.</p><p>A custom runtime requires only one thing: an executable named <code>bootstrap</code> in the root level of your lambda function&apos;s archive. When your function is invoked for the first time, the Lambda runtime executes the <code>bootstrap</code> function, which is then expected to call Lambda&apos;s <a href="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next">next invocation
API</a>, which returns the request body of whatever called your lambda function, which the runtime customarily hands off to the actual code implementing your lambda function and then feeds the return value of that to the Lambda <a href="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-response">invocation
response
API</a>, and then waits for the next request and does the same thing all over again.</p><p>In the case of Blambda!, the custom runtime consists of three parts:</p><ul><li>The statically linked Babashka executable itself</li><li>A Clojure program, <a href="https://github.com/jmglov/blambda/blob/f1ab0ecd79e7b9d1ff733927baf68a9551e42d6b/bootstrap.clj"><code>bootstrap.clj</code></a>, that implements the request handling loop described above. I borrowed this from an existing Babashka runtime, <a href="https://github.com/tatut/bb-lambda">bb-lambda</a>, which I decided not to use because it uses Docker, which makes me almost as sad as NodeJS. ;)</li><li>A <a href="https://github.com/jmglov/blambda/blob/f1ab0ecd79e7b9d1ff733927baf68a9551e42d6b/bootstrap"><code>bootstrap</code></a> shell script which uses Babashka to evaluate the above Clojure program</li></ul><p>Packaging this as a layer is as simple as downloading Babashka, then zipping it into an archive with the other two files, which you can see in the <code>build</code> task of Blambda!&apos;s <a href="https://github.com/jmglov/blambda/blob/39519beeae0296508517f292df6de8f5df563dd7/bb.edn#L17"><code>bb.edn</code></a>.</p><p>To use Blambda!, you can build and deploy the custom runtime layer by cloning the repo and running:</p><pre><code>bb deploy
</code></pre><p>You then create a lambda function that uses the &quot;provided&quot; runtime, includes the &quot;blambda&quot; layer that was created by the <code>bb deploy</code> command, and sets the handler to whatever function in your namespace that will handle function invocations. For example, if you have a namespace like this:</p><pre><code class="language-clojure">(ns hello)

(defn hello [{:keys [name] :or {name &quot;Blambda&quot;} :as event} context]
  (prn {:msg &quot;Invoked with event&quot;,
        :data {:event event}})
  {:greeting (str &quot;Hello &quot; name &quot;!&quot;)})
</code></pre><p>you can create a lambda function like this:</p><p><img alt="AWS Lambda console create function page showing the setting of runtime to
&apos;provide your own bootstrap on Amazon Linux 2&apos;" src="assets/2022-07-03-blambda-create-function.png" /></p><p><img alt="AWS Lambda console add layer page showing selecting a custom layer named &apos;blambda&apos;" src="assets/2022-07-03-blambda-add-layer.png" /></p><p><img alt="AWS Lambda console edit runtime settings page showing setting the handler to &apos;hello/hello&apos;" src="assets/2022-07-03-blambda-set-handler.png" /></p><p>and then test it with an event like this:</p><pre><code class="language-json">{
  &quot;name&quot;: &quot;jmglov&quot;
}
</code></pre><p>The Lambda console will display something like this:</p><pre><code>Test Event Name
hello

Response
{
  &quot;greeting&quot;: &quot;Hello jmglov!&quot;
}

Function Logs
START RequestId: 4288f5e7-f4c9-41b2-a26f-b5d688c146ec Version: $LATEST
Loading babashka lambda handler:  hello/hello
Starting babashka lambda event loop
{:msg &quot;Invoked with event&quot;, :data {:event {:name &quot;jmglov&quot;}}}
END RequestId: 4288f5e7-f4c9-41b2-a26f-b5d688c146ec
REPORT RequestId: 4288f5e7-f4c9-41b2-a26f-b5d688c146ec	Duration: 240.41 ms	Billed Duration: 669 ms	Memory Size: 128 MB	Max Memory Used: 97 MB	Init Duration: 427.73 ms

Request ID
4288f5e7-f4c9-41b2-a26f-b5d688c146ec
</code></pre><p>Stay tuned for future posts on Blambda! when I try to actually use it for something real. ;)</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-06-26-loose-ends.html</id>
    <link href="https://jmglov.net/blog/2022-06-26-loose-ends.html"/>
    <title>Tying off loose ends</title>
    <updated>2022-06-26T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>I have been working my way through the <a href="2022-06-21-todo-list.html">old todo
list</a> in the five days since I wrote it, and I wanted to give you an update.</p><p>As I predicted, all of the things that should have definitely happened did in fact definitely happen:</p><ul><li>Fika with Esther. Beers were drunk and shade was sat it. Conversation was had, and verily it was good.</li><li>Stop by the store on the way home from said fika. I got ingredients for harissa and guacamole, though my plans for making and consuming these delicacies did encounter a slight setback, as you will see.</li><li>Walk my dog. Regular as clockwork, that dude gets his walks, though it&apos;s been bloody hot in Stockholm recently (today is 30 degrees!) and thus the poor fella doesn&apos;t look like he&apos;s enjoying them all that much.</li><li>Play Guitar Hero with Simon. This happened, and it happened twice. On the day that I wrote the todo list, the original idea was to drink beer and eat burritos and guacamole and such prior to fucking out, but through an accident of fate, Simon needed to return home for dinner after the shredfest, and thus drove his car over instead of biking. This made beers an impossibility, and I decided that I didn&apos;t want to go to the trouble of making food that I wouldn&apos;t eat until much later, so only Guitar Hero was played. However, I&apos;m happy to admit that my plans for Wednesday fell through because my friend Johan very rudely got the sniffles or something and thus couldn&apos;t make his leaving drinks, so Simon and I reprised our roles as the greatest middle aged rockers to have ever rocked clicky plastic guitars to an adoring crowd of my dog, and this time we did eat the black bean and rice burritos and loads of guacamole and drink some margaritas that I accidentally made double strong.</li></ul><p>Some of the things that were likely to have happened have already happened, and they shall be detailed below!</p><p>The thing that was unlikely to have happened did not in fact happen, but I don&apos;t feel bad about that because I told you it was unlikely to happen anyway so in a way, it&apos;s awesome that it didn&apos;t happen because otherwise I would have been wrong in my prediction that it was unlikely to happen. Of course, the summer isn&apos;t over yet, so it could still be unlikely to happen yet, Mr. Frodo.</p><div class="markdown-heading"><h2 id="https-for-the-blog">HTTPS for the blog</h2><a href="#https-for-the-blog" class="anchor" aria-label="Permalink: HTTPS for the blog"><img src="assets/link.svg" /></a></div><p>I did finally get HTTPS working for my blog, as you can see from the following screenshot that looks something like what you would see in the address bar of your very own browser should you choose to look up there at it:</p><p><img alt="Browser address bar showing a shield and a
lock" src="assets/2022-06-26-address-bar.png" /></p><p>Of course, the URL itself will be a bit different, but you know what I mean.</p><p>So here&apos;s what I needed to do (after following my <a href="2022-06-24-s3-https.html">50 simple
steps</a>, of course):</p><ol start="1"><li>Use the <a href="https://us-east-1.console.aws.amazon.com/acm/home?region=us-east-1#/welcome">AWS Certificate Manager
   console</a> (in the us-east-1 region; this is extremely important!) to create a certificate containing domain names <code>jmglov.net</code> and <code>www.jmglov.net</code>, using DNS validation since I host my own domain using Route 53.</li><li>Open the hosted zone for <code>jmglov.net</code> in the <a href="https://us-east-1.console.aws.amazon.com/route53/v2/hostedzones#">Route 53
   console</a> and manually add the CNAME records displayed on the ACM certificate (for some reason, the <strong>Create records in Route 53</strong> button in ACM didn&apos;t work for me, but whatevs).</li><li>Use the <a href="https://us-east-1.console.aws.amazon.com/cloudfront/v3/home?region=eu-west-1#/">CloudFront
   console</a> to create a distribuion, setting the origin to <code>jmglov.net.s3-website-eu-west-1.amazonaws.com</code>, adding <code>jmglov.net</code> and <code>www.jmglov.net</code> as alternate domain names, choosing the ACM certificate that I just created as the custom SSL certificate, and setting HTTP to redirect to HTTPS.</li><li>Wait for the CloudFront distribution to deploy. You can test this by making sure the S3 hosted site loads when you browse to the distribution domain name that CloudFront creates for you (in my case, <a href="https://d3bulohh9org4y.cloudfront.net">https://d3bulohh9org4y.cloudfront.net</a>).</li><li>Once the website loads using the distribution, use the Route 53 console to update the A records for <code>jmglov.net</code> and <code>www.jmglov.net</code> to alias my CloudFront distribution instead of my S3 bucket.</li></ol><p>Et voilà!</p><p>Oh, and my website logs did of course start showing up in the S3 logs bucket I created, after some delay probably caused by buffering. I also configured my CloudFront distribution to log to the same place, and those logs are also showing up there.</p><div class="markdown-heading"><h2 id="blambda!">Blambda!</h2><a href="#blambda!" class="anchor" aria-label="Permalink: Blambda!"><img src="assets/link.svg" /></a></div><p>I also created an AWS Lambda custom runtime for Babashka, which I have called <a href="https://github.com/jmglov/blambda">Blambda!</a>, because I couldn&apos;t think of a good pun involving BBs and lambdas or something like that.</p><p>This was also quite easy to do, thanks to a <a href="https://github.com/tatut/bb-lambda">bb-lambda</a> project that I found on Github that already took care of the heavy lifting of interacting with the Lambda runtime API to process function invocations.</p><p>I decided to create my own custom runtime instead of just straight up using bb-lambda because it uses <a href="https://www.docker.com/">Docker</a>, which I hate and fear (I don&apos;t even know what a container is, much less why you should use it to implement a serverless function). Thanks to the borktacular <a href="https://github.com/borkdude">borkdude</a> (<a href="https://ko-fi.com/borkdude">toss him a few euros on
Ko-fi</a> if you can) and the fact that he builds a static executable for <a href="https://github.com/babashka/babashka/releases/tag/v0.8.156">each borkin&apos; release of
Babashka</a>, creating a lambda layer for a custom runtime is really easy!</p><div class="markdown-heading"><h2 id="more-stuff-to-do">More stuff to do</h2><a href="#more-stuff-to-do" class="anchor" aria-label="Permalink: More stuff to do"><img src="assets/link.svg" /></a></div><p>Things that are likely to happen:</p><ul><li>Open up my Guitar Hero controller, attempt to fix it, don&apos;t succeed, but also don&apos;t make things any worse.</li><li>Play some Civ V. I had <a href="2022-06-25-midsommar.html">planned to do this
  yesterday</a>, but ran out of time because I ended up going over to Simon and Pippa&apos;s for pizza (red peppers and aubergine / eggplant, thanks for asking!). It is imperative that I do this today, because those Koreans and Ottomans aren&apos;t going to defeat themselves. (Unless of course they turn on each other, which would be totally awesome!)</li><li>Add some cool stuff to Blambda! to make it easier to deploy functions and the like.</li><li>Dig into <a href="https://open.spotify.com/episode/4TPwgRZTOsHPGXuVwJQyHd">REPL-acement</a> with Ray.</li><li>Learn what&apos;s so awesome about <a href="https://nixos.wiki/wiki/Flakes">Nix flakes</a>.</li></ul><p>Things that may happen:</p><ul><li>Open up my Guitar Hero controller, attempt to fix it, and succeed!</li><li>Open up my Guitar Hero controller, attempt to fix it, and bollocks it all up and then cry tears of great sadness and hit <a href="https://www.blocket.se/">Blocket</a> (kinda like a Swedish version of eBay or online garage sale thingy) to try to find a new to me used one.</li></ul><p>Things that are unlikely to happen but really should:</p><ul><li>Learn Swedish.</li></ul></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-06-21-todo-list.html</id>
    <link href="https://jmglov.net/blog/2022-06-21-todo-list.html"/>
    <title>The old todo list</title>
    <updated>2022-06-21T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>I&apos;m getting a late start with the old blogging today, so I&apos;ll make do with a todo list for the summer.</p><p>Things that will definitely happen:</p><ul><li>Take a walk over to a nearby cafe with my friend Esther to have some <a href="https://en.wikipedia.org/wiki/Coffee_culture#Sweden">fika</a>. This is definitely going to happen, as Esther is Dutch and therefore has made an entry in her diary and entries in Dutch diaries are non-negotiable. Also, this event will take place in 15 minutes.</li><li>Stop by the store on the way back from fika and buy a few ingredients for making guacamole and <a href="https://en.wikipedia.org/wiki/Harissa">harissa</a>. No, I will not be eating both of this things together. Unless I decide to put harissa on my black bean burrito that I&apos;m going to also put guacamole on, which actually sounds kinda good now that I say it out loud. I&apos;ll let you know how this crime against food turns out.</li><li>Walk my dog. This will definitely happen at least twice a day, because otherwise Rover gets very sad because he still hasn&apos;t learned to use the big boy potty. Also he needs exercise.</li><li>Play some <a href="https://en.wikipedia.org/wiki/Guitar_Hero:_Warriors_of_Rock">Guitar Hero: Warriors of
  Rock</a> with my friend Simon. This will involve drinking beer and eating some chips with guacamole, as long as I don&apos;t eat all of the guacamole on my burrito like a greedy bastard. Headbanging, throwing horns, and &quot;the man stance&quot; are also likely to feature.</li></ul><p>Things that are likely to happen:</p><ul><li>Create an AWS Lambda custom runtime for <a href="https://github.com/babashka/babashka">Babashka</a>. I want to do this so I can get blazing fast startup times for my lambda functions AND be able to edit the source in the lambda console AND not be subjected to NodeJS in any way, shape, or form. <a href="https://clojurescript.org/">ClojureScript</a> is a wonderful wonderful thing, but to <a href="https://news.ycombinator.com/item?id=4013118">mangle the words</a> of the great Rich Hickey, &quot;Clojure rocks, Node reeks&quot;. Ray and I are in violent disagreement about this, but Ray is wrong and can therefore suck it.</li><li>Enable HTTPS for my blog, because <a href="http://jmglov.net/blog/">http://jmglov.net/blog/</a> is just embarassing. I use S3 static website hosting, and I know there&apos;s a way to use CloudFront plus an ACM (no, not <a href="https://www.acm.org/">that ACM</a>, <a href="https://aws.amazon.com/certificate-manager/">this
  one</a>) cert to do this, but I&apos;m pretty sure it will require a full day, mystic chanting, and the sacrifice of a monitor or two (when I throw it across the room out of frustration).</li><li>Dig into <a href="https://open.spotify.com/episode/4TPwgRZTOsHPGXuVwJQyHd">REPL-acement</a> with Ray.</li><li>Learn what&apos;s so awesome about <a href="https://nixos.wiki/wiki/Flakes">Nix flakes</a>.</li></ul><p>Things that are unlikely to happen but really should:</p><ul><li>Learn Swedish.</li></ul><p>OK, I need to run because otherwise I&apos;m gonna be late for fika, and that just will not do.</p><p><strong>Update:</strong> <a href="2022-06-26-loose-ends.md">I actually did some of these things</a>!</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-06-19-actually-blogging-with-clojure.html</id>
    <link href="https://jmglov.net/blog/2022-06-19-actually-blogging-with-clojure.html"/>
    <title>Actually blogging with Clojure</title>
    <updated>2022-06-19T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><p>I admit that my previous post on <a href="2022-06-17-creating-a-blog-with-clojure.html">how to create a blog with
Clojure</a> may have been slightly tongue in cheek. This one will be less so, since I&apos;ve actually gotten stuff working. ;)</p><p>Assuming that you have <a href="https://github.com/babashka/babashka">Babashka</a> installed (which should be really easy unless you sail into the perfect storm of NixOS + broken zlib), cloning <a href="https://github.com/borkdude/blog">borkdude’s blog
repo</a> from Github should give you quite an easy start.</p><p>Here&apos;s all I needed to do after getting my Babashka issues sorted to make it my own:</p><ol start="1"><li>Clone the repo: <code>git clone git@github.com:borkdude/blog.git</code></li><li>Update <code>bb.edn</code> to change the <code>publish</code> task to do an <code>aws s3 sync</code> to the S3 bucket my website is hosted from instead of rsync-ing to borkdude&apos;s webserver.</li><li>Run <code>rm posts/*.md</code> to get rid of all of borkdude&apos;s content.</li><li>Add a new <code>posts/2022-06-17-creating-a-blog-with-clojure.md</code> file and copy and paste the content from my Medium blog post into it.</li><li>Update <code>posts.edn</code> to remove the metadata for borkdude&apos;s content and replace it with my single post:<pre><code class="language-clojure">{:title &quot;Creating a blog with Clojure in 50 simple steps&quot;
 :file &quot;2022-06-17-creating-a-blog-with-clojure.md&quot;
 :categories #{&quot;clojure&quot;}
 :date &quot;2022-06-17&quot;}
</code></pre></li><li>Update <code>render.clj</code> and change <code>blog-root</code> and <code>atom-feed</code> to reflect that this is my blog and not borkdude&apos;s.</li><li>Update <code>templates/base.html</code> to comment out the Github discussions link to borkdude&apos;s blog (I should put that back in once I make my website repo public) and replace his Twitter username with mine.</li><li>Open a pull request to <a href="https://github.com/ghoseb/planet.clojure">Planet
   Clojure</a> to pick up <a href="http://jmglov.net/blog/atom.xml">http://jmglov.net/blog/atom.xml</a> instead of my Medium feed.</li><li>Run <code>bb publish</code>.</li><li>Check out <a href="http://jmglov.net/blog/">http://jmglov.net/blog/</a> and rejoice!</li></ol><p>So it seems like having your kickass Clojure blog and eating it too only takes 10 easy steps, not 50.</p></div>]]></content>
  </entry>
  <entry>
    <id>https://jmglov.net/blog/2022-06-17-creating-a-blog-with-clojure.html</id>
    <link href="https://jmglov.net/blog/2022-06-17-creating-a-blog-with-clojure.html"/>
    <title>Creating a blog with Clojure in 50 simple steps</title>
    <updated>2022-06-17T23:59:59+00:00</updated>
    <content type="html"><![CDATA[<div><ol start="1"><li>Install <a href="https://nixos.org/">NixOS</a> on your laptop because it’s super cool but also because you hate yourself just a little.</li><li>Come up with the idea of writing something every day this summer and publishing it on “your blog”.</li><li>Try and remember if you have a blog somewhere.</li><li>Try and remember what your password to that blog might have been. Or did you use your Google account to sign up?</li><li>Get lucky when you sign in with Google and you’re dropped into your profile where you have a single blog entry from several years ago and of course a few drafts because why not?</li><li>Start a new blog entry.</li><li>Try to figure out what in the world you’re going to write about.</li><li>Go on a walk with your dog and talk to your friend Ray on the phone (well, Signal audio call, because who uses their phone for actual phoning?) about your nascent blogging career.</li><li>Mention that you’re planning to do your blogging on your own site, using some static site generator or other. Wisely realise that this will be way more work that you think. Predict serious rabbit-holing to your friend.</li><li>Remember that the inimitable <a href="https://www.michielborkent.nl/">borkdude</a> wrote a <a href="https://blog.michielborkent.nl/migrating-octopress-to-babashka.html">blog
    entry</a> about how he’s generating his blog as a static site with <a href="https://github.com/babashka/babashka">Babashka</a>.</li><li>Clone <a href="https://github.com/borkdude/blog">borkdude’s blog</a> from Github because of course the blog itself is open source because borkdude is awesome!</li><li>Add <code>pkgs.babashka</code> to your <a href="https://github.com/jmglov/nixos-config/blob/main/home.nix"><code>home.nix</code></a> and run <code>sudo nixos-rebuild switch</code> to install it.</li><li>Run <code>bb render</code> and get excited as Babashka downloads the <a href="https://github.com/clj-kondo/clj-kondo">clj-kondo</a> pod.</li><li>Cry tears of sadness as Babashka errors out with:<pre><code>java.util.zip.ZipException: invalid entry CRC (expected 0x7463ff01 but got
0x6bbe279e)
</code></pre></li><li>Realise that you’re about a million versions behind the most current Babashka.</li><li>Check <a href="https://github.com/NixOS/nixpkgs/blob/a153c90eec38d1a5694c3a8793f5732608b94e8f/pkgs/development/interpreters/clojure/babashka.nix"><code>babashka.nix</code></a> on the main branch of <a href="https://github.com/NixOS/nixpkgs">nixpkgs</a> to see what the latest available version is.</li><li>Get excited when you see that someone has just upgraded to the latest version of Babashka last week.</li><li>Update your home.nix to pull Babashka (and just Babashka) from nixpkgs at the commit where it was updated because you can do that in Nix and you knew that Nix rules previously so that’s why you’re running NixOS like a boss! (Also, because you hate yourself just a little.)</li><li>Run <code>bb render</code> again, triumphant in the knowledge that it’s going to work now that it’s on the latest version, because the latest version of any given piece of software has fixed all of the bugs.</li><li>Get a permission denied error when Babashka tries to execute clj-kondo.</li><li><code>ls -l ~/.babashka/pods/repository/borkdude/clj-kondo/2021.10.19/clj-kondo</code></li><li>See that in fact the execute bit is not set.</li><li>Surmise that this is because the clj-kondo pod failed to install due to the <code>ZipException</code>.</li><li><code>rm -rf ~/.babashka/pods/repository/ &amp;&amp; bb render</code></li><li>Get the same bloody ZipException.</li><li>Try to remember your password to <a href="https://clojurians.slack.com/">Clojurians
    Slack</a>.</li><li>Install the desktop Slack client by adding pkgs.slack to your home.nix.</li><li>Revel in the glory of Nix.</li><li>Get a magic signin link from the Slack client to your email.</li><li>See that your friend Ray DM’d you back in 2019 to ask if you were going to <a href="https://clojutre.org/">ClojuTre</a> and you totally ghosted him because you apparently hadn’t logged into Clojurians Slack since the spring of 2018.</li><li>See if there’s a #babashka channel on Clojurians Slack and breathe a sigh of relief when of course there is!</li><li>Post about your problem in #babashka.</li><li>Wait 42 seconds for borkdude himself (creator of Babashka and about a zillion other awesome open source thingies, mostly Clojure-related) to answer your question.</li><li>Provide borkdude with the version of zlib you’re using to validate his theory.</li><li>Watch as borkdude pings in some badass Nix expert to help and wait 42 more seconds before said badass arrives.</li><li>Provide the badass with a 14 line <code>bb.nix</code> that reproduces the problem on any Nix installation because that’s how Nix works.</li><li>Whilst the badass works on a proper fix (applying the Arch Linux patch where they fixed the zlib issue to the zlib derivation that the graalvm derivation depends on, obviously), attempt to create a Nix overlay that pins zlib to 1.2.11, the last version that works with GraalVM.</li><li>Ask yourself WTF is happening when you keep getting infinite recursion when evaluating your new Babashka derivation that uses the overlay that pins zlib.</li><li>Find out that apparently you <a href="https://github.com/NixOS/nixpkgs/issues/61682">can’t override zlib in an
    overlay</a> because <code>pkgs.stdlib</code> for Linux includes zlib.</li><li>Despair when borkdude points you to a Nix flake that you could probably hack up to work around the problem because you haven’t had the time to wrap your head around <a href="https://nixos.wiki/wiki/Flakes">Nix flakes</a>.</li><li>Walk your dog and talk to Ray on Signal and describe the rabbit hole and laugh when he says that your words from the previous chat were prophetic when you said that building your blog in Clojure would result in a rabbit hole.</li><li>Be proud of yourself for writing your daily blog entry <strong>before</strong> messing around with this stuff.</li><li>Make some oatmeal for yourself and your son.</li><li>Start to head back to your desk to keep hacking but then realise that the sun is shining so go outside and play football with your son instead.</li><li>[Optional step] Go out to supper with some good friends from the union and drink your troubles away.</li><li>Watch some Star Trek: The Next Generation even though your friend Sen hates on it all the time because she thinks TOS is better even though she’s wrong and is super mean about it when you try to convince her she’s wrong but that’s OK because she just got a dope NCC-1701 tattoo so all is forgiven and she’s actually the best anyway because she’s chair of the local union and a total badass.</li><li>Fall asleep on the couch for half an hour but then do the responsible thing and brush your teeth and take the dog out for a wee before getting in bed.</li><li>Sleep pretty damned well even though your rib is aching like wild because you broke it 7 years ago and then broke it again 6 years ago (and when you say you broke it, what you actually mean is that some wanker broke it for you during football training, and then a really nice guy from work who was going in fairly for a 50–50 challenge caught you in the same rib with his shoulder a year later and broke it for you again) and then some 20-something wanker from Brommapojkarna (they really need to change their name, the sexist bastards) performed a full-on hockey-style body check on you during a 7-a-side football match last week and hit the damned rib but luckily it didn’t break this time but just bruised pretty badly.</li><li>Wake up and see that the Nix badass has opened a PR to nixpkgs that fixes your issue.</li><li>Responsibly write a blog entry on how to write a blog in Clojure in 50 easy steps before you try out the fix from the badass’s branch.</li></ol><p>See, toldya it was easy!</p><p><img alt="The Clojure logo" src="img/clojure-logo.png" /></p><p>PS: I did write a blog entry and publish it yesterday, but it was a guest piece for my friend Tim’s blog: <a href="https://7amkickoff.com/index.php/2022/06/16/story-of-a-mediocre-fan/">“Story of a mediocre
fan”</a>. I guess next time I do that, I should at least link it here so I have a record of having written something for posterity.</p></div>]]></content>
  </entry>
</feed>
