Skip to content

Commit

Permalink
Merge pull request #13 from xtdb/refactor+version
Browse files Browse the repository at this point in the history
Some refactoring + include the xt version + warm up xt on startup
  • Loading branch information
Akeboshiwind authored Mar 8, 2024
2 parents b5e2cca + 19891fb commit 92ea314
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 86 deletions.
17 changes: 0 additions & 17 deletions resources/public/index.html

This file was deleted.

2 changes: 1 addition & 1 deletion shadow-cljs.edn
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@


:output-dir "resources/public/js/compiled"
:asset-path "/js/compiled"
:asset-path "/public/js/compiled"
:dev {:compiler-options {:devcards true}}
:release {:compiler-options {:warnings-as-errors true
:warnings {:redef-in-file false}
Expand Down
91 changes: 37 additions & 54 deletions src/server.clj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
(:require [clojure.edn :as edn]
[clojure.spec.alpha :as s]
[clojure.tools.logging :as log]
[clojure.core.match :refer [match]]
[integrant.core :as ig]
[muuntaja.core :as m]
[reitit.coercion.spec :as rcs]
Expand All @@ -14,15 +13,14 @@
[ring.adapter.jetty :as jetty]
[ring.middleware.params :as params]
[ring.util.response :as response]
[xtdb.error :as err]
[xtdb.api :as xt]
[xtdb.node :as xtn]))
[xtdb.node :as xtn]
[hiccup.page :as h]))

(s/def ::txs string?) ; Always EDN
(s/def ::query string?) ; Either XTQL or SQL
(s/def ::txs string?)
(s/def ::query string?)
(s/def ::db-run (s/keys :req-un [::txs ::query]))


(defn- handle-ex-info [ex req]
{:status 400,
:body {:message (ex-message ex)
Expand All @@ -37,13 +35,37 @@
{xtdb.IllegalArgumentException handle-ex-info
xtdb.RuntimeException handle-ex-info})))

(def xt-version
(-> (slurp "deps.edn")
(edn/read-string)
(get-in [:deps 'com.xtdb/xtdb-core :mvn/version])))
(assert (string? xt-version) "xt-version not present")

(def index
(h/html5
[:head
[:meta {:charset "utf-8"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
[:meta {:name "description" :content ""}]
[:link {:rel "stylesheet" :href "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css"}]
[:link {:rel "stylesheet" :type "text/css" :href "/public/css/main.css"}]
[:script {:src "https://cdn.tailwindcss.com"}]
[:title "XT Fiddle"]]
[:body
[:div {:id "app"}]
[:script {:type "text/javascript" :src "/public/js/compiled/app.js"}]
[:script {:type "text/javascript"}
(str "var xt_version = '" xt-version "';")]
[:script {:type "text/javascript"}
"xt_fiddle.client.init()"]]))

(defn router
[]
(ring/router
[["/"
{:get {:summary "Fetch main page"
:handler (fn [_request]
(-> (response/resource-response "public/index.html")
(-> (response/response index)
(response/content-type "text/html")))}}]

["/status"
Expand All @@ -55,11 +77,10 @@
{:post {:summary "Run transactions + a query"
:parameters {:body ::db-run}
:handler (fn [request]
(let [{:keys [txs query] :as body} (get-in request [:parameters :body])
(let [{:keys [txs query]} (get-in request [:parameters :body])
;; TODO: Filter for only the reader required?
txs (edn/read-string {:readers *data-readers*} txs)
query (edn/read-string {:readers *data-readers*} query)]
#_(log/info :requst-data {:txs txs :query query})
(try
(with-open [node (xtn/start-node {})]
(xt/submit-tx node txs)
Expand All @@ -69,10 +90,9 @@
(catch Exception e
(log/warn :submit-error {:e e})
(throw e)))))}}]
;; TODO put static resources under path without conflicts
["/*" (ring/create-resource-handler)]]
{:conflicts (constantly nil)
:exception pretty/exception

["/public/*" (ring/create-resource-handler)]]
{:exception pretty/exception
:data {:coercion rcs/coercion
:muuntaja m/instance
:middleware [params/wrap-params
Expand All @@ -84,6 +104,10 @@

(defn start
[{:keys [join port] :or {port 8000}}]
; NOTE: This ensure xtdb is warmed up before starting the server
; Otherwise, the first few requests will fail
(with-open [node (xtn/start-node {})]
(xt/status node))
(let [server (jetty/run-jetty (ring/ring-handler
(router)
(ring/routes
Expand All @@ -98,44 +122,3 @@

(defmethod ig/halt-key! ::server [_ server]
(.stop server))

(comment
(def server (start {:join false}))
(do
(.stop server)
(def server (start {:join false})))

(require '[clojure.java.browse :as browse])
(browse/browse-url "http://localhost:8000")

;; testing the db-run route
(require '[hato.client :as client])

;; XTQL
(def txs (pr-str "[(xt/put :docs {:xt/id 1 :foo \"bar\"})]"))
(def query (pr-str '(from :docs [xt/id foo])))

(-> (client/request {:accept :json
:as :string
:request-method :post
:content-type :json
:form-params {:txs txs :query query}
:url "http://localhost:8000/db-run"
:throw-exceptions? false} {})
:body)
;; => "[{\"foo\":\"bar\",\"xt/id\":1}]"

;; SQL
(def txs ["INSERT INTO users (xt$id, name) VALUES ('jms', 'James'), ('hak', 'Håkan')"])
(def query "SELECT * FROM users")

(-> (client/request {:accept :json
:as :string
:request-method :post
:content-type :json
:form-params {:txs txs :query query}
:url "http://localhost:8000/db-run"
:throw-exceptions? false} {})
:body))


31 changes: 17 additions & 14 deletions src/xt_fiddle/client.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@
(rf/reg-event-fx
:app/init
[(rf/inject-cofx ::query-params/get)]
(fn [{:keys [query-params]} _]
(fn [{:keys [query-params]} [_ xt-version]]
(let [{:keys [type txs query]} query-params
type (if type (keyword type) :sql)]
{:db {:type type
{:db {:version xt-version
:type type
:txs (if txs
(js/atob txs)
(default-txs type))
Expand All @@ -50,7 +51,8 @@
(rf/reg-event-fx
:share
(fn [{:keys [db]}]
{::query-params/set {:type (name (:type db))
{::query-params/set {:version (:version db)
:type (name (:type db))
:txs (js/btoa (:txs db))
:query (js/btoa (:query db))}}))

Expand All @@ -74,18 +76,19 @@

(rf/reg-sub
:get-type
(fn [db _]
(:type db)))
:-> :type)

(rf/reg-sub
:txs
(fn [db _]
(:txs db)))
:-> :txs)

(rf/reg-sub
:query
(fn [db _]
(:query db)))
:-> :query)

(rf/reg-sub
:version
:-> :version)

(rf/reg-sub
:app/loading
Expand Down Expand Up @@ -139,13 +142,11 @@

(rf/reg-sub
:twirly?
(fn [db _]
(:show-twirly db)))
:-> :show-twirly)

(rf/reg-sub
:results-or-failure
(fn [db _]
(select-keys db [:results :failure])))
:-> #(-> % (select-keys [:results :failure])))


(defn language-dropdown []
Expand Down Expand Up @@ -238,6 +239,8 @@
[language-dropdown]
[button {:on-click #(rf/dispatch [:share])}
[title "Share"]]
[:span {:class "text-sm text-gray-400"}
@(rf/subscribe [:version])]
[:div {:class "flex-grow"}]
[button {:on-click #(rf/dispatch [:db-run])}
[title "Run!"]]]]
Expand Down Expand Up @@ -278,7 +281,7 @@
(log/info :start "start")
(hljs/registerLanguage "clojure" hljs-clojure)
(hljs/registerLanguage "json" hljs-json)
(rf/dispatch-sync [:app/init])
(rf/dispatch-sync [:app/init js/xt_version])
(reagent.dom/render [app] (js/document.getElementById "app")))

(defn ^:export init []
Expand Down

0 comments on commit 92ea314

Please sign in to comment.