author | Mahlon E. Smith <mahlon@martini.nu> |
Wed, 27 Oct 2021 13:57:16 -0700 | |
changeset 6 | d49437ff8f2f |
parent 4 | ffb8b9920057 |
permissions | -rw-r--r-- |
6
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
1 |
# vim: set et sta sw=4 ts=4 : |
0 | 2 |
# |
6
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
3 |
# Copyright (c) 2015-2021, Mahlon E. Smith <mahlon@martini.nu> |
0 | 4 |
# All rights reserved. |
5 |
# Redistribution and use in source and binary forms, with or without |
|
6 |
# modification, are permitted provided that the following conditions are met: |
|
7 |
# |
|
8 |
# * Redistributions of source code must retain the above copyright |
|
9 |
# notice, this list of conditions and the following disclaimer. |
|
10 |
# |
|
11 |
# * Redistributions in binary form must reproduce the above copyright |
|
12 |
# notice, this list of conditions and the following disclaimer in the |
|
13 |
# documentation and/or other materials provided with the distribution. |
|
14 |
# |
|
15 |
# * Neither the name of Mahlon E. Smith nor the names of his |
|
16 |
# contributors may be used to endorse or promote products derived |
|
17 |
# from this software without specific prior written permission. |
|
18 |
# |
|
19 |
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY |
|
20 |
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
|
21 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
|
22 |
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY |
|
23 |
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
|
24 |
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
|
25 |
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
|
26 |
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
|
27 |
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
|
28 |
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
|
29 |
||
30 |
## This module is a simple interface to the Mongrel2 webserver |
|
31 |
## environment (http://mongrel2.org/). After a Mongrel2 server has been |
|
32 |
## properly configured, you can use this library to easily service client |
|
33 |
## requests. |
|
34 |
## |
|
35 |
## Bare minimal, do-nothing example: |
|
36 |
## |
|
37 |
## .. code-block:: nim |
|
38 |
## |
|
39 |
## newM2Handler( "app-id", "tcp://127.0.0.1:9009", "tcp://127.0.0.1:9008" ).run |
|
40 |
## |
|
41 |
## Yep, that's it. Assuming your Mongrel2 server is configured with a |
|
42 |
## matching application identifier and request/response communication |
|
43 |
## ports, that's enough to see the default output from the handler when |
|
44 |
## loaded in browser. |
|
45 |
## |
|
46 |
## It's likely that you'll want to do something of more substance. This |
|
47 |
## is performed via an `action` hook, which is just a proc() reference. |
|
48 |
## It is passed the parsed `M2Request` client request, and it needs to |
|
49 |
## return a matching `M2Response` object. What happens in between is |
|
50 |
## entirely up to you. |
|
51 |
## |
|
52 |
## Here's a "hello world": |
|
53 |
## |
|
54 |
## .. code-block:: nim |
|
55 |
## |
|
56 |
## let handler = newM2Handler( "app-id", "tcp://127.0.0.1:9009", "tcp://127.0.0.1:9008" ) |
|
57 |
## |
|
58 |
## proc hello_world( request: M2Request ): M2Response = |
|
59 |
## result = request.response |
|
60 |
## result[ "Content-Type" ] = "text/plain" |
|
61 |
## result.body = "Hello there, world!" |
|
62 |
## result.status = HTTP_OK |
|
63 |
## |
|
64 |
## handler.action = hello_world |
|
65 |
## handler.run |
|
66 |
## |
|
67 |
## And finally, a slightly more interesting example: |
|
68 |
## |
|
69 |
## .. code-block:: nim |
|
70 |
## |
|
71 |
## import |
|
72 |
## mongrel2, |
|
73 |
## json, |
|
74 |
## re |
|
75 |
## |
|
76 |
## let handler = newM2Handler( "app-id", "tcp://127.0.0.1:9009", "tcp://127.0.0.1:9008" ) |
|
77 |
## var data = %*[] ## the JSON data to "remember" |
|
78 |
## |
|
79 |
## |
|
80 |
## proc demo( request: M2Request ): M2Response = |
|
81 |
## ## This is a demonstration handler action. |
|
82 |
## ## |
|
83 |
## ## It accepts and stores a JSON data structure |
|
84 |
## ## on POST, and returns it on GET. |
|
85 |
## |
|
86 |
## # Create a response object for the current request. |
|
87 |
## var response = request.response |
|
88 |
## |
|
89 |
## case request.meth |
|
90 |
## |
|
91 |
## # For GET requests, display the current JSON structure. |
|
92 |
## # |
|
93 |
## of "GET": |
|
94 |
## if request[ "Accept" ].match( re(".*text/(html|plain).*") ): |
|
95 |
## response[ "Content-Type" ] = "text/plain" |
|
96 |
## response.body = "Hi there. POST some JSON to me and I'll remember it.\n\n" & $( data ) |
|
97 |
## response.status = HTTP_OK |
|
98 |
## |
|
99 |
## elif request[ "Accept" ].match( re("application/json") ): |
|
100 |
## response[ "Content-Type" ] = "application/json" |
|
101 |
## response.body = $( data ) |
|
102 |
## response.status = HTTP_OK |
|
103 |
## |
|
104 |
## else: |
|
105 |
## response.status = HTTP_BAD_REQUEST |
|
106 |
## |
|
107 |
## # POST requests overwrite the current JSON structure. |
|
108 |
## # |
|
109 |
## of "POST": |
|
110 |
## if request[ "Content-Type" ].match( re(".*application/json.*") ): |
|
111 |
## try: |
|
112 |
## data = request.body.parse_json |
|
113 |
## response.status = HTTP_OK |
|
114 |
## response[ "Content-Type" ] = "application/json" |
|
115 |
## response.body = $( data ) |
|
116 |
## except: |
|
117 |
## response.status = HTTP_BAD_REQUEST |
|
118 |
## response[ "Content-Type" ] = "text/plain" |
|
119 |
## response.body = request.body |
|
120 |
## |
|
121 |
## else: |
|
122 |
## response.body = "I only accept valid JSON strings." |
|
123 |
## response.status = HTTP_BAD_REQUEST |
|
124 |
## |
|
125 |
## else: |
|
126 |
## response.status = HTTP_NOT_ACCEPTABLE |
|
127 |
## |
|
128 |
## return response |
|
129 |
## |
|
130 |
## |
|
131 |
## # Attach the proc reference to the handler action. |
|
132 |
## handler.action = demo |
|
133 |
## |
|
134 |
## # Start 'er up! |
|
135 |
## handler.run |
|
136 |
## |
|
137 |
||
138 |
||
139 |
import |
|
6
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
140 |
std/json, |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
141 |
std/strutils, |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
142 |
std/tables, |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
143 |
std/times, |
0 | 144 |
tnetstring, |
145 |
zmq |
|
146 |
||
147 |
type |
|
148 |
M2Handler* = ref object of RootObj |
|
149 |
handler_id: string |
|
6
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
150 |
request_sock: ZConnection |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
151 |
response_sock: ZConnection |
0 | 152 |
action*: proc ( request: M2Request ): M2Response |
153 |
disconnect_action*: proc ( request: M2Request ) |
|
154 |
||
155 |
M2Request* = ref object of RootObj |
|
156 |
sender_id*: string ## Mongrel2 app-id |
|
157 |
conn_id*: string |
|
158 |
path*: string |
|
159 |
meth*: string |
|
160 |
version*: string |
|
161 |
uri*: string |
|
162 |
pattern*: string |
|
163 |
scheme*: string |
|
164 |
remote_addr*: string |
|
165 |
query*: string |
|
166 |
headers*: seq[ tuple[name: string, value: string] ] |
|
167 |
body*: string |
|
168 |
||
169 |
M2Response* = ref object of RootObj |
|
170 |
sender_id*: string |
|
171 |
conn_id*: string |
|
172 |
status*: int |
|
173 |
headers*: seq[ tuple[name: string, value: string] ] |
|
174 |
body*: string |
|
175 |
extended: string |
|
176 |
ex_data: seq[ string ] |
|
177 |
||
178 |
const |
|
179 |
MAX_CLIENT_BROADCAST = 128 ## The maximum number of client to broadcast a response to |
|
180 |
CRLF = "\r\n" ## Network line ending |
|
181 |
DEFAULT_CONTENT = """ |
|
182 |
<!DOCTYPE html> |
|
183 |
<html lang="en"> |
|
184 |
<head> |
|
185 |
<title>It works!</title> |
|
186 |
<link href='http://fonts.googleapis.com/css?family=Play' rel='stylesheet' type='text/css'> |
|
187 |
<style> |
|
188 |
body { |
|
189 |
margin: 50px; |
|
190 |
height: 100%; |
|
191 |
background-color: #ddd; |
|
192 |
font-family: Play, Arial, serif; |
|
193 |
font-weight: 400; |
|
194 |
background: linear-gradient( to bottom, #7db9e8 25%,#fff 100% ); |
|
195 |
} |
|
196 |
a, a:hover, a:visited { |
|
197 |
text-decoration: none; |
|
198 |
color: rgb( 66,131,251 ); |
|
199 |
} |
|
200 |
.content { |
|
201 |
font-size: 1.2em; |
|
202 |
border-radius: 10px; |
|
203 |
margin: 0 auto 0 auto; |
|
204 |
width: 50%; |
|
205 |
padding: 5px 20px 20px 20px; |
|
206 |
box-shadow: 1px 2px 6px #000; |
|
207 |
background-color: #fff; |
|
208 |
border: 1px; |
|
209 |
} |
|
210 |
.handler { |
|
211 |
font-size: 0.9em; |
|
212 |
padding: 2px 0 0 10px; |
|
213 |
color: rgb( 192,220,255 ); |
|
214 |
background-color: rgb( 6,20,85 ); |
|
215 |
border: 2px solid rgb( 66,131,251 ); |
|
216 |
} |
|
217 |
</style> |
|
218 |
</head> |
|
219 |
<body> |
|
220 |
<div class="content"> |
|
221 |
<h1>Almost there...</h1> |
|
222 |
<p> |
|
223 |
This is the default handler output. While this is |
|
224 |
useful to demonstrate that your <a href="http://mongrel2.org">Mongrel2</a> |
|
225 |
server is indeed speaking to your <a href="http://nim-lang.org">nim</a> |
|
226 |
handler, you're probably going to want to do something else for production use. |
|
227 |
</p> |
|
228 |
<p> |
|
229 |
Here's an example handler: |
|
230 |
</p> |
|
231 |
||
232 |
<div class="handler"> |
|
233 |
<pre> |
|
234 |
import |
|
235 |
mongrel2, |
|
236 |
json, |
|
237 |
re |
|
238 |
||
239 |
let handler = newM2Handler( "app-id", "tcp://127.0.0.1:9009", "tcp://127.0.0.1:9008" ) |
|
240 |
var data = %*[] ## the JSON data to "remember" |
|
241 |
||
242 |
||
243 |
proc demo( request: M2Request ): M2Response = |
|
244 |
## This is a demonstration handler action. |
|
245 |
## |
|
246 |
## It accepts and stores a JSON data structure |
|
247 |
## on POST, and returns it on GET. |
|
248 |
||
249 |
# Create a response object for the current request. |
|
250 |
var response = request.response |
|
251 |
||
252 |
case request.meth |
|
253 |
||
254 |
# For GET requests, display the current JSON structure. |
|
255 |
# |
|
256 |
of "GET": |
|
257 |
if request[ "Accept" ].match( re(".*text/(html|plain).*") ): |
|
258 |
response[ "Content-Type" ] = "text/plain" |
|
259 |
response.body = "Hi there. POST some JSON to me and I'll remember it.\n\n" & $( data ) |
|
260 |
response.status = HTTP_OK |
|
261 |
||
262 |
elif request[ "Accept" ].match( re("application/json") ): |
|
263 |
response[ "Content-Type" ] = "application/json" |
|
264 |
response.body = $( data ) |
|
265 |
response.status = HTTP_OK |
|
266 |
||
267 |
else: |
|
268 |
response.status = HTTP_BAD_REQUEST |
|
269 |
||
270 |
# Overwrite the current JSON structure. |
|
271 |
# |
|
272 |
of "POST": |
|
273 |
if request[ "Content-Type" ].match( re(".*application/json.*") ): |
|
274 |
try: |
|
275 |
data = request.body.parse_json |
|
276 |
response.status = HTTP_OK |
|
277 |
response[ "Content-Type" ] = "application/json" |
|
278 |
response.body = $( data ) |
|
279 |
except: |
|
280 |
response.status = HTTP_BAD_REQUEST |
|
281 |
response[ "Content-Type" ] = "text/plain" |
|
282 |
response.body = request.body |
|
283 |
||
284 |
else: |
|
285 |
response.body = "I only accept valid JSON strings." |
|
286 |
response.status = HTTP_BAD_REQUEST |
|
287 |
||
288 |
else: |
|
289 |
response.status = HTTP_NOT_ACCEPTABLE |
|
290 |
||
291 |
return response |
|
292 |
||
293 |
||
294 |
# Attach the proc reference to the handler action. |
|
295 |
handler.action = demo |
|
296 |
||
297 |
# Start 'er up! |
|
298 |
handler.run |
|
299 |
</pre> |
|
300 |
</div> |
|
301 |
</div> |
|
302 |
</body> |
|
303 |
</html> |
|
304 |
""" |
|
305 |
||
306 |
HTTP_CONTINUE* = 100 |
|
307 |
HTTP_SWITCHING_PROTOCOLS* = 101 |
|
308 |
HTTP_PROCESSING* = 102 |
|
309 |
HTTP_OK* = 200 |
|
310 |
HTTP_CREATED* = 201 |
|
311 |
HTTP_ACCEPTED* = 202 |
|
312 |
HTTP_NON_AUTHORITATIVE* = 203 |
|
313 |
HTTP_NO_CONTENT* = 204 |
|
314 |
HTTP_RESET_CONTENT* = 205 |
|
315 |
HTTP_PARTIAL_CONTENT* = 206 |
|
316 |
HTTP_MULTI_STATUS* = 207 |
|
317 |
HTTP_MULTIPLE_CHOICES* = 300 |
|
318 |
HTTP_MOVED_PERMANENTLY* = 301 |
|
319 |
HTTP_MOVED* = 301 |
|
320 |
HTTP_MOVED_TEMPORARILY* = 302 |
|
321 |
HTTP_REDIRECT* = 302 |
|
322 |
HTTP_SEE_OTHER* = 303 |
|
323 |
HTTP_NOT_MODIFIED* = 304 |
|
324 |
HTTP_USE_PROXY* = 305 |
|
325 |
HTTP_TEMPORARY_REDIRECT* = 307 |
|
326 |
HTTP_BAD_REQUEST* = 400 |
|
327 |
HTTP_AUTH_REQUIRED* = 401 |
|
328 |
HTTP_UNAUTHORIZED* = 401 |
|
329 |
HTTP_PAYMENT_REQUIRED* = 402 |
|
330 |
HTTP_FORBIDDEN* = 403 |
|
331 |
HTTP_NOT_FOUND* = 404 |
|
332 |
HTTP_METHOD_NOT_ALLOWED* = 405 |
|
333 |
HTTP_NOT_ACCEPTABLE* = 406 |
|
334 |
HTTP_PROXY_AUTHENTICATION_REQUIRED* = 407 |
|
335 |
HTTP_REQUEST_TIME_OUT* = 408 |
|
336 |
HTTP_CONFLICT* = 409 |
|
337 |
HTTP_GONE* = 410 |
|
338 |
HTTP_LENGTH_REQUIRED* = 411 |
|
339 |
HTTP_PRECONDITION_FAILED* = 412 |
|
340 |
HTTP_REQUEST_ENTITY_TOO_LARGE* = 413 |
|
341 |
HTTP_REQUEST_URI_TOO_LARGE* = 414 |
|
342 |
HTTP_UNSUPPORTED_MEDIA_TYPE* = 415 |
|
343 |
HTTP_RANGE_NOT_SATISFIABLE* = 416 |
|
344 |
HTTP_EXPECTATION_FAILED* = 417 |
|
345 |
HTTP_UNPROCESSABLE_ENTITY* = 422 |
|
346 |
HTTP_LOCKED* = 423 |
|
347 |
HTTP_FAILED_DEPENDENCY* = 424 |
|
348 |
HTTP_UPGRADE_REQUIRED* = 426 |
|
349 |
HTTP_RECONDITION_REQUIRED* = 428 |
|
350 |
HTTP_TOO_MANY_REQUESTS* = 429 |
|
351 |
HTTP_REQUEST_HEADERS_TOO_LARGE* = 431 |
|
352 |
HTTP_SERVER_ERROR* = 500 |
|
353 |
HTTP_NOT_IMPLEMENTED* = 501 |
|
354 |
HTTP_BAD_GATEWAY* = 502 |
|
355 |
HTTP_SERVICE_UNAVAILABLE* = 503 |
|
356 |
HTTP_GATEWAY_TIME_OUT* = 504 |
|
357 |
HTTP_VERSION_NOT_SUPPORTED* = 505 |
|
358 |
HTTP_VARIANT_ALSO_VARIES* = 506 |
|
359 |
HTTP_INSUFFICIENT_STORAGE* = 507 |
|
360 |
HTTP_NOT_EXTENDED* = 510 |
|
361 |
||
362 |
HTTPCODE = { |
|
363 |
HTTP_CONTINUE: ( desc: "Continue", label: "CONTINUE" ), |
|
364 |
HTTP_SWITCHING_PROTOCOLS: ( desc: "Switching Protocols", label: "SWITCHING_PROTOCOLS" ), |
|
365 |
HTTP_PROCESSING: ( desc: "Processing", label: "PROCESSING" ), |
|
366 |
HTTP_OK: ( desc: "OK", label: "OK" ), |
|
367 |
HTTP_CREATED: ( desc: "Created", label: "CREATED" ), |
|
368 |
HTTP_ACCEPTED: ( desc: "Accepted", label: "ACCEPTED" ), |
|
369 |
HTTP_NON_AUTHORITATIVE: ( desc: "Non-Authoritative Information", label: "NON_AUTHORITATIVE" ), |
|
370 |
HTTP_NO_CONTENT: ( desc: "No Content", label: "NO_CONTENT" ), |
|
371 |
HTTP_RESET_CONTENT: ( desc: "Reset Content", label: "RESET_CONTENT" ), |
|
372 |
HTTP_PARTIAL_CONTENT: ( desc: "Partial Content", label: "PARTIAL_CONTENT" ), |
|
373 |
HTTP_MULTI_STATUS: ( desc: "Multi-Status", label: "MULTI_STATUS" ), |
|
374 |
HTTP_MULTIPLE_CHOICES: ( desc: "Multiple Choices", label: "MULTIPLE_CHOICES" ), |
|
375 |
HTTP_MOVED_PERMANENTLY: ( desc: "Moved Permanently", label: "MOVED_PERMANENTLY" ), |
|
376 |
HTTP_MOVED: ( desc: "Moved Permanently", label: "MOVED" ), |
|
377 |
HTTP_MOVED_TEMPORARILY: ( desc: "Found", label: "MOVED_TEMPORARILY" ), |
|
378 |
HTTP_REDIRECT: ( desc: "Found", label: "REDIRECT" ), |
|
379 |
HTTP_SEE_OTHER: ( desc: "See Other", label: "SEE_OTHER" ), |
|
380 |
HTTP_NOT_MODIFIED: ( desc: "Not Modified", label: "NOT_MODIFIED" ), |
|
381 |
HTTP_USE_PROXY: ( desc: "Use Proxy", label: "USE_PROXY" ), |
|
382 |
HTTP_TEMPORARY_REDIRECT: ( desc: "Temporary Redirect", label: "TEMPORARY_REDIRECT" ), |
|
383 |
HTTP_BAD_REQUEST: ( desc: "Bad Request", label: "BAD_REQUEST" ), |
|
384 |
HTTP_AUTH_REQUIRED: ( desc: "Authorization Required", label: "AUTH_REQUIRED" ), |
|
385 |
HTTP_UNAUTHORIZED: ( desc: "Authorization Required", label: "UNAUTHORIZED" ), |
|
386 |
HTTP_PAYMENT_REQUIRED: ( desc: "Payment Required", label: "PAYMENT_REQUIRED" ), |
|
387 |
HTTP_FORBIDDEN: ( desc: "Forbidden", label: "FORBIDDEN" ), |
|
388 |
HTTP_NOT_FOUND: ( desc: "Not Found", label: "NOT_FOUND" ), |
|
389 |
HTTP_METHOD_NOT_ALLOWED: ( desc: "Method Not Allowed", label: "METHOD_NOT_ALLOWED" ), |
|
390 |
HTTP_NOT_ACCEPTABLE: ( desc: "Not Acceptable", label: "NOT_ACCEPTABLE" ), |
|
391 |
HTTP_PROXY_AUTHENTICATION_REQUIRED: ( desc: "Proxy Authentication Required", label: "PROXY_AUTHENTICATION_REQUIRED" ), |
|
392 |
HTTP_REQUEST_TIME_OUT: ( desc: "Request Time-out", label: "REQUEST_TIME_OUT" ), |
|
393 |
HTTP_CONFLICT: ( desc: "Conflict", label: "CONFLICT" ), |
|
394 |
HTTP_GONE: ( desc: "Gone", label: "GONE" ), |
|
395 |
HTTP_LENGTH_REQUIRED: ( desc: "Length Required", label: "LENGTH_REQUIRED" ), |
|
396 |
HTTP_PRECONDITION_FAILED: ( desc: "Precondition Failed", label: "PRECONDITION_FAILED" ), |
|
397 |
HTTP_REQUEST_ENTITY_TOO_LARGE: ( desc: "Request Entity Too Large", label: "REQUEST_ENTITY_TOO_LARGE" ), |
|
398 |
HTTP_REQUEST_URI_TOO_LARGE: ( desc: "Request-URI Too Large", label: "REQUEST_URI_TOO_LARGE" ), |
|
399 |
HTTP_UNSUPPORTED_MEDIA_TYPE: ( desc: "Unsupported Media Type", label: "UNSUPPORTED_MEDIA_TYPE" ), |
|
400 |
HTTP_RANGE_NOT_SATISFIABLE: ( desc: "Requested Range Not Satisfiable", label: "RANGE_NOT_SATISFIABLE" ), |
|
401 |
HTTP_EXPECTATION_FAILED: ( desc: "Expectation Failed", label: "EXPECTATION_FAILED" ), |
|
402 |
HTTP_UNPROCESSABLE_ENTITY: ( desc: "Unprocessable Entity", label: "UNPROCESSABLE_ENTITY" ), |
|
403 |
HTTP_LOCKED: ( desc: "Locked", label: "LOCKED" ), |
|
404 |
HTTP_FAILED_DEPENDENCY: ( desc: "Failed Dependency", label: "FAILED_DEPENDENCY" ), |
|
405 |
HTTP_UPGRADE_REQUIRED: ( desc: "Upgrade Required", label: "UPGRADE_REQUIRED" ), |
|
406 |
HTTP_RECONDITION_REQUIRED: ( desc: "Precondition Required", label: "RECONDITION_REQUIRED" ), |
|
407 |
HTTP_TOO_MANY_REQUESTS: ( desc: "Too Many Requests", label: "TOO_MANY_REQUESTS" ), |
|
408 |
HTTP_REQUEST_HEADERS_TOO_LARGE: ( desc: "Request Headers too Large", label: "REQUEST_HEADERS_TOO_LARGE" ), |
|
409 |
HTTP_SERVER_ERROR: ( desc: "Internal Server Error", label: "SERVER_ERROR" ), |
|
410 |
HTTP_NOT_IMPLEMENTED: ( desc: "Method Not Implemented", label: "NOT_IMPLEMENTED" ), |
|
411 |
HTTP_BAD_GATEWAY: ( desc: "Bad Gateway", label: "BAD_GATEWAY" ), |
|
412 |
HTTP_SERVICE_UNAVAILABLE: ( desc: "Service Temporarily Unavailable", label: "SERVICE_UNAVAILABLE" ), |
|
413 |
HTTP_GATEWAY_TIME_OUT: ( desc: "Gateway Time-out", label: "GATEWAY_TIME_OUT" ), |
|
414 |
HTTP_VERSION_NOT_SUPPORTED: ( desc: "HTTP Version Not Supported", label: "VERSION_NOT_SUPPORTED" ), |
|
415 |
HTTP_VARIANT_ALSO_VARIES: ( desc: "Variant Also Negotiates", label: "VARIANT_ALSO_VARIES" ), |
|
416 |
HTTP_INSUFFICIENT_STORAGE: ( desc: "Insufficient Storage", label: "INSUFFICIENT_STORAGE" ), |
|
417 |
HTTP_NOT_EXTENDED: ( desc: "Not Extended", label: "NOT_EXTENDED" ) |
|
418 |
}.toTable |
|
419 |
||
420 |
||
421 |
||
422 |
proc newM2Handler*( id: string, req_sock: string, res_sock: string ): M2Handler = |
|
423 |
## Instantiate a new `M2Handler` object. |
|
424 |
## The `id` should match the app ID in the Mongrel2 config, |
|
425 |
## `req_sock` is the ZMQ::PULL socket Mongrel2 sends client request |
|
426 |
## data on, and `res_sock` is the ZMQ::PUB socket Mongrel2 subscribes |
|
427 |
## to. Nothing is put into action until the run() method is invoked. |
|
428 |
new( result ) |
|
429 |
result.handler_id = id |
|
3
ecde1a332692
I'm not sure how I missed this one. Ssssh. Nothing to see here.
Mahlon E. Smith <mahlon@martini.nu>
parents:
0
diff
changeset
|
430 |
result.request_sock = zmq.connect( req_sock, PULL ) |
ecde1a332692
I'm not sure how I missed this one. Ssssh. Nothing to see here.
Mahlon E. Smith <mahlon@martini.nu>
parents:
0
diff
changeset
|
431 |
result.response_sock = zmq.connect( res_sock, PUB ) |
0 | 432 |
|
433 |
||
434 |
proc parse_request( request: string ): M2Request = |
|
435 |
## Parse a message `request` string received from Mongrel2, |
|
436 |
## return it as a M2Request object. |
|
437 |
var |
|
438 |
reqstr = request.split( ' ' ) |
|
439 |
rest = "" |
|
440 |
req_tnstr: TNetstringNode |
|
441 |
headers: JsonNode |
|
442 |
||
443 |
new( result ) |
|
444 |
result.sender_id = reqstr[ 0 ] |
|
445 |
result.conn_id = reqstr[ 1 ] |
|
446 |
result.path = reqstr[ 2 ] |
|
447 |
||
448 |
# There must be a better way to join() a seq... |
|
449 |
# |
|
450 |
for i in 3 .. reqstr.high: |
|
451 |
rest = rest & reqstr[ i ] |
|
452 |
if i < reqstr.high: rest = rest & ' ' |
|
453 |
reqtnstr = rest.parse_tnetstring |
|
454 |
result.body = reqtnstr.extra.parse_tnetstring.getStr("") |
|
455 |
||
456 |
# Pull Mongrel2 control headers into the request object. |
|
457 |
# |
|
458 |
headers = reqtnstr.getStr.parse_json |
|
459 |
||
460 |
if headers.has_key( "METHOD" ): |
|
461 |
result.meth = headers[ "METHOD" ].getStr |
|
462 |
headers.delete( "METHOD" ) |
|
463 |
||
464 |
if headers.has_key( "PATTERN" ): |
|
465 |
result.pattern = headers[ "PATTERN" ].getStr |
|
466 |
headers.delete( "PATTERN" ) |
|
467 |
||
468 |
if headers.has_key( "REMOTE_ADDR" ): |
|
469 |
result.remote_addr = headers[ "REMOTE_ADDR" ].getStr |
|
470 |
headers.delete( "REMOTE_ADDR" ) |
|
471 |
||
472 |
if headers.has_key( "URI" ): |
|
473 |
result.uri = headers[ "URI" ].getStr |
|
474 |
headers.delete( "URI" ) |
|
475 |
||
476 |
if headers.has_key( "URL_SCHEME" ): |
|
477 |
result.scheme = headers[ "URL_SCHEME" ].getStr |
|
478 |
headers.delete( "URL_SCHEME" ) |
|
479 |
||
480 |
if headers.has_key( "VERSION" ): |
|
481 |
result.version = headers[ "VERSION" ].getStr |
|
482 |
headers.delete( "VERSION" ) |
|
483 |
||
484 |
if headers.has_key( "QUERY" ): |
|
485 |
result.query = headers[ "QUERY" ].getStr |
|
486 |
headers.delete( "QUERY" ) |
|
487 |
||
488 |
# Remaining headers are client supplied. |
|
489 |
# |
|
490 |
result.headers = @[] |
|
491 |
for key, val in headers: |
|
492 |
result.headers.add( ( key, val.getStr ) ) |
|
493 |
||
494 |
||
495 |
proc response*( request: M2Request ): M2Response = |
|
496 |
## Instantiate a new `M2Response`, paired from an `M2Request`. |
|
497 |
new( result ) |
|
498 |
result.sender_id = request.sender_id |
|
499 |
result.conn_id = request.conn_id |
|
500 |
result.headers = @[] |
|
501 |
||
502 |
||
503 |
proc `[]`*( request: M2Request, label: string ): string = |
|
504 |
## Defer to the underlying headers tuple array. Lookup is case-insensitive. |
|
505 |
for header in request.headers: |
|
506 |
if cmpIgnoreCase( label, header.name ) == 0: |
|
507 |
return header.value |
|
4
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
508 |
return "" |
0 | 509 |
|
510 |
||
511 |
proc is_disconnect*( request: M2Request ): bool = |
|
512 |
## Returns true if this is a Mongrel2 disconnect request. |
|
513 |
if ( request.path == "@*" and request.meth == "JSON") : |
|
514 |
var body = request.body.parseJson |
|
515 |
if ( body.has_key( "type" ) and body[ "type" ].getStr == "disconnect" ): |
|
516 |
return true |
|
517 |
return false |
|
518 |
||
519 |
||
520 |
proc `[]`*( response: M2Response, label: string ): string = |
|
521 |
## Defer to the underlying headers tuple array. Lookup is case-insensitive. |
|
522 |
for header in response.headers: |
|
523 |
if cmpIgnoreCase( label, header.name ) == 0: |
|
524 |
return header.value |
|
4
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
525 |
return "" |
0 | 526 |
|
527 |
||
528 |
proc `[]=`*( response: M2Response, name: string, value: string ) = |
|
529 |
## Set a header on the response. Duplicates are replaced. |
|
530 |
var new_headers: seq[ tuple[name: string, value: string] ] = @[] |
|
531 |
for header in response.headers: |
|
532 |
if cmpIgnoreCase( name, header.name ) != 0: |
|
533 |
new_headers.add( header ) |
|
534 |
response.headers = new_headers |
|
535 |
response.headers.add( (name, value) ) |
|
536 |
||
537 |
||
538 |
proc add_header*( response: M2Response, name: string, value: string ) = |
|
539 |
## Adds a header to the response. Duplicates are ignored. |
|
540 |
response.headers.add( (name, value) ) |
|
541 |
||
542 |
||
543 |
proc extend*( response: M2Response, filter: string ) = |
|
544 |
## Set a response as extended. This means different things depending on |
|
545 |
## the Mongrel2 filter in use. |
|
546 |
response.extended = filter |
|
547 |
||
548 |
||
549 |
proc add_extended_data*( response: M2Response, data: varargs[string, `$`] ) = |
|
550 |
## Attach filter arguments to the extended response. Arguments should |
|
551 |
## be coercible into strings. |
|
4
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
552 |
# if isNil( response.ex_data ): response.ex_data = @[] |
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
553 |
# response.ex_data = @[] |
0 | 554 |
for arg in data: |
555 |
response.ex_data.add( arg ) |
|
556 |
||
557 |
||
558 |
proc is_extended*( response: M2Response ): bool = |
|
559 |
## Predicate method to determine if a response is extended. |
|
4
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
560 |
return not ( response.extended == "" ) |
0 | 561 |
|
562 |
||
563 |
proc broadcast*[T]( response: M2Response, ids: openarray[T] ) = |
|
564 |
## Send the response to multiple backend client IDs. |
|
565 |
assert( ids.len <= MAX_CLIENT_BROADCAST, "Exceeded client broadcast maximum" ) |
|
566 |
||
567 |
response.conn_id = $( ids[0] ) |
|
568 |
for i in 1 .. ids.high: |
|
569 |
if i <= ids.high: response.conn_id = response.conn_id & ' ' |
|
570 |
response.conn_id = response.conn_id & $( ids[i] ) |
|
571 |
||
572 |
||
573 |
proc format( response: M2Response ): string = |
|
574 |
## Format an `M2Response` object for Mongrel2. |
|
575 |
var conn_id: string |
|
576 |
||
577 |
# Mongrel2 extended response. |
|
578 |
# |
|
579 |
if response.is_extended: |
|
580 |
conn_id = newTNetstringString( "X " & response.conn_id ).dump_tnetstring |
|
581 |
result = response.sender_id & ' ' & conn_id |
|
582 |
||
583 |
# 1st argument is the filter name. |
|
584 |
# |
|
585 |
var tnet_array = newTNetstringArray() |
|
586 |
tnet_array.add( newTNetstringString(response.extended) ) |
|
587 |
||
588 |
# rest are the filter arguments, if any. |
|
589 |
# |
|
4
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
590 |
if response.is_extended: |
0 | 591 |
for data in response.ex_data: |
592 |
tnet_array.add( newTNetstringString(data) ) |
|
593 |
||
594 |
result = result & ' ' & tnet_array.dump_tnetstring |
|
595 |
||
596 |
||
597 |
else: |
|
598 |
# Regular HTTP request/response cycle. |
|
599 |
# |
|
4
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
600 |
if response.body == "": |
0 | 601 |
response.body = HTTPCODE[ response.status ].desc |
602 |
response[ "Content-Length" ] = $( response.body.len ) |
|
603 |
else: |
|
604 |
response[ "Content-Length" ] = $( response.body.len ) |
|
605 |
||
606 |
let code = "$1 $2" % [ $(response.status), HTTPCODE[response.status].label ] |
|
607 |
conn_id = newTNetstringString( response.conn_id ).dump_tnetstring |
|
608 |
result = response.sender_id & ' ' & conn_id |
|
609 |
result = result & " HTTP/1.1 " & code & CRLF |
|
610 |
||
611 |
for header in response.headers: |
|
612 |
result = result & header.name & ": " & header.value & CRLF |
|
613 |
||
614 |
result = result & CRLF & response.body |
|
615 |
||
616 |
||
617 |
proc handle_default( request: M2Request ): M2Response = |
|
618 |
## This is the default handler, if the caller didn't install one. |
|
619 |
result = request.response |
|
620 |
result[ "Content-Type" ] = "text/html" |
|
621 |
result.body = DEFAULT_CONTENT |
|
622 |
||
623 |
||
6
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
624 |
proc handle_disconnect( request: M2Request ): void = |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
625 |
## This is the default disconnect handler, if the caller didn't install one. |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
626 |
return |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
627 |
|
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
628 |
|
0 | 629 |
proc run*( handler: M2Handler ) {. noreturn .} = |
630 |
## Enter the request loop conversation with Mongrel2. |
|
631 |
## If an action() proc is attached, run that to generate |
|
632 |
## a response. Otherwise, run the default. |
|
633 |
while true: |
|
634 |
var |
|
635 |
request: M2Request |
|
636 |
response: M2Response |
|
637 |
info: string |
|
638 |
||
639 |
request = parse_request( handler.request_sock.receive ) # block, waiting for next request |
|
640 |
||
641 |
# Ignore disconnects unless there's a separate |
|
642 |
# disconnect_action. |
|
643 |
# |
|
644 |
if request.is_disconnect: |
|
6
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
645 |
if isNil( handler.disconnect_action ): |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
646 |
handler.disconnect_action = handle_disconnect |
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
647 |
handler.disconnect_action( request ) |
0 | 648 |
|
649 |
# Defer regular response content to the handler action. |
|
650 |
# |
|
651 |
if isNil( handler.action ): |
|
652 |
handler.action = handle_default |
|
653 |
response = handler.action( request ) |
|
654 |
||
655 |
if response.status == 0: response.status = HTTP_OK |
|
656 |
||
657 |
if defined( testing ): |
|
658 |
echo "REQUEST:\n", repr(request) |
|
659 |
echo "RESPONSE:\n", repr(response) |
|
660 |
||
661 |
info = "$1 $2 $3" % [ |
|
662 |
request.remote_addr, |
|
663 |
request.meth, |
|
664 |
request.uri |
|
665 |
] |
|
666 |
||
667 |
echo "$1: $2 --> $3 $4" % [ |
|
6
d49437ff8f2f
Updates for more recent (v1.6.0) nim.
Mahlon E. Smith <mahlon@martini.nu>
parents:
4
diff
changeset
|
668 |
$(get_time()), |
0 | 669 |
info, |
670 |
$( response.status ), |
|
671 |
HTTPCODE[ response.status ].label |
|
672 |
] |
|
673 |
||
674 |
handler.response_sock.send( response.format ) |
|
675 |
||
676 |
||
677 |
||
678 |
# |
|
679 |
# Tests! |
|
680 |
# |
|
681 |
when isMainModule: |
|
682 |
||
683 |
var reqstr = """host 33 /hosts 502:{"PATH":"/hosts","x-forwarded-for":"10.3.0.75","cache-control":"max-age=0","accept-language":"en-US,en;q=0.5","connection":"keep-alive","accept-encoding":"gzip, deflate","dnt":"1","accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","user-agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0","host":"hotsoup.sunset.laika.com:8080","METHOD":"GET","VERSION":"HTTP/1.1","URI":"/hosts","PATTERN":"/hosts","URL_SCHEME":"http","REMOTE_ADDR":"10.3.0.75"},0:,""" |
|
684 |
||
685 |
var req = parse_request( reqstr ) |
|
686 |
var dreq = parse_request( """host 1234 @* 17:{"METHOD":"JSON"},21:{"type":"disconnect"},""" ) |
|
687 |
||
688 |
# Request parsing. |
|
689 |
# |
|
690 |
doAssert( req.sender_id == "host" ) |
|
691 |
doAssert( req.conn_id == "33" ) |
|
692 |
doAssert( req.path == "/hosts" ) |
|
693 |
doAssert( req.remote_addr == "10.3.0.75" ) |
|
694 |
doAssert( req.scheme == "http" ) |
|
695 |
doAssert( req.meth == "GET" ) |
|
696 |
doAssert( req["DNT"] == "1" ) |
|
697 |
doAssert( req["X-Forwarded-For"] == "10.3.0.75" ) |
|
698 |
||
699 |
doAssert( req.is_disconnect == false ) |
|
700 |
||
701 |
var res = req.response |
|
702 |
res.status = HTTP_OK |
|
703 |
||
704 |
doAssert( res.sender_id == req.sender_id ) |
|
705 |
doAssert( res.conn_id == req.conn_id ) |
|
706 |
||
707 |
# Response headers |
|
708 |
# |
|
709 |
res.add_header( "alright", "yep" ) |
|
710 |
res[ "something" ] = "nope" |
|
711 |
res[ "something" ] = "yep" |
|
712 |
doAssert( res["alright"] == "yep" ) |
|
713 |
doAssert( res["something"] == "yep" ) |
|
714 |
||
715 |
# Client broadcasts |
|
716 |
# |
|
717 |
res.broadcast([ 1, 2, 3, 4 ]) |
|
718 |
doAssert( res.conn_id == "1 2 3 4" ) |
|
719 |
doAssert( res.format == "host 7:1 2 3 4, HTTP/1.1 200 OK\r\nalright: yep\r\nsomething: yep\r\nContent-Length: 2\r\n\r\nOK" ) |
|
720 |
||
721 |
# Extended replies |
|
722 |
# |
|
723 |
doAssert( res.is_extended == false ) |
|
724 |
res.extend( "sendfile" ) |
|
725 |
doAssert( res.is_extended == true ) |
|
726 |
doAssert( res.format == "host 9:X 1 2 3 4, 11:8:sendfile,]" ) |
|
727 |
res.add_extended_data( "arg1", "arg2" ) |
|
728 |
res.add_extended_data( "arg3" ) |
|
729 |
doAssert( res.format == "host 9:X 1 2 3 4, 32:8:sendfile,4:arg1,4:arg2,4:arg3,]" ) |
|
730 |
||
731 |
doAssert( dreq.is_disconnect == true ) |
|
732 |
||
733 |
# Automatic body if none is specified |
|
734 |
# |
|
4
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
735 |
res.extended = "" |
ffb8b9920057
Re-arrange for use with nimble, updates for nim 0.19.
Mahlon E. Smith <mahlon@martini.nu>
parents:
3
diff
changeset
|
736 |
res.body = "" |
0 | 737 |
res.status = HTTP_CREATED |
738 |
discard res.format |
|
739 |
doAssert( res.body == "Created" ) |
|
740 |
||
741 |
echo "* Tests passed!" |
|
742 |