forked from laarc/laarc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
srv.arc
783 lines (632 loc) · 23.3 KB
/
srv.arc
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
; HTTP Server.
; To improve performance with static files, set static-max-age*.
(= arcdir* (libpath "arc/")
logdir* (libpath "arc/logs/")
staticdir* (libpath "static/"))
(or= quitsrv* nil breaksrv* nil killreq* (no (readenv "DEV" nil)))
(def serve ((o port 8080) repl: (o repl? (readenv "DEV")))
(wipe quitsrv*)
(ensure-srvdirs)
(map [apply new-bgthread _] pending-bgthreads*)
(w/socket s port
(setuid 2) ; XXX switch from root to pg
(ero "ready to serve http://localhost:@port")
(= currsock* s)
(def serving ()
(until quitsrv*
(handle-request s breaksrv*)))
(if repl?
(do (thread:serving)
(interact))
(serving)))
(prn "quit server"))
(def serve1 ((o port 8080))
(w/socket s port (handle-request s t)))
(def ensure-srvdirs ()
(map ensure-dir (list arcdir* logdir* staticdir*)))
(or= srv-noisy* nil)
; http requests currently capped at 2 meg by socket-accept
; should threads process requests one at a time? no, then
; a browser that's slow consuming the data could hang the
; whole server.
; wait for a connection from a browser and start a thread
; to handle it. also arrange to kill that thread if it
; has not completed in threadlife* seconds.
(or= threadlife* 30 requests* 0 requests/ip* (table)
throttle-ips* (table) ignore-ips* (table) spurned* (table))
(def handle-request (s breaksrv)
(if breaksrv
(handle-request-1 s)
(errsafe (handle-request-1 s))))
(def handle-request-1 (s)
(let (i o ip) (socket-accept s)
(if (and (or (ignore-ips* ip) (abusive-ip ip))
(++ (spurned* ip 0)))
(force-close i o)
(do (withs (th1 nil th2 nil)
(= th1 (thread
(after (handle-request-thread i o ip)
(close i o)
(kill-thread th2))))
(= th2 (thread
(sleep threadlife*)
(when killreq*
(unless (dead th1)
(prn "srv thread took too long for " ip))
(break-thread th1)
(force-close i o)))))))))
; Returns true if ip has made req-limit* requests in less than
; req-window* seconds. If an ip is throttled, only 1 request is
; allowed per req-window* seconds. If an ip makes req-limit*
; requests in less than dos-window* seconds, it is a treated as a DoS
; attack and put in ignore-ips* (for this server invocation).
; To adjust this while running, adjust the req-window* time, not
; req-limit*, because algorithm doesn't enforce decreases in the latter.
(or= req-times* (table) req-limit* 30 req-window* 10 dos-window* 2 dos-protection* nil)
(def abusive-ip (ip)
(and dos-protection*
(only&> (requests/ip* ip) 250)
(let now (seconds)
(do1 (if (req-times* ip)
(and (>= (qlen (req-times* ip))
(if (throttle-ips* ip) 1 req-limit*))
(let dt (- now (deq (req-times* ip)))
(if (< dt dos-window*) (set (ignore-ips* ip)))
(< dt req-window*)))
(do (= (req-times* ip) (queue))
nil))
(enq now (req-times* ip))))))
(def noisy-header (lines (o label) (o footer "\n"))
(when srv-noisy*
(atomic
(if label (pr label))
(each line lines
(prn line))
(if footer (pr footer))
(flushout)))
lines)
(def handle-request-thread (i o ip)
(withs (nls 0 lines nil line nil responded nil t0 (msec))
(after
(whilet c (unless responded (readc i))
(if (is c #\newline)
(if (is (++ nls) 2)
(withs (h (noisy-header (rev lines) (+ "Time: " (moment) "\nHeader: "))
(type op args n cooks ip . more) (parseheader h ip))
(let t1 (msec)
(case type
get (respond o op args cooks ip)
post (handle-post i o op args n cooks ip)
(respond-err o "Unknown request: " (car lines)))
(log-request type op args cooks ip t0 t1)
(set responded)))
(do (push (string (rev line)) lines)
(wipe line)))
(unless (is c #\return)
(push c line)
(= nls 0))))
(close i o)))
(harvest-fnids))
(def log-request (type op args cooks ip t0 t1)
(withs (parsetime (- t1 t0) respondtime (- (msec) t1))
(srvlog 'srv ip
parsetime
respondtime
(if (> (+ parsetime respondtime) 1000) "***" "")
type
op
(let arg1 (car args)
(if (caris arg1 "fnid") ""
(caris arg1 "X-Arc-Secure") ""
arg1))
cooks)))
; Could ignore return chars (which come from textarea fields) here by
; (unless (is c #\return) (push c line))
(def handle-post (i o op args n cooks ip)
(if (no n)
(respond-err o "Post request without Content-Length.")
(let line nil
(whilet c (and (> n 0) (readc i))
(-- n)
(push c line))
(let line (string (rev line))
(noisy-header (list line) "Post Contents: ")
(respond o op (+ (parseargs line) args) cooks ip)))))
(or= type-header* (table))
(def gen-type-header (ctype)
(+ "HTTP/1.0 200 OK
Content-Type: "
ctype
"
Connection: close"))
(= header* (gen-type-header "text/html; charset=utf-8"))
(= secure-header* "X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31556900
";Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ https://cdnjs.cloudflare.com/; frame-src 'self' https://www.google.com/recaptcha/; style-src 'self' 'unsafe-inline'"
)
(map (fn ((k v)) (= (type-header* k) (gen-type-header v)))
'((image/x-icon "image/x-icon")
(image/svg "image/svg+xml")
(image/gif "image/gif")
(image/jpg "image/jpeg")
(image/png "image/png")
(text/plain "text/plain")
(text/html "text/html; charset=utf-8")
(text/css "text/css")
(text/xml "text/xml")
(text/csv "text/csv")
(application/json "application/json")
(application/javascript "application/javascript")
(application/manifest "application/manifest+json")
))
(= rdheader* "HTTP/1.0 302 Moved")
(or= srvops* (table) redirector* (table) optimes* (table) opcounts* (table))
(def save-optime (name elapsed)
; this is the place to put a/b testing
; toggle a flag and push elapsed into one of two lists
(++ (opcounts* name 0))
(unless (optimes* name) (= (optimes* name) (queue)))
(enq-limit elapsed (optimes* name) 1000))
; For ops that want to add their own headers. They must thus remember
; to prn a blank line before anything meant to be part of the page.
(mac defop-raw (name parms . body)
(w/uniq t1
`(= (srvops* ',name)
(fn ,parms
(let ,t1 (msec)
(do1 (do ,@body)
(save-optime ',name (- (msec) ,t1))))))))
(mac defopr-raw (name parms . body)
`(= (redirector* ',name) t
(srvops* ',name) (fn ,parms ,@body)))
(mac defop (name parm :header . body)
(w/uniq gs
`(do ,(if header `(= (static-header* ',name) ,header))
(wipe (redirector* ',name))
(defop-raw ,name (,gs ,parm)
(w/stdout ,gs (prn) ,@body)))))
; Defines op as a redirector. Its retval is new location.
(mac defopr (name parm . body)
(w/uniq gs
`(do (set (redirector* ',name))
(defop-raw ,name (,gs ,parm)
,@body))))
;(mac testop (name . args) `((srvops* ',name) ,@args))
(deftem request
args nil
cooks nil
ip nil)
(= unknown-msg* "Unknown.")
(or= max-age* (table) static-header* (table) static-max-age* nil)
(def respond (str op args cooks ip)
(or (hook 'respond str op args cooks ip)
(w/stdout str
(let (op args) (parseop op args)
(iflet f (srvops* op)
(let req (the-req*)
(= req!op op
req!args args)
(if (redirector* op)
(do (prn rdheader*)
(aand (or (hook 'respond-headers str req f t)
(f str req)
"/")
(prn "Location: " it))
(prn))
(do (prn (aif (static-header* op) (gen-type-header it) header*))
(awhen (max-age* op)
(prn "Cache-Control: max-age=" it))
(when (srvsecure req)
(prn secure-header*))
(or (hook 'respond-headers str req f nil)
(f str req)))))
(withs (op (car (tokens op #\?))
filetype (static-filetype op))
(aif (and filetype (file-exists (string staticdir* op)))
(do (prn (or (static-header* op) (type-header* filetype)))
(awhen static-max-age*
(prn "Cache-Control: max-age=" it))
(prn)
(w/infile i it
(whilet b (readb i)
(writeb b str))))
(respond-err str unknown-msg*))))))))
(def static-filetype (sym)
(let fname (str sym)
(and (~find #\/ fname)
(case (downcase (last (check (tokens fname #\.) ~single)))
"ico" 'image/x-icon
"svg" 'image/svg
"gif" 'image/gif
"jpg" 'image/jpg
"jpeg" 'image/jpg
"png" 'image/png
"css" 'text/css
"txt" 'text/plain
"htm" 'text/html
"html" 'text/html
"arc" 'text/plain
"csv" 'text/csv
"xml" 'text/xml
"js" 'application/javascript
"json" 'application/json
"webmanifest" 'application/manifest
))))
(def static-src (filename)
(string "/" filename "?" (shashfile (+ staticdir* filename))))
#'(require file/sha1)
(def shash (str)
(#'sha1 (instring str)))
(defmemo shashfile-1 (filename modtime)
(w/infile i filename
(#'sha1 i)))
(def shashfile (filename)
(shashfile-1 filename (modtime filename)))
(def respond-err (str msg . args)
(w/stdout str
(prn header*)
(prn)
(apply pr msg args)))
(def parseop (op args)
(let xs (tokens op #\/)
(if (< (len xs) 2)
(list op args)
(list (sym (car xs)) (+ (list (list "path" (concat (map urldecode (cdr xs)) #\/))) args)))))
(or= the-header* (make-param nil false 'the-header*)
the-req* (make-param (table) false 'the-req*))
(def srvsecure ((o req (the-req*)))
(is (arg req "X-Arc-Secure") "1"))
(def parsereq (xs)
(let (type op args n cooks ip . more) xs
(the-req* (inst 'request 'type type 'op op 'args args 'cooks cooks 'n n 'ip ip 'more more))
(++ requests*)
(++ (requests/ip* ip 0))
xs))
(def parseheader (lines (o ip))
(the-header* lines)
(let (type op args) (parseurl (car lines))
(parsereq
(list type
op
(+ args
(rem nil (map [when (begins _ "X-Arc-")
(tokens _ [or (whitec _) (is _ #\:)])]
(cdr lines))))
(and (is type 'post)
(some (fn (s)
(and (begins s "Content-Length:")
(errsafe:coerce (cadr (tokens s)) 'int)))
(cdr lines)))
(some (fn (s)
(and (or (begins s "Cookie:")
(begins s "cookie:"))
(parsecookies s)))
(cdr lines))
(or (some (fn (s)
(and (begins s "CF-Connecting-IP:")
(errsafe:cadr (tokens s))))
(cdr lines))
ip)))))
; (parseurl "GET /p1?foo=bar&ug etc") -> (get p1 (("foo" "bar") ("ug")))
(def parseurl (s)
(let (type url) (tokens s)
(let (base args) (tokens url #\?)
(list (sym (downcase type))
(sym (cut base 1))
(if args
(parseargs args)
nil)))))
; I don't urldecode field names or anything in cookies; correct?
(def parseargs (s)
(map (fn ((k v)) (list k (urldecode v)))
(map [tokens _ #\=] (tokens s #\&))))
(def parsecookies (s)
(map [tokens _ #\=]
(cdr (tokens s [or (whitec _) (is _ #\;)]))))
(def arg args
(case (len args)
0 ((the-req*) 'args)
1 (apply arg (the-req*) args)
(let (req key) args
(alref req!args (str key)))))
; *** Warning: does not currently urlencode args, so if need to do
; that replace v with (urlencode v).
(def reassemble-args ((o req (the-req*)))
(aif req!args
(apply string "?" (intersperse '&
(map (fn ((k v))
(string k '= v))
it)))
""))
(or= fns* (table) fnkeys* (table) fnids* (table) timed-fnids* (table))
(def lexval (e)
(each (id getx setx) e
(let v (if (isa getx 'fn) (getx) getx)
(unless (or (is v (the-req*))
(isa v 'fn))
(out v)))))
(def lextree (x)
(treewise cons [case (type _)
sym (rem digit _)
fn (sym:tostring:pr _)
_]
x))
(def lexcompile (expr)
(lextree (ac expr)))
(mac lexkey (name . body)
`(list ',name
(lexval (lexenv))
',(map lexcompile body)))
; count on huge (expt 64 22) size of fnid space to avoid clashes
(def gen-fnid ()
(sym:rand-string 22))
(def fnid-key (key (o req (the-req*)))
(list (get-user)
req!op
(when (is (str req!type) "get")
(reassemble-args req))
key))
(def new-fnid ((o key))
(if key
(or= (fnkeys* (fnid-key key))
(gen-fnid))
(gen-fnid)))
(def fnidf (f k)
(atwith key (new-fnid k)
(= (fns* key) f
(fnids* key) (list (now) (get-user)))
(wipe (timed-fnids* key))))
(def timed-fnidf (lasts f k)
(atwith key (new-fnid k)
(= (fns* key) f
(timed-fnids* key) (list (now) lasts (get-user)))
(wipe (fnids* key))))
(mac fnid (f (o k `(lexkey fnid ,f))) `(fnidf ,f ,k))
(mac timed-fnid (lasts f (o k `(lexkey fnid ,f))) `(timed-fnidf ,lasts ,f ,k))
; Within f, it will be bound to the fn's own fnid. Remember that this is
; so low-level that need to generate the newline to separate from the headers
; within the body of f.
(mac afnid (f (o k `(lexkey afnid ,f)))
`(atwith it (new-fnid ,k)
(= (fns* it) ,f
(fnids* it) (list (now) (get-user)))
(wipe (timed-fnids* it))))
;(defop test-afnid req
; (tag (a href (url-for (afnid (fn (req) (prn) (pr "my fnid is " it)))))
; (pr "click here")))
; To be more sophisticated, instead of killing fnids, could first
; replace them with fns that tell the server it's harvesting too
; aggressively if they start to get called. But the right thing to
; do is estimate what the max no of fnids can be and set the harvest
; limit there-- beyond that the only solution is to buy more memory.
(= fnid-harvest-max* 50000 ; was 20000
fnid-harvest-ratio* 10
fnid-hours-max* 6)
(def fnids ((o getter car))
(map getter (sortable fnids* < car)))
(def kill-fnid (id)
(wipe (fnids* id) (timed-fnids* id) (fns* id)) t)
(def user-fnids (user)
(sort (compare > car)
(each (id (created subj)) fnids*
(when (is subj user)
(out (minutes-since created) id)))))
(def dead-fnids ((o max-hours fnid-hours-max*))
(+ (each (id (created lasts)) timed-fnids*
(when (> (since created) lasts)
(out id)))
(each (id (created user)) fnids*
(when (>= (hours-since created) max-hours)
(out id)))))
(def harvest-fnids ((o force nil)
(o n fnid-harvest-max*)
(o r fnid-harvest-ratio*))
(when (or force (len> fns* n))
(each id (dead-fnids)
(kill-fnid id))
(when (or force (len> fns* n))
(atlet nharvest (trunc (/ (min n (len fns*)) r))
(let (kill keep) (split (fnids) nharvest)
(each id kill
(kill-fnid id)))))))
(= fnurl* "/x" rfnurl* "/r" rfnurl2* "/y" jfnurl* "/a")
(= todo-msg* (tostring:gentag img src "/todo.gif" width 18 height 18)
dead-msg* (+ "\nUnknown or expired link. " (tostring:br) todo-msg*))
(defop-raw x (str req)
(w/stdout str
(aif (fns* (sym (arg req "fnid")))
(it req)
(pr dead-msg*))))
(defopr-raw y (str req)
(aif (fns* (sym (arg req "fnid")))
(w/stdout str (it req))
"deadlink"))
; For asynchronous calls; discards the page. Would be better to tell
; the fn not to generate it.
(defop-raw a (str req)
(aif (fns* (sym (arg req "fnid")))
(tostring (it req))))
(defopr r req
(aif (fns* (sym (arg req "fnid")))
(it req)
"deadlink"))
(defop deadlink req
(pr dead-msg*))
(def url-for (fnid)
(string fnurl* "?fnid=" fnid))
(def flinkf (f k)
(string fnurl* "?fnid=" (fnid (fn (req) (prn) (f req)) k)))
(def rflinkf (f k)
(string rfnurl* "?fnid=" (fnid f k)))
(def fredir (f redir)
(w/uniq (ga gx gr)
(if redir
`(fn (,ga) (withs (,gx (,f ,ga) ,gr ,redir)
(if (isa ,gr 'string) ,gr ,gx)))
`(fn (,ga) (prn) (,f ,ga)))))
(mac flink (f (o k `(lexkey flink ,f)) :redir)
(if redir
`(rflinkf ,(fredir f redir) ,k)
`(flinkf ,f ,k)))
(mac rflink (f)
`(flink ,f :redir))
; Since it's just an expr, gensym a parm for (ignored) args.
(mac w/link (expr :redir . body)
`(tag (a href (flink redir: ,redir (fn (,(uniq)) ,expr)))
,@body))
(mac w/rlink (expr . body)
`(w/link :redir ,expr ,@body))
(mac onlink (text :redir . body)
`(w/link redir: ,redir (do ,@body) (pr ,text)))
(mac onrlink (text . body)
`(onlink :redir ,text ,@body))
; bad to have both flink and linkf; rename flink something like fnid-link
(mac linkf (text parms :redir . body)
(w/uniq gtext
`(let ,gtext ,text
(tag (a href (flink redir: ,redir (fn ,parms ,@body)))
(pr ,gtext)))))
(mac rlinkf (text parms . body)
`(linkf :redir ,text ,parms ,@body))
;(defop top req (linkf 'whoami? (req) (pr "I am " (get-user))))
;(defop testf req (w/link (pr "ha ha ha") (pr "laugh")))
(mac w/link-if (test expr :redir . body)
`(tag-if ,test (a href (flink redir: ,redir (fn (,(uniq)) ,expr)))
,@body))
(def fnid-field (id)
(gentag input type 'hidden name 'fnid value id))
; f should be a fn of one arg, which will be http request args.
(def fnformf (f bodyfn (o redir) (o k))
(tag (form method 'post action (if redir rfnurl2* fnurl*))
(fnid-field (fnid f k))
(bodyfn)))
(mac fnform (f bodyfn (o redir) (o k `(lexkey fnform ,f ,bodyfn ,redir)))
`(fnformf ,f ,bodyfn ,redir ,k))
; Could also make a version that uses just an expr, and var capture.
; Is there a way to ensure user doesn't use "fnid" as a key?
(mac aform (f :redir . body)
`(tag (form method 'post action ,(if redir 'rfnurl* 'fnurl*))
(fnid-field (fnid ,(fredir f redir) (lexkey aform ,f ,@body)))
,@body))
;(defop test1 req
; (fnform (fn (req) (prn) (pr req))
; (fn () (single-input "" 'foo 20 "submit"))))
;(defop test2 req
; (aform (fn (req) (pr req))
; (single-input "" 'foo 20 "submit")))
; Like aform except creates a fnid that will last for lasts seconds
; (unless the server is restarted).
(mac taform (lasts f :redir . body)
(w/uniq (gl gf gi ge)
`(withs (,gl ,lasts
,ge (lexkey taform ,f ,@body)
,gf ,(fredir f redir))
(tag (form method 'post action ,(if redir 'rfnurl* 'fnurl*))
(fnid-field (if ,gl (timed-fnid ,gl ,gf ,ge) (fnid ,gf ,ge)))
,@body))))
(mac arform (f . body)
`(aform :redir ,f ,@body))
(mac tarform (lasts f . body)
`(taform :redir ,lasts ,f ,@body))
(mac aformh (f :redir . body)
`(tag (form method 'post action ,(if redir 'rfnurl2* 'fnurl*))
(fnid-field (fnid ,(fredir f redir) (lexkey aformh ,f ,@body)))
,@body))
(mac arformh (f . body)
`(aformh ,f :redir ,@body))
; only unique per server invocation
(or= unique-ids* (table))
(def unique-id ((o len 32))
(let id (sym (rand-string (max 5 len)))
(if (unique-ids* id)
(unique-id)
(= (unique-ids* id) id))))
(def srvlog (type . args)
(w/appendfile o (logfile-name type)
(w/stdout o (atomic (apply prs (seconds) args) (prn)))))
(def logfile-name (type)
(string logdir* type "-" (memodate)))
(withs (lastasked nil lastval nil)
(def memodate ()
(let now (seconds)
(if (or (no lastasked) (> (- now lastasked) 60))
(= lastasked now lastval (datestring))
lastval)))
)
(unless (srvops* '||)
(defop || req (pr "It's alive.")))
(defop topips req
(when (admin)
(whitepage
(sptab
(each ip (with leaders nil
(each (ip n) requests/ip*
(when (>= n 1)
(insort (compare > requests/ip*)
ip
leaders))))
(let n (requests/ip* ip)
(row ip n (pr (num (* 10 (/ n requests*)) 1)))))))))
(defop spurned req
(when (admin)
(whitepage
(sptab
(map (fn ((ip n)) (row ip n))
(sortable spurned* >))))))
; eventually promote to general util
(def sortable (ht (o f >) (o key idfn))
(sort (compare f key:cadr) (each (k v) ht (out k v))))
; Background Threads
(or= bgthreads* (table) pending-bgthreads* nil bgthreads-noisy* nil)
(mac bgthread (name f sec)
`(let ,name (fn ()
(while t
(sleep ,sec)
(when bgthreads-noisy*
(ero sep: "" "Running background thread " ',name " via " ,f " (every " ,sec "s)"))
(,f)))
(new-thread ,name)))
(def new-bgthread (id f sec)
(aif (bgthreads* id) (break-thread it))
(= (bgthreads* id) (eval `(bgthread ,id ,f ,sec))))
; should be a macro for this?
(mac defbg (id sec . body)
(let name (+ id '-bg)
`(do (def ,name () ,@body)
(pull [caris _ ',id] pending-bgthreads*)
(push (list ',id ',name ,sec)
pending-bgthreads*)
(when (bgthreads* ',id)
(new-bgthread ',id ',name ,sec)))))
; reload changed code each request
(def noisy-reload ()
(awhen (any:reload)
(ero it)))
(when (readenv "DEV" nil)
(defhook respond (str op args cooks ips . rest)
(noisy-reload)
(hook 'reload-admins)
(when srv-noisy*
(let (op args) (parseop op args)
(when (srvops* op)
(ero op))))
nil))
; pull from github periodically
(or= git-pull-time* (readenv "PULL" nil)
git-pull-count* 0)
(def git-pull-reload ()
(when (errsafe:git-pull)
(when (readenv "NUKE")
(errsafe:git-reset-to-origin t))
(++ git-pull-count*))
(errsafe:reload))
(def git-pull-stats ()
(git-pull-reload)
(cons git-pull-count* (reload-stats)))
(awhen git-pull-time*
(defbg git-pull it (git-pull-reload)))
; Idea: make form fields that know their value type because of
; gensymed names, and so the receiving fn gets args that are not
; strings but parsed values.