Use HTMX-compatible HTML fragments on WebSocket, fix multi-connection

- WebSocket sends HTML fragments with id="price-display" instead of JSON
  for direct HTMX OOB swap on the client
- Switch from ring-undertow-adapter ws wrapper to raw Undertow WebSocket
  API (proxy) to fix single-connection limitation
- Keep JSON endpoint at /api/price/latest unchanged
- Update CLAUDE.md and README.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-23 22:28:24 +01:00
co-authored by Claude Opus 4.6
parent 9283826ac4
commit 917b020be4
3 changed files with 56 additions and 30 deletions
+1 -1
View File
@@ -44,7 +44,7 @@ Docker runs alongside local dev on different ports and databases:
## API Endpoints ## API Endpoints
- `GET /api/health` — Health check - `GET /api/health` — Health check
- `GET /api/price/ws` — WebSocket endpoint for live JSON price updates - `GET /api/price/ws` — WebSocket endpoint for live HTML price fragments (HTMX-compatible)
- `GET /api/price/latest` — Latest price as JSON - `GET /api/price/latest` — Latest price as JSON
## Source Layout ## Source Layout
+2 -2
View File
@@ -1,12 +1,12 @@
# btcdata # btcdata
Bitcoin data backend service. Fetches BTC prices from Binance (WebSocket) and Kraken (HTTP polling), stores them in PostgreSQL, and exposes a JSON API with Server-Sent Events for live price streaming. Bitcoin data backend service. Fetches BTC prices from Binance (WebSocket) and Kraken (HTTP polling), stores them in PostgreSQL, and exposes a JSON API with WebSocket for live price streaming.
## API ## API
| Endpoint | Description | | Endpoint | Description |
|---|---| |---|---|
| `GET /api/price/stream` | SSE stream — emits `price-update` events with JSON `{price, prev_price, recorded_at}` | | `GET /api/price/ws` | WebSocket — sends HTML fragments with live price updates (HTMX-compatible) |
| `GET /api/price/latest` | Latest price as JSON | | `GET /api/price/latest` | Latest price as JSON |
| `GET /api/health` | Health check | | `GET /api/health` | Health check |
+53 -27
View File
@@ -9,11 +9,13 @@
[reitit.ring.coercion :as coercion] [reitit.ring.coercion :as coercion]
[reitit.ring.middleware.muuntaja :as muuntaja] [reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.parameters :as parameters] [reitit.ring.middleware.parameters :as parameters]
[reitit.swagger :as swagger] [reitit.swagger :as swagger])
[ring.adapter.undertow.websocket :as ws])
(:import (:import
[io.undertow.server HttpServerExchange] [io.undertow.server HttpServerExchange]
[io.undertow.websockets.core WebSockets WebSocketChannel] [io.undertow.websockets WebSocketConnectionCallback WebSocketProtocolHandshakeHandler]
[io.undertow.websockets.core AbstractReceiveListener WebSockets WebSocketChannel]
[java.time Instant ZoneId]
[java.time.format DateTimeFormatter]
[java.util.concurrent LinkedBlockingQueue TimeUnit])) [java.util.concurrent LinkedBlockingQueue TimeUnit]))
(defn- price->json [{:keys [price prev-price recorded-at]}] (defn- price->json [{:keys [price prev-price recorded-at]}]
@@ -22,32 +24,56 @@
:prev_price (when prev-price (str prev-price)) :prev_price (when prev-price (str prev-price))
:recorded_at (str recorded-at)})) :recorded_at (str recorded-at)}))
(def ^:private ts-fmt (DateTimeFormatter/ofPattern "dd-MM HH:mm:ss"))
(defn- price->html [{:keys [price prev-price recorded-at]}]
(let [p (double (bigdec price))
pp (when prev-price (double (bigdec prev-price)))
color (cond
(nil? pp) "text-gray-900"
(> p pp) "text-green-600"
(< p pp) "text-red-600"
:else "text-gray-900")
ts (.format (.atZone (Instant/from recorded-at) (ZoneId/systemDefault)) ts-fmt)]
(str "<div id=\"price-display\">"
"<div class=\"bg-white rounded-2xl shadow-sm border border-gray-200 p-6\">"
"<div class=\"text-center\">"
"<p class=\"text-4xl font-bold " color "\">$" (format "%,.2f" p) "</p>"
"<p class=\"text-xs text-gray-400 mt-2\">Updated " ts "</p>"
"</div></div></div>")))
(defn- start-ws-send-loop! [^WebSocketChannel channel price-atom]
(let [queue (LinkedBlockingQueue.)
wkey (keyword (gensym "ws-"))]
(.set (.getReceiveSetter channel)
(proxy [AbstractReceiveListener] []))
(.resumeReceives channel)
(add-watch price-atom wkey
(fn [_ _ _ v] (.offer queue v)))
(when-let [v @price-atom]
(.offer queue v))
(future
(try
(loop []
(when (.isOpen channel)
(if-let [v (.poll queue 15 TimeUnit/SECONDS)]
(WebSockets/sendTextBlocking (price->html v) channel)
(WebSockets/sendTextBlocking "" channel))
(recur)))
(catch Exception _)
(finally
(remove-watch price-atom wkey)
(when (.isOpen channel)
(try (.close channel) (catch Exception _))))))))
(defn- ws-price-handler [{:keys [binance]} req] (defn- ws-price-handler [{:keys [binance]} req]
(let [^HttpServerExchange exchange (:server-exchange req) (let [^HttpServerExchange exchange (:server-exchange req)
price-atom (:latest-price binance)] price-atom (:latest-price binance)
(ws/ws-request exchange nil callback (proxy [WebSocketConnectionCallback] []
(ws/ws-callback (onConnect [_ws-exchange channel]
{:on-open (start-ws-send-loop! channel price-atom)))
(fn [{:keys [^WebSocketChannel channel]}] handler (WebSocketProtocolHandshakeHandler. callback)]
(let [queue (LinkedBlockingQueue.) (.handleRequest handler exchange)
wkey (keyword (gensym "ws-"))]
(add-watch price-atom wkey
(fn [_ _ _ v] (.offer queue v)))
(when-let [v @price-atom]
(.offer queue v))
(future
(try
(loop []
(when (.isOpen channel)
(if-let [v (.poll queue 15 TimeUnit/SECONDS)]
(WebSockets/sendTextBlocking (price->json v) channel)
(WebSockets/sendTextBlocking "{\"ping\":true}" channel))
(recur)))
(catch Exception _)
(finally
(remove-watch price-atom wkey)
(when (.isOpen channel)
(try (.close channel) (catch Exception _))))))))}))
nil)) nil))
(defn- latest-price-handler [{:keys [binance]} _req] (defn- latest-price-handler [{:keys [binance]} _req]