I am am trying to setup LevelDB in a ring/compojure app, and looking for an idiomatic way to to access the opened db descriptor into each request.
For example:
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Opening LevelDB file in db/main")
(with-open [main-db (db/open "db/main")]
(println "Running server on port 3000")
(run-jetty #'web/app {:port 3000})))
How do you access the main-db
descriptor into the request handlers?
ie.:
(defroutes handler
(GET "/test" []
(db/put main-db (.getBytes "testKey2") (.getBytes "testValue2"))
"<h1>Hello World</h1>")
PS: I am using the leveldb-clj lib from Sedward and packaged it into a clojar: https://clojars.org/org.clojars.aircart/leveldb-clj
If you want a single global descriptor in your app, the simplest option might be to store a promise or delay in a top-level Var:
(def level-db-descriptor (promise))
(defn open [...]
...
(deliver level-db-descriptor ...))
(open ...)
;; or
(def level-db-descriptor (delay (open ...)))
Then say @level-db-descriptor
when you need to get at it.
This is not that great if you need to replace the descriptor occasionally; you can, however, support that too while preserving the @level-db-descriptor
pattern of usage:
(defprotocol PDescriptorBox
(put-descriptor! [this d])
(get-descriptor [this]))
(defn make-descriptor-box []
(let [box (clojure.lang.Box. nil)]
(reify
clojure.lang.IDeref
(deref [this] (get-descriptor this))
PDescriptorBox
(get-descriptor [this]
(locking this
(.-val box)))
(put-descriptor! [this d]
(locking this
(set! (.-val box) d))))))
You could replace put-descriptor!
with something more sophisticated, of course (perhaps producing a new descriptor only after doing something with the old one).
If you want to be able to run multiple instances of your app in parallel, then those individual instances will likely use some sort of state containers and you'll probably want to use those to store your descriptors rather than top-level Vars.