-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
handler.clj
188 lines (169 loc) · 6.54 KB
/
handler.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
(ns hello.handler
(:require
[aleph.http :as http]
[aleph.netty :as netty]
[byte-streams :as bs]
[clj-async-profiler.core :as prof]
[hiccup.page :as hp]
[hiccup.util :as hu]
[jsonista.core :as json]
[manifold.deferred :as d]
[porsas.async :as async])
(:import (clojure.lang IDeref)
(io.netty.channel ChannelOption)
(io.netty.buffer PooledByteBufAllocator)
(java.util.function Supplier)
(java.util.concurrent ThreadLocalRandom)
(porsas.async Context))
(:gen-class))
(def plaintext-response
{:status 200
:headers {"Content-Type" "text/plain"}
:body (bs/to-byte-array "Hello, World!")})
(def json-response
{:status 200
:headers {"Content-Type" "application/json"}})
(def html-response
{:status 200
:headers {"Content-Type" "text/html; charset=utf-8"}})
(def db-spec
{:uri "postgresql://tfb-database:5432/hello_world"
:user "benchmarkdbuser"
:password "benchmarkdbpass"
:size 1})
(defmacro thread-local [& body]
`(let [tl# (ThreadLocal/withInitial (reify Supplier (get [_] ~@body)))]
(reify IDeref (deref [_] (.get tl#)))))
(def pool
"PostgreSQL pool of connections (`PgPool`)."
(thread-local (async/pool db-spec)))
(defn random
"Generate a random number between 1 and 10'000."
[]
(unchecked-inc (.nextInt (ThreadLocalRandom/current) 10000)))
(defn sanitize-queries-param
"Sanitizes the `queries` parameter. Clamps the value between 1 and 500.
Invalid (string) values become 1."
[request]
(let [queries (-> request
:query-string
(subs 8))
n (try (Integer/parseInt queries)
(catch Exception _ 1))] ; default to 1 on parse failure
(cond
(< n 1) 1
(> n 500) 500
:else n)))
(def ^Context
query-mapper
"Map each row into a record."
(async/context {:row (async/rs->compiled-record)}))
(defn query-one-random-world
"Query a random world on the database.
Return a `CompletableFuture`."
[]
(async/query-one query-mapper
@pool
["SELECT id, randomnumber FROM world WHERE id=$1" (random)]))
(defn update-world
"Update a world on the database.
Return a `CompletableFuture`."
[{:keys [randomNumber id]}]
(async/query @pool
["UPDATE world SET randomnumber=$1 WHERE id=$2" randomNumber id]))
(defn run-queries
"Run a number of `queries` on the database to fetch a random world.
Return a `manifold.deferred`."
[queries]
(apply d/zip
(take queries
(repeatedly query-one-random-world))))
(defn query-fortunes
"Query the fortunes on database.
Return a `CompletableFuture`."
[]
(async/query query-mapper @pool ["SELECT id, message from FORTUNE"]))
(defn get-fortunes
"Fetch the full list of Fortunes from the database, sort them by the fortune
message text.
Return a `CompletableFuture` with the results."
[]
(d/chain (query-fortunes)
(fn [fortunes]
(sort-by :message
(conj fortunes
{:id 0
:message "Additional fortune added at request time."})))))
(defn update-and-persist
"Fetch a number of `queries` random world from the database.
Compute a new `randomNumber` for each of them a return a `CompletableFuture`
with the updated worlds."
[queries]
(d/chain' (run-queries queries)
(fn [worlds]
(let [worlds' (mapv #(assoc % :randomNumber (random)) worlds)]
(d/chain' (apply d/zip (mapv update-world worlds'))
(fn [_] worlds'))))))
(defn fortunes-hiccup
"Render the given fortunes to simple HTML using Hiccup."
[fortunes]
(hp/html5
[:head
[:title "Fortunes"]]
[:body
[:table
[:tr
[:th "id"]
[:th "message"]]
(for [x fortunes]
[:tr
[:td (:id x)]
[:td (hu/escape-html (:message x))]])]]))
(defn handler
"Ring handler representing the different tests."
[req]
(let [uri (:uri req)]
(cond
(.equals "/plaintext" uri) plaintext-response
(.equals "/json" uri) (assoc json-response
:body (json/write-value-as-bytes {:message "Hello, World!"}))
(.equals "/db" uri) (-> (query-one-random-world)
(d/chain (fn [world]
(assoc json-response
:body (json/write-value-as-bytes world)))))
(.equals "/queries" uri) (-> (sanitize-queries-param req)
(run-queries)
(d/chain (fn [worlds]
(assoc json-response
:body (json/write-value-as-bytes worlds)))))
(.equals "/fortunes" uri) (d/chain' (get-fortunes)
fortunes-hiccup
(fn [body]
(assoc html-response :body body)))
(.equals "/updates" uri) (-> (sanitize-queries-param req)
(update-and-persist)
(d/chain (fn [worlds]
(assoc json-response
:body (json/write-value-as-bytes worlds)))))
:else {:status 404})))
;;;
(defn -main [& _]
(netty/leak-detector-level! :disabled)
(http/start-server handler {:port 8080
:raw-stream? true
:epoll? true
:executor :none
:bootstrap-transform (fn [bootstrap]
(.option bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT)
(.childOption bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT))
:pipeline-transform (fn [pipeline]
(.remove pipeline "continue-handler"))})
;; Uncomment to enable async-profiler
#_
(do
(prof/profile-for 60
#_
{:transform (fn [s]
(when-not (re-find #"(writev|__libc|epoll_wait|write|__pthread)" s)
s))})
(prof/serve-files 8081)))