Skip to content
Newer
Older
100644 182 lines (165 sloc) 7.62 KB
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
1 (ns ^{:author "Chas Emerick"}
2 clojure.tools.nrepl.middleware.interruptible-eval
3 (:require [clojure.tools.nrepl.transport :as t]
4 clojure.main)
5 (:use [clojure.tools.nrepl.misc :only (response-for returning)])
6 (:import clojure.lang.LineNumberingPushbackReader
7 (java.io StringReader Writer)
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
8 java.util.concurrent.atomic.AtomicLong
9 (java.util.concurrent ArrayBlockingQueue LinkedBlockingQueue
10 TimeUnit ThreadPoolExecutor
11 ThreadFactory)))
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
12
13 (def ^{:dynamic true
14 :doc "The message currently being evaluated."}
15 *msg* nil)
16
17 (defn evaluate
18 "Evaluates some code within the dynamic context defined by a map of `bindings`,
19 as per `clojure.core/get-thread-bindings`.
20
21 Uses `clojure.main/repl` to drive the evaluation of :code in a second
22 map argument (either a string or a seq of forms to be evaluated), which may
23 also optionally specify a :ns (resolved via `find-ns`). The map MUST
24 contain a Transport implementation in :transport; expression results and errors
25 will be sent via that Transport.
26
27 Returns the dynamic scope that remains after evaluating all expressions
28 in :code.
29
30 It is assumed that `bindings` already contains useful/appropriate entries
31 for all vars indicated by `clojure.main/with-bindings`."
32 [bindings {:keys [code ns transport] :as msg}]
33 (let [bindings (atom (merge bindings (when ns {#'*ns* (-> ns symbol find-ns)})))]
34 (try
35 (clojure.main/repl
36 :init (fn [] (push-thread-bindings @bindings))
37 :read (if (string? code)
38 (let [reader (LineNumberingPushbackReader. (StringReader. code))]
39 #(read reader false %2))
40 (let [q (java.util.concurrent.ArrayBlockingQueue. (count code) false code)]
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
41 #(or (.poll q 0 TimeUnit/MILLISECONDS) %2)))
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
42 :prompt (fn [])
43 :need-prompt (constantly false)
44 ; TODO pretty-print?
45 :print (fn [v]
46 (reset! bindings (assoc (get-thread-bindings)
47 #'*3 *2
48 #'*2 *1
49 #'*1 v))
50 (t/send transport (response-for msg
51 {:value v
52 :ns (-> *ns* ns-name str)})))
53 ; TODO customizable exception prints
54 :caught (fn [e]
55 (let [root-ex (#'clojure.main/root-cause e)]
56 (when-not (instance? ThreadDeath root-ex)
57 (reset! bindings (assoc (get-thread-bindings) #'*e e))
58 (t/send transport (response-for msg {:status :eval-error
59 :ex (-> e class str)
60 :root-ex (-> root-ex class str)}))
61 (clojure.main/repl-caught e)))))
62 @bindings
63 (finally
64 (pop-thread-bindings)
65 (.flush ^Writer (@bindings #'*out*))
66 (.flush ^Writer (@bindings #'*err*))))))
67
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
68 (defn- configure-thread-factory
69 "Returns a new ThreadFactory for the given session. This implementation
70 generates daemon threads, with names that include the session id."
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
71 []
72 (let [session-thread-counter (AtomicLong. 0)]
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
73 (reify ThreadFactory
74 (newThread [_ runnable]
75 (doto (Thread. runnable
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
76 (format "nREPL-worker-%s" (.getAndIncrement session-thread-counter)))
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
77 (.setDaemon true))))))
78
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
79 (def ^{:private true} jdk6? (try
80 (Class/forName "java.util.ServiceLoader")
81 true
82 (catch ClassNotFoundException e false)))
83
84 (defn- configure-executor
85 "Returns a ThreadPoolExecutor, configured (by default) to
86 have no core threads, use an unbounded queue, create only daemon threads,
87 and allow unused threads to expire after 30s."
88 [& {:keys [keep-alive queue thread-factory]
89 :or {keep-alive 30000
90 queue (LinkedBlockingQueue.)}}]
91 ; ThreadPoolExecutor in JDK5 *will not run* submitted jobs if the core pool size is zero and
92 ; the queue has not yet rejected a job (see http://kirkwylie.blogspot.com/2008/10/java5-vs-java6-threadpoolexecutor.html)
93 (ThreadPoolExecutor. (if jdk6? 0 1) Integer/MAX_VALUE
94 (long 30000) TimeUnit/MILLISECONDS
95 queue
96 (or thread-factory (configure-thread-factory))))
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
97
07786ca @cemerick build against Clojure 1.4.0 final
cemerick authored Apr 16, 2012
98 ; A little mini-agent implementation. Needed because agents cannot be used to host REPL
99 ; evaluation: http://dev.clojure.org/jira/browse/NREPL-17
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
100 (defn- prep-session
101 [session]
102 (locking session
103 (returning session
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
104 (when-not (-> session meta :queue)
105 (alter-meta! session assoc :queue (atom clojure.lang.PersistentQueue/EMPTY))))))
106
107 (declare run-next)
108 (defn- run-next*
109 [session executor]
110 (let [qa (-> session meta :queue)]
111 (loop []
112 (let [q @qa
113 qn (pop q)]
114 (if-not (compare-and-set! qa q qn)
115 (recur)
116 (when (seq qn)
117 (.execute executor (run-next session executor (peek qn)))))))))
118
119 (defn- run-next
120 [session executor f]
121 #(try
122 (f)
123 (finally
124 (run-next* session executor))))
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
125
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
126 (defn- queue-eval
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
127 "Queues the function for the given session."
128 [session executor f]
129 (let [qa (-> session prep-session meta :queue)]
130 (loop []
131 (let [q @qa]
132 (if-not (compare-and-set! qa q (conj q f))
133 (recur)
134 (when (empty? q)
135 (.execute executor (run-next session executor f))))))))
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
136
137 (defn interruptible-eval
138 "Evaluation middleware that supports interrupts. Returns a handler that supports
139 \"eval\" and \"interrupt\" :op-erations that delegates to the given handler
140 otherwise."
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
141 [h & {:keys [executor] :or {executor (configure-executor)}}]
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
142 (fn [{:keys [op session interrupt-id id transport] :as msg}]
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
143 (case op
144 "eval"
145 (if-not (:code msg)
146 (t/send transport (response-for msg :status #{:error :no-code}))
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
147 (queue-eval session executor
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
148 (comp
149 (partial reset! session)
150 (fn []
151 (alter-meta! session assoc
152 :thread (Thread/currentThread)
153 :eval-msg msg)
154 (binding [*msg* msg]
a8bc0c0 @cemerick #'*agent* no longer implicated in REPL goings-on
cemerick authored Apr 13, 2012
155 (returning (dissoc (evaluate @session msg) #'*msg*)
afcba72 @cemerick stop using agents to model REPL sessions; fixing NREPL-17
cemerick authored Apr 13, 2012
156 (t/send transport (response-for msg :status :done))
157 (alter-meta! session dissoc :thread :eval-msg)))))))
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
158
159 "interrupt"
160 ; interrupts are inherently racy; we'll check the agent's :eval-msg's :id and
161 ; bail if it's different than the one provided, but it's possible for
162 ; that message's eval to finish and another to start before we send
163 ; the interrupt / .stop.
164 (let [{:keys [id eval-msg ^Thread thread]} (meta session)]
165 (if (or (not interrupt-id)
166 (= interrupt-id (:id eval-msg)))
167 (if-not thread
168 (t/send transport (response-for msg :status #{:done :session-idle}))
169 (do
f955b8c @cemerick eliminate :interrupted status race condition
cemerick authored Feb 14, 2012
170 ; notify of the interrupted status before we .stop the thread so
171 ; it is received before the standard :done status (thereby ensuring
172 ; that is stays within the scope of a clojure.tools.nrepl/message seq
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
173 (t/send transport {:status #{:interrupted}
174 :id (:id eval-msg)
175 :session id})
f955b8c @cemerick eliminate :interrupted status race condition
cemerick authored Feb 14, 2012
176 (.stop thread)
4e3317c @cemerick split handlers namespace into separate topical middleware namespaces
cemerick authored Feb 14, 2012
177 (t/send transport (response-for msg :status #{:done}))))
178 (t/send transport (response-for msg :status #{:error :interrupt-id-mismatch :done}))))
179
180 (h msg))))
9f11cfd @cemerick take 2 on NREPL-17; no more per-session executors, coping with JDK5/6…
cemerick authored Apr 16, 2012
181
Something went wrong with that request. Please try again.