Heroku Clojure application exit hook - heroku

The entrance point for my clojure app is -main, but is there a function that is called upon the application's exit? I need to close some connections when my Heroku dyno goes down, but can't figure out where or how to do that.

As Diego Basch said, use a JVM shutdown hook.
This is what I usually do when I need to do so:
(defn -main
[& args]
((start ...)
(.. (Runtime/getRuntime) (addShutdownHook (proxy [Thread] []
(run []
(stop ...)))))))

Related

jdbc connections in clojure are garbage collected prematurely

I am using the [com.impossibl.pgjdbc-ng/pgjdbc-ng "0.7.1"] library to connect to a postgres database.
The connection is saved inside an atom.
I then arm multiple listeners like so:
(doto (.createStatement (connection f))
(.execute (format "LISTEN %s;" event))
(.closeOnCompletion)))
f in this case is a function called when the event triggers.
For some reason it does not take long until the connection seems to be garbage collected, which obviously makes the listeners non-functioning.
WARNING: Cleaning up leaked connection ( jdbc:pgsql://my-container/database )
This warning is followed by a stacktrace to where I opened the connection in the arm-listeners method.
I tried several things, like store the connection in a let, but none seemed to help with this specific issue.
The complete function to establish the connection and start the listener which I use are those: https://github.com/n2o/postgres-listener/blob/master/src/postgres_listener/core.clj
This is how I start the listeners:
(defn start-listeners
"Start all important listeners."
[]
(connect {:host (System/getenv "DB_HOST")
:port (read-string (System/getenv "DB_PORT"))
:database (System/getenv "DB_NAME")
:user (System/getenv "DB_USER")
:password (System/getenv "DB_PW")})
(arm-listener handle-textversions "textversions_changes")
(arm-listener handle-statements "statements_changes")
(arm-listener handle-arguments "arguments_changes")
It seems that using the connection in a let statement and than returning it, helps the JVM not to collect the reference.
So something like this would help:
(let [conn (connect <...>)
a (arm-listener f name)]
conn)
I'll keep the question open for a while, in case somebody has another answer.

Clojure Sente: Sente sends a follow up message to the client after page load and destroys the view

I'm quite confused about why sente is sending the client a message all on its own around 8 seconds after the page is initially loaded. What else is strange, is that if I quickly send a message to the server over the websocket before this happens, everything stabilizes and the view doesn't crash.
For reference, the front-end is clojurescript with reagent, and its a luminus project. For further reference, its pretty much exactly the sample application from chapter 5 of "web development with clojure".
I can tell that its the server pushing a message to the client that's causing the problem, I just don't know enough about Sente to understand why it would even be doing this.
Here's what I think the relevant code is:
Server side:
(defn save-message! [message]
(if-let [errors (validate-message message)]
{:errors errors}
(do
(db/save-message! message)
message)))
(defn handle-message! [{:keys [id client-id ?data]}]
(when (= id :guestbook/add-message)
(let [response (-> ?data
(assoc :timestamp (java.util.Date.))
save-message!)]
(if (:errors response)
(chsk-send! client-id [:guestbook/error response])
(doseq [uid (:any #connected-uids)]
(chsk-send! uid [:guestbook/add-message response]))))))
Client side (with reagent):
(defn response-handler [messages fields errors]
(fn [{[_ message] :?data}]
(if-let [response-errors (:errors message)]
(reset! errors response-errors)
(do
;; Fires right before the view crashes!
(.log js/console "response-handled")
(reset! errors nil)
(reset! fields nil)
(swap! messages conj message)))))
(defn home []
(let [messages (atom nil)
fields (atom nil)
errors (atom nil)]
(ws/start-router! (response-handler messages fields errors))
(get-messages messages)
(fn []
[:div
[:div.row
[:div.span12
[message-list messages]]]
[:div.row
[:div.span12
[message-form fields errors]]]])))
The problem is that when sente sends the message on its own there is no data to update the messages (or atleast that's my best guess), so the atom's fields become null and reagent (react.js) throws trying to diff and patch from the vdom.
If anyone knows what sente is doing it would be very much appreciated. This exact same set up works fine when you use Immutant's async socket support, and do a lot of the work yourself (serialize/deserialize, handle connections etc).
;;;;;;;;
As a follow up, I solved the issue by filtering for non nil messages:
(defn response-handler [messages fields errors]
(fn [{[_ message] :?data}]
(if-let [response-errors (:errors message)]
(reset! errors response-errors)
(when (not= message nil)
(reset! errors nil)
(reset! fields nil)
(swap! messages conj message)))))
Still, this is kind of a bandage solution, it would be nice to know why Sente throws a message at me after the page loads if the socket isn't used immediately.
You can inspect what is happening by looking at the network tab in the developer tools; there should be a sub-tab for websocket frames.
Sente sends some events on its own, and the event name (a keyword which is the first element of the event vector) is in the chsk namespace if I remember correctly. I believe that you should use some kind of dispatch on the event names anyway, and not assume that only one kind of event will arrive.
In the context of re-frame, I have been filtering the unwanted events and dispatching the rest to the re-frame event loop. I guess that you could do something similar in luminus. On the server side, I have been using multimethods in a similar setting.

What is the idiomatic way to stop the event propagation with core.async (ClojureScript)?

I have a very simple use case: in a text area, I want to stop the event propagation for some key codes and trigger some function f, and for other key codes, I just trigger some function g.
So I've defined a channel called out and a listener, which is putting all keypress events to the channel:
(events/listen
(dom/getElement "input")
"keypress"
(fn [e] (put! out e)))
And here comes the crux: where should I stop the event propagation? To do it after I extracted the event from the channel seems logically to late and, as expected, doesn't work. To stop the event propagation within the handler as shown above seems to be idiomatically wrong. And I really don't want to put any logic into the pre-channel handlers: why would I use core.async then, if I do all the work in the listener directly?
So how is it supposed to work then?
I think #edbond's answer above is correct, and if you have versions of clojure, clojurescript and core.async that are up to date enough to support transducers, you should go with that.
If you are on an older stack, you can use the filter> fn to apply filtering on the channel:
(def ch (async/filter> even? (async/chan)))
(go-loop [msg (async/<! ch)]
(when msg
(println msg)
(recur (async/<! ch))))
(go
(async/put! ch 1) ;; does nothing
(async/put! ch 2)) ;; prints 2

How to prevent overlapping animations using core.async?

I have this loop handling animations for a character -- set-image! just takes a key and displays the appropriate image.
(defn main-animation-loop []
(go (while true
(set-image! :normal)
(<! (timeout 8000))
(set-image! :blink)
(<! (timeout 150)))))
Every once in a while the character needs to do some special actions. This should be able to interrupt the main animation:
(defn dance! []
(go (set-image! :look-left)
(<! (timeout 1000))
(set-image! :look-right)
(<! (timeout 1000))
(set-image! :wave)
(<! (timeout 2000))))
What's a good way to pause the main animation while the dance routine is happening?
It's common in CSP style programming to pass a control channel to event loops so you can, at the very least tell them when to stop. In this case if there was a control channel that went to main-animation-loop and you gave a copy of that to dance!, then dance could tell main-animation-loop to pause and unpause appropriatly. Or stop it then start it again (passing the same control channel in case others are using it).
I use a pattern like this to check for messages each time around the event loop:
(go (while (not= control-chan
(second (async/alts! [control-chan (async/timeout arg)])))
(do-stuff-here))
This checks to see if it was the timeout or the control channel that caused the interruption.
(defn main-animation-loop [control-chan]
(go (while (not= control-chan
(second (async/alts! [control-chan (async/timeout 150)])))
(set-image! :normal)
(<! (timeout 8000))
(set-image! :blink))))
(defn dance! [control-chan]
(go (!> control-chan :stop)
(set-image! :look-left)
(<! (timeout 1000))
(set-image! :look-right)
(<! (timeout 1000))
(set-image! :wave)
(<! (timeout 2000))
(main-animation-loop control-chan)))
By passing the same channel to both functions, you allow them to communicate with each other. main-animation-loop will keep looping as long as all the messages it receives are coming from the timeout channel. As soon as it sees that one of them came from the control channel instead of the timeout, it will stop. This allows dance! to tell it to stop by sending any message to the control channel. In similar code I often have the main event loop check the content of the message and do more than just stop, though in this case stopping is enough because dance! can simply start the event loop again.

Why the thread is not executing (Racket)

I have a program and one func of it takes too long, say longfunc (the specific thing done in the longfunc is a bunch of files generated). so I want to use thread asynchronously executed this longfunc. However, when I wrote like the following, it does not really execute longfunc since there are no files generated...
(thread
(λ ()
(longfunc arg1 arg2)))
and when I get the above thread descriptor, testing whether the thread is running, it says true, this is so weird...
Can anybody explain what's going on with the thread? Is it because of some inner scheduling scheme? how to make the thread run normally?
The thread should start and run normally. For instance, running this program
#lang racket
(thread (lambda ()
(for ([i 10])
(sleep 2)
(printf "thread 1\n"))))
(thread (lambda ()
(for ([i 20])
(sleep 1)
(printf "thread 2\n"))))
should show you both threads running at once.

Resources