Fix indents
[tt.git] / tt.rkt
CommitLineData
cd541405 1#lang typed/racket/no-check
4764ff89 2
1d753430 3(require openssl/sha1)
4764ff89 4(require racket/date)
9c464d95 5(require
d718efc4 6 net/head
edadb804 7 net/uri-codec
8da029e4 8 net/url)
4764ff89 9
3c9c8266
SK
10(require (prefix-in info: "info.rkt"))
11
78398948 12(module+ test
de3ff448 13 (require rackunit))
78398948 14
98529d3d
SK
15(define-type Url
16 net/url-structs:url)
17
18(define-type Out-Format
19 (U 'single-line
20 'multi-line))
21
22(define-type Timeline-Order
23 (U 'old->new
24 'new->old))
25
7fd20778
SK
26(define-type Result
27 (∀ (α β) (U (cons 'ok α)
28 (cons 'error β))))
29
7296ed94 30(struct User
3dc554da
SK
31 ([uri : Url]
32 [nick : (Option String)]))
7296ed94
SK
33
34(struct User-Agent
3dc554da
SK
35 ([user : User]
36 [prog : Prog]))
7296ed94
SK
37
38(struct Prog
3dc554da
SK
39 ([name : String]
40 [version : String]))
7296ed94 41
b0ff061a 42(struct Msg
78142acb 43 ([ts-epoch : Integer]
3877a0c4 44 [ts-orig : String]
0cb1ae9c 45 [from : Peer]
13c11724 46 [text : String]
b0ff061a 47 [mentions : (Listof Peer)]))
9c464d95 48
dbc26280 49(struct Peer
b056019b
SK
50 ([nick : (Option String)]
51 [uri : Url]
e2840743 52 [uri-str : String]
b056019b 53 [comment : (Option String)])
d0a0e073 54 #:transparent)
4764ff89 55
f65d6338
SK
56(struct Resp
57 ([status-line : String]
58 [headers : (Listof Bytes)]
7fd20778
SK
59 [body-input : Input-Port])
60 #:transparent)
f65d6338 61
7296ed94
SK
62(: prog Prog)
63(define prog
64 (Prog "tt" (info:#%info-lookup 'version)))
65
66(: user-default User)
67(define user-default
ab7bf8d5 68 (User (string->url "https://github.com/xandkar/tt") #f))
7296ed94
SK
69
70(: user->str (-> User String))
71(define (user->str user)
ab7bf8d5
SK
72 (match-define (User u0 n) user)
73 (define u (url->string u0))
7296ed94 74 (if n
3dc554da
SK
75 (format "+~a; @~a" u n)
76 (format "+~a" u )))
7296ed94
SK
77
78(: user-agent->str (-> User-Agent String))
79(define (user-agent->str ua)
80 (match-define (User-Agent u p) ua)
81 (format "~a/~a (~a)" (Prog-name p) (Prog-version p) (user->str u)))
82
83(: user->user-agent User)
84(define (user->user-agent user)
85 (User-Agent user prog))
86
87(: user-agent-str String)
88(define user-agent-str
89 (user-agent->str (user->user-agent user-default)))
90
91(: set-user-agent-str (-> Path-String Void))
92(define (set-user-agent-str filename)
93 (set! user-agent-str (user-agent->str (user->user-agent (file->user filename))))
94 (log-info "User-Agent string is now set to: ~v" user-agent-str))
95
96(: file->user (-> Path-String User))
97(define (file->user filename)
98 (if (file-exists? filename)
99 (match (set->list (file->peers filename))
100 [(list p)
101 (log-info
102 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
103 filename
104 (peer->str p))
105 (peer->user p)]
106 [(list* p _)
107 (log-warning
108 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
109 filename
110 (peer->str p))
111 (peer->user p)]
112 ['()
113 (log-warning
114 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
115 filename
116 user-default)
117 user-default])
118 (begin
119 (log-warning
120 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
121 filename
122 user-default)
123 user-default)))
124
ab7bf8d5 125(: peer->user (-> Peer User))
7296ed94 126(define (peer->user p)
ab7bf8d5 127 (match-define (Peer n u _ _) p)
7296ed94
SK
128 (User u n))
129
0cb1ae9c
SK
130(: peers-equal? (-> Peer Peer Boolean))
131(define (peers-equal? p1 p2)
132 (equal? (Peer-uri-str p1)
133 (Peer-uri-str p2)))
134
135(: peer-hash (-> Peer Fixnum))
136(define (peer-hash p)
137 (equal-hash-code (Peer-uri-str p)))
138
e2840743
SK
139(define-custom-set-types peers
140 #:elem? Peer?
0cb1ae9c
SK
141 peers-equal?
142 peer-hash)
e2840743
SK
143; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
144; the following contract violations:
145;
146; custom-elem-contents: contract violation
147; expected: custom-elem?
148; given: #f
149; context...:
150; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
151; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
152; /usr/share/racket/collects/racket/cmdline.rkt:191:51
153; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
154;
155; TODO Investigate why and make a minimal reproducible test case.
156
50f0609d
SK
157(define (peers-union . peer-sets)
158 (define groups
159 (foldl
160 (λ (p groups)
161 (hash-update groups (Peer-uri-str p) (λ (group) (cons p group)) '()))
162 (hash)
163 (append* (map set->list peer-sets))))
164 (define (merge peers)
165 (match peers
166 ['() (raise 'impossible)]
167 [(list p) p]
168 [(list* p1 p2 ps)
169 (let* ([n1 (Peer-nick p1)]
170 [n2 (Peer-nick p2)]
171 [p (cond
172 [(and (not n1) (not n2)) p1]
173 [(and n1 n2 ) p1]
174 [(and n1 (not n2)) p1]
175 [(and (not n1) n2) p2]
176 [else
177 (raise 'impossible)])])
178 (merge (cons p ps)))]))
179 (make-immutable-peers (map merge (hash-values groups))))
180
181(module+ test
182 (let* ([u1 "http://foo/bar"]
183 [u2 "http://baz/quux"]
184 [p1 (Peer #f (string->url u1) u1 #f)]
185 [p2 (Peer "a" (string->url u1) u1 #f)]
186 [p3 (Peer "b" (string->url u2) u2 #f)]
187 [s1 (make-immutable-peers (list p1))]
188 [s2 (make-immutable-peers (list p2 p3))])
189 (check-true (peers? (peers-union s1 s2)))
190 (check-true (peers? (peers-union s2 s1)))
191 (check-equal? (list p3 p2) (set->list (peers-union s1 s2)))
192 (check-equal? (list p3 p2) (set->list (peers-union s2 s1)))))
193
edadb804
SK
194(: tt-home-dir Path-String)
195(define tt-home-dir (build-path (expand-user-path "~") ".tt"))
196
9a346534 197(: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
78142acb 198(define (concurrent-filter-map num-workers f xs)
dad4504d 199 ; TODO preserve order of elements OR communicate that reorder is expected
a239a233 200 ; TODO switch from mailboxes to channels
895a32cf
SK
201 (define (make-worker id f)
202 (define parent (current-thread))
203 (λ ()
a9511f7c
SK
204 (define self : Thread (current-thread))
205 (: work (∀ (α) (-> α)))
895a32cf
SK
206 (define (work)
207 (thread-send parent (cons 'next self))
208 (match (thread-receive)
c562bea3
SK
209 ['done (thread-send parent (cons 'exit id))]
210 [(cons 'unit x) (begin
211 (define y (f x))
212 (when y (thread-send parent (cons 'result y)))
213 (work))]))
895a32cf 214 (work)))
a9511f7c 215 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
895a32cf
SK
216 (define (dispatch ws xs ys)
217 (if (empty? ws)
f1493e49
SK
218 ys
219 (match (thread-receive)
c562bea3
SK
220 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
221 [(cons 'result y) (dispatch ws xs (cons y ys))]
222 [(cons 'next thd) (match xs
223 ['() (begin
224 (thread-send thd 'done)
225 (dispatch ws xs ys))]
226 [(cons x xs) (begin
227 (thread-send thd (cons 'unit x))
228 (dispatch ws xs ys))])])))
78142acb 229 (define workers (range num-workers))
9926c9a9
SK
230 (define threads (map (λ (id) (thread (make-worker id f))) workers))
231 (define results (dispatch workers xs '()))
895a32cf
SK
232 (for-each thread-wait threads)
233 results)
234
dad4504d 235(module+ test
de3ff448
SK
236 (let* ([f (λ (x) (if (even? x) x #f))]
237 [xs (range 11)]
238 [actual (sort (concurrent-filter-map 10 f xs) <)]
239 [expected (sort ( filter-map f xs) <)])
c562bea3 240 (check-equal? actual expected "concurrent-filter-map")))
dad4504d 241
98529d3d 242(: msg-print (-> Out-Format Integer Msg Void))
3d042e75
SK
243(define msg-print
244 (let* ([colors (vector 36 33)]
245 [n (vector-length colors)])
246 (λ (out-format color-i msg)
01e4c499 247 (let ([color (vector-ref colors (modulo color-i n))]
0cb1ae9c
SK
248 [nick (Peer-nick (Msg-from msg))]
249 [uri (Peer-uri-str (Msg-from msg))]
250 [text (Msg-text msg)])
3d042e75 251 (match out-format
01e4c499 252 ['single-line
13c11724
SK
253 (let ([nick (if nick nick uri)])
254 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
255 (parameterize
256 ([date-display-format 'iso-8601])
b0ff061a 257 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
13c11724 258 nick color text))]
01e4c499 259 ['multi-line
13c11724
SK
260 (let ([nick (if nick (string-append nick " ") "")])
261 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
262 (parameterize
263 ([date-display-format 'rfc2822])
b0ff061a
SK
264 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
265 (Msg-ts-orig msg)
13c11724 266 nick uri color text))])))))
e96264cc 267
3877a0c4
SK
268(: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
269(define rfc3339->epoch
270 (let ([re (pregexp "^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(:([0-9]{2}))?(\\.[0-9]+)?(Z|([+-])([0-9]{1,2}):?([0-9]{2}))?$")])
271 (λ (ts)
272 (match (regexp-match re ts)
273 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
274 (let*
275 ([tz-offset
276 (match* (tz-whole tz-sign tz-HH tz-MM)
277 [("Z" #f #f #f)
278 0]
279 [(_ (or "-" "+") (? identity h) (? identity m))
280 (let ([h (string->number h)]
281 [m (string->number m)]
282 ; Reverse to get back to UTC:
283 [op (match tz-sign ["+" -] ["-" +])])
284 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
285 [(a b c d)
286 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
287 0])]
288 [ts-orig ts]
289 [local-time? #f]
290 [ts-epoch (find-seconds (if SS (string->number SS) 0)
291 (string->number MM)
292 (string->number HH)
293 (string->number dd)
294 (string->number mm)
295 (string->number yyyy)
296 local-time?)])
297 (+ ts-epoch tz-offset))]
298 [_
b8b29fbb 299 (log-debug "Invalid timestamp: ~v" ts)
3877a0c4
SK
300 #f]))))
301
0cb1ae9c 302(: str->msg (-> Peer String (Option Msg)))
b4689464 303(define str->msg
3877a0c4 304 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
0cb1ae9c
SK
305 (λ (from str)
306 (define from-str (peer->str from))
d3ac9e11 307 (define str-head (substring str 0 (min 100 (string-length str))))
b4689464
SK
308 (with-handlers*
309 ([exn:fail?
310 (λ (e)
b8b29fbb 311 (log-debug
9c464d95 312 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
0cb1ae9c 313 str-head from-str e)
b4689464
SK
314 #f)])
315 (match (regexp-match re str)
3877a0c4
SK
316 [(list _wholething ts-orig text)
317 (let ([ts-epoch (rfc3339->epoch ts-orig)])
318 (if ts-epoch
13c11724
SK
319 (let ([mentions
320 (filter-map
321 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
322 [(list _wholething nick-uri)
dbc26280 323 (str->peer nick-uri)]))
13c11724 324 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
0cb1ae9c 325 (Msg ts-epoch ts-orig from text mentions))
3877a0c4 326 (begin
b8b29fbb 327 (log-debug
0cb1ae9c
SK
328 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
329 from-str str-head)
3877a0c4 330 #f)))]
b4689464 331 [_
0cb1ae9c 332 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
b4689464 333 #f])))))
88d50b3e 334
63afa259 335(module+ test
13c11724 336 ; TODO Test for when missing-nick case
b4689464
SK
337 (let* ([tzs (for*/list ([d '("-" "+")]
338 [h '("5" "05")]
339 [m '("00" ":00" "57" ":57")])
340 (string-append d h m))]
341 [tzs (list* "" "Z" tzs)])
342 (for* ([n '("fake-nick")]
0cb1ae9c 343 [u '("http://fake-uri")]
50f0609d 344 [p (list (Peer n (string->url u) u #f))]
b4689464
SK
345 [s '("" ":10")]
346 [f '("" ".1337")]
347 [z tzs]
348 [sep (list "\t" " ")]
349 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
350 (let* ([ts (string-append "2020-11-18T22:22"
351 (if (non-empty-string? s) s ":00")
352 z)]
0cb1ae9c 353 [m (str->msg p (string-append ts sep txt))])
b4689464 354 (check-not-false m)
0cb1ae9c 355 (check-equal? (Msg-from m) p)
b0ff061a
SK
356 (check-equal? (Msg-text m) txt)
357 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
b4689464
SK
358 )))
359
de3ff448
SK
360 (let* ([ts "2020-11-18T22:22:09-0500"]
361 [tab " "]
362 [text "Lorem ipsum"]
363 [nick "foo"]
0cb1ae9c 364 [uri "http://bar/"]
50f0609d 365 [peer (Peer nick (string->url uri) uri #f)]
0cb1ae9c
SK
366 [actual (str->msg peer (string-append ts tab text))]
367 [expected (Msg 1605756129 ts peer text '())])
c562bea3 368 (check-equal?
b0ff061a
SK
369 (Msg-ts-epoch actual)
370 (Msg-ts-epoch expected)
78142acb 371 "str->msg ts-epoch")
3877a0c4 372 (check-equal?
b0ff061a
SK
373 (Msg-ts-orig actual)
374 (Msg-ts-orig expected)
3877a0c4 375 "str->msg ts-orig")
c562bea3 376 (check-equal?
0cb1ae9c
SK
377 (Peer-nick (Msg-from actual))
378 (Peer-nick (Msg-from expected))
c562bea3
SK
379 "str->msg nick")
380 (check-equal?
0cb1ae9c
SK
381 (Peer-uri (Msg-from actual))
382 (Peer-uri (Msg-from expected))
c562bea3 383 "str->msg uri")
0cb1ae9c
SK
384 (check-equal?
385 (Peer-uri-str (Msg-from actual))
386 (Peer-uri-str (Msg-from expected))
387 "str->msg uri-str")
c562bea3 388 (check-equal?
b0ff061a
SK
389 (Msg-text actual)
390 (Msg-text expected)
c562bea3 391 "str->msg text")))
63afa259 392
98529d3d 393(: str->lines (-> String (Listof String)))
e96264cc
SK
394(define (str->lines str)
395 (string-split str (regexp "[\r\n]+")))
396
63afa259 397(module+ test
de3ff448 398 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
63afa259 399
0cb1ae9c
SK
400(: str->msgs (-> Peer String (Listof Msg)))
401(define (str->msgs peer str)
402 (filter-map (λ (line) (str->msg peer line))
403 (filter-comments (str->lines str))))
4764ff89 404
edadb804
SK
405(: cache-dir Path-String)
406(define cache-dir (build-path tt-home-dir "cache"))
407
d718efc4
SK
408(define cache-object-dir (build-path cache-dir "objects"))
409
edadb804
SK
410(: url->cache-file-path-v1 (-> Url Path-String))
411(define (url->cache-file-path-v1 uri)
412 (define (hash-sha1 str) : (-> String String)
413 (define in (open-input-string str))
414 (define digest (sha1 in))
415 (close-input-port in)
416 digest)
d718efc4 417 (build-path cache-object-dir (hash-sha1 (url->string uri))))
edadb804
SK
418
419(: url->cache-file-path-v2 (-> Url Path-String))
420(define (url->cache-file-path-v2 uri)
d718efc4
SK
421 (build-path cache-object-dir (uri-encode (url->string uri))))
422
0cb1ae9c
SK
423(define url->cache-object-path
424 url->cache-file-path-v2)
d3ac9e11 425
d718efc4
SK
426(define (url->cache-etag-path uri)
427 (build-path cache-dir "etags" (uri-encode (url->string uri))))
428
429(define (url->cache-lmod-path uri)
430 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
9c464d95 431
fee11be9 432(: uri-read-cached (-> Url (Option String)))
4214c0f3 433(define (uri-read-cached uri)
edadb804
SK
434 (define path-v1 (url->cache-file-path-v1 uri))
435 (define path-v2 (url->cache-file-path-v2 uri))
436 (when (file-exists? path-v1)
437 (rename-file-or-directory path-v1 path-v2 #t))
438 (if (file-exists? path-v2)
439 (file->string path-v2)
0e16a46c 440 (begin
b8b29fbb 441 (log-debug "Cache file not found for URI: ~a" (url->string uri))
fee11be9 442 #f)))
4214c0f3 443
b056019b
SK
444(: str->url (-> String (Option String)))
445(define (str->url s)
446 (with-handlers*
447 ([exn:fail? (λ (e) #f)])
448 (string->url s)))
a60c484e 449
0cb1ae9c
SK
450(: peer->str (-> Peer String))
451(define (peer->str peer)
452 (match-define (Peer n _ u c) peer)
453 (format "~a~a~a"
454 (if n (format "~a " n) "")
455 u
456 (if c (format " # ~a" c) "")))
457
458(: str->peer (-> String (Option Peer)))
dbc26280
SK
459(define (str->peer str)
460 (log-debug "Parsing peer string: ~v" str)
b056019b
SK
461 (match
462 (regexp-match
463 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
464 str)
465 [(list _wholething
466 _nick-with-space
467 nick
468 url
469 _comment-with-hash
470 comment)
471 (match (str->url url)
472 [#f
473 (log-error "Invalid URI in peer string: ~v" str)
474 #f]
e2840743
SK
475 [url
476 (Peer nick url (url->string url) comment)])]
b056019b 477 [_
b8b29fbb 478 (log-debug "Invalid peer string: ~v" str)
b056019b 479 #f]))
13c11724 480
b056019b
SK
481(module+ test
482 (check-equal?
483 (str->peer "foo http://bar/file.txt # some rando")
e2840743 484 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
b056019b
SK
485 (check-equal?
486 (str->peer "http://bar/file.txt # some rando")
e2840743 487 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
b056019b
SK
488 (check-equal?
489 (str->peer "http://bar/file.txt #")
e2840743 490 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
b056019b
SK
491 (check-equal?
492 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
e2840743 493 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
b056019b
SK
494 (check-equal?
495 (str->peer "http://bar/file.txt")
e2840743 496 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
497 (check-equal?
498 (str->peer "foo http://bar/file.txt")
e2840743 499 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
500 (check-equal?
501 (str->peer "foo bar # baz")
502 #f)
503 (check-equal?
504 (str->peer "foo bar://baz # quux")
e2840743 505 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
b056019b
SK
506 (check-equal?
507 (str->peer "foo bar//baz # quux")
508 #f))
9c464d95 509
98529d3d 510(: filter-comments (-> (Listof String) (Listof String)))
9c464d95
SK
511(define (filter-comments lines)
512 (filter-not (λ (line) (string-prefix? line "#")) lines))
513
e2840743 514(: str->peers (-> String (Setof Peer)))
dbc26280 515(define (str->peers str)
e2840743 516 (make-immutable-peers (filter-map str->peer (filter-comments (str->lines str)))))
9c464d95 517
e2840743 518(: peers->file (-> (Setof Peers) Path-String Void))
a60c484e
SK
519(define (peers->file peers path)
520 (display-lines-to-file
0cb1ae9c 521 (map peer->str
e2840743
SK
522 (sort (set->list peers)
523 (match-lambda**
524 [((Peer n1 _ _ _) (Peer n2 _ _ _))
525 (string<? (if n1 n1 "")
526 (if n2 n2 ""))])))
a60c484e
SK
527 path
528 #:exists 'replace))
529
e2840743 530(: file->peers (-> Path-String (Setof Peer)))
d0a0e073
SK
531(define (file->peers file-path)
532 (if (file-exists? file-path)
533 (str->peers (file->string file-path))
534 (begin
a60c484e 535 (log-warning "File does not exist: ~v" (path->string file-path))
e2840743 536 (make-immutable-peers))))
9c464d95 537
9c5e4499
SK
538(define re-rfc2822
539 #px"^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-2][0-9]):([0-6][0-9]):([0-6][0-9]) GMT")
540
541(: b->n (-> Bytes (Option Number)))
542(define (b->n b)
543 (string->number (bytes->string/utf-8 b)))
544
545(: mon->num (-> Bytes Natural))
546(define/match (mon->num mon)
547 [(#"Jan") 1]
548 [(#"Feb") 2]
549 [(#"Mar") 3]
550 [(#"Apr") 4]
551 [(#"May") 5]
552 [(#"Jun") 6]
553 [(#"Jul") 7]
554 [(#"Aug") 8]
555 [(#"Sep") 9]
556 [(#"Oct") 10]
557 [(#"Nov") 11]
558 [(#"Dec") 12])
559
560(: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
561(define (rfc2822->epoch timestamp)
562 (match (regexp-match re-rfc2822 timestamp)
563 [(list _ _ dd mo yyyy HH MM SS)
564 #:when (and dd mo yyyy HH MM SS)
565 (find-seconds (b->n SS)
566 (b->n MM)
567 (b->n HH)
568 (b->n dd)
569 (mon->num mo)
570 (b->n yyyy)
571 #f)]
572 [_
573 #f]))
574
d718efc4
SK
575(: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
576(define (header-get headers name)
577 (match (filter-map (curry extract-field name) headers)
578 [(list val) val]
579 [_ #f]))
580
7fd20778
SK
581(: uri-download-from-port
582 (-> Url (Listof (U Bytes String)) Input-Port
583 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
584(define (uri-download-from-port u headers body-input)
585 (define u-str (url->string u))
586 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
d718efc4
SK
587 (define cached-object-path (url->cache-object-path u))
588 (define cached-etag-path (url->cache-etag-path u))
589 (define cached-lmod-path (url->cache-lmod-path u))
7fd20778
SK
590 (define etag (header-get headers #"ETag"))
591 (define lmod (header-get headers #"Last-Modified"))
592 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
593 (define lmod-prev (if (file-exists? cached-lmod-path)
594 (rfc2822->epoch (file->bytes cached-lmod-path))
595 #f))
596 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
597 (define cached?
598 (or (and etag
599 (file-exists? cached-etag-path)
600 (bytes=? etag (file->bytes cached-etag-path))
601 (begin
602 (log-debug "ETags match, skipping the rest of ~v" u-str)
603 #t))
604 (and lmod-curr
605 lmod-prev
606 (<= lmod-curr lmod-prev)
607 (begin
608 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
609 #t))))
610 (if (not cached?)
68bbd2e9
SK
611 (begin
612 (log-debug
613 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
614 u-str etag lmod)
615 (make-parent-directory* cached-object-path)
616 (make-parent-directory* cached-etag-path)
617 (make-parent-directory* cached-lmod-path)
618 (call-with-output-file cached-object-path
619 (curry copy-port body-input)
620 #:exists 'replace)
621 (when etag
622 (display-to-file etag cached-etag-path #:exists 'replace))
623 (when lmod
624 (display-to-file lmod cached-lmod-path #:exists 'replace))
625 'downloaded-new)
626 'skipped-cached))
7fd20778
SK
627
628(: uri-download
629 (-> Positive-Float Url
630 (Result (U 'skipped-cached 'downloaded-new)
631 Any))) ; TODO Maybe more-precise error type?
632(define (uri-download timeout u)
f65d6338 633 (define u-str (url->string u))
f65d6338
SK
634 (define timeout-chan (make-channel))
635 (define result-chan (make-channel))
636 (define timeout-thread
637 (thread (λ ()
638 ; Doing this instead of sync/timeout to distinguish error values,
639 ; rather than just have #f to work with.
640 (sleep timeout)
7fd20778 641 (channel-put timeout-chan '(error . timeout)))))
f65d6338
SK
642 (define result-thread
643 (thread (λ ()
644 ; XXX We timeout getting a response, but body download could
645 ; also take a long time and we might want to time that out as
646 ; well, but then we may end-up with partially downloaded
647 ; objects. But that could happen anyway if the server drops the
648 ; connection for whatever reason.
649 ;
650 ; Maybe that is OK once we start treating the
651 ; downloaded object as an addition to the stored set of
652 ; messages, rather than the final set of messages.
653
654 ; TODO message db
655 ; - 1st try can just be an in-memory set that gets written-to
656 ; and read-from disk as a whole.
657 (define result
658 (with-handlers
7fd20778
SK
659 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
660 ([exn:fail:network?
661 (λ (e) `(error . (net-error . ,e)))]
662 [exn?
663 (λ (e) `(error . (other . ,e)))])
f65d6338
SK
664 (define-values (status-line headers body-input)
665 (http-sendrecv/url
666 u
7296ed94 667 #:headers (list (format "User-Agent: ~a" user-agent-str))))
7fd20778 668 `(ok . ,(Resp status-line headers body-input))))
f65d6338
SK
669 (channel-put result-chan result))))
670 (define result
671 (sync timeout-chan
672 result-chan))
673 (kill-thread result-thread)
674 (kill-thread timeout-thread)
675 (match result
7fd20778
SK
676 [(cons 'error _)
677 result]
f65d6338
SK
678 [(cons 'ok (Resp status-line headers body-input))
679 (log-debug "headers: ~v" headers)
680 (log-debug "status-line: ~v" status-line)
681 (define status
682 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
683 (log-debug "status: ~v" status)
7fd20778
SK
684 ; TODO Handle redirects. Should be within same timeout as req and body.
685 (let ([result
686 (match status
687 [200
688 `(ok . ,(uri-download-from-port u headers body-input))]
689 [_
690 `(error . (http . ,status))])])
691 (close-input-port body-input)
692 result)]))
4764ff89 693
98529d3d 694(: timeline-print (-> Out-Format (Listof Msg) Void))
b201e854 695(define (timeline-print out-format timeline)
0cb1ae9c
SK
696 (match timeline
697 ['()
698 (void)]
699 [(cons first-msg _)
700 (void (foldl (match-lambda**
701 [((and m (Msg _ _ from _ _)) (cons prev-from i))
702 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
703 (msg-print out-format i m)
704 (cons from i))])
705 (cons (Msg-from first-msg) 0)
706 timeline))]))
4764ff89 707
dbc26280 708(: peer->msgs (-> Peer (Listof Msg)))
b056019b 709(define (peer->msgs peer)
e2840743
SK
710 (match-define (Peer nick uri uri-str _) peer)
711 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
fee11be9 712 (define msgs-data (uri-read-cached uri))
4a23fd99 713 ; TODO Expire cache
fee11be9 714 (if msgs-data
0cb1ae9c 715 (str->msgs peer msgs-data)
fee11be9 716 '()))
4214c0f3 717
7fd20778
SK
718(: peer-download
719 (-> Positive-Float Peer
720 (Result (U 'skipped-cached 'downloaded-new)
721 Any)))
f65d6338 722(define (peer-download timeout peer)
e2840743 723 (match-define (Peer nick uri u _) peer)
7fd20778
SK
724 (log-info "Download BEGIN URL:~a" u)
725 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
f65d6338 726 (time-apply uri-download (list timeout uri)))
7fd20778
SK
727 (define result (car results))
728 (log-info "Download END in ~a seconds, URL:~a, result:~s"
729 (/ tm-real-ms 1000.0)
730 u
731 result)
732 result)
4214c0f3 733
e2840743 734(: timeline-download (-> Integer Positive-Float (Setof Peer) Void))
f65d6338 735(define (timeline-download num-workers timeout peers)
7fd20778
SK
736 (define results
737 (concurrent-filter-map num-workers
738 (λ (p) (cons p (peer-download timeout p)))
e2840743 739 (set->list peers)))
d54812ea
SK
740 (define peers-ok
741 (filter-map (match-lambda
742 [(cons p (cons 'ok _)) p]
743 [(cons _ (cons 'error e)) #f])
744 results))
745 (define peers-err
746 (filter-map (match-lambda
747 [(cons _ (cons 'ok _))
748 #f]
749 [(cons p (cons 'error e))
750 (struct-copy Peer p [comment (format "~s" e)])])
751 results))
7fd20778 752 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
7fd20778 753 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
9a6a9f9a 754
50f0609d 755(: peers->timeline (-> (Setof Peer) (Listof Msg)))
a60c484e 756(define (peers->timeline peers)
e2840743 757 (append* (filter-map peer->msgs (set->list peers))))
a60c484e 758
e2840743 759(: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
a60c484e 760(define (timeline-sort msgs order)
a4899240
SK
761 (define cmp (match order
762 ['old->new <]
763 ['new->old >]))
a60c484e
SK
764 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
765 (Msg-ts-epoch b)))))
4764ff89 766
e2840743 767(: paths->peers (-> (Listof String) (Setof Peer)))
d0a0e073
SK
768(define (paths->peers paths)
769 (let* ([paths (match paths
770 ['()
771 (let ([peer-refs-file (build-path tt-home-dir "peers")])
772 (log-debug
773 "No peer ref file paths provided, defaulting to ~v"
774 (path->string peer-refs-file))
775 (list peer-refs-file))]
776 [paths
777 (log-debug "Peer ref file paths provided: ~v" paths)
778 (map string->path paths)])]
50f0609d 779 [peers (apply peers-union (map file->peers paths))])
e2840743
SK
780 (log-info "Read-in ~a peers." (set-count peers))
781 peers))
d0a0e073 782
50f0609d
SK
783(: cache-filename->peer (-> Path-String (Option Peer)))
784(define (cache-filename->peer filename)
785 (define nick #f) ; TODO Look it up in the nick-db when it exists.
786 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
787 (match (str->url url-str)
788 [#f #f]
789 [url (Peer nick url url-str #f)]))
790
791(: peers-cached (-> (Setof Peer)))
792(define (peers-cached)
793 ; TODO Expire cache?
794 (make-immutable-peers
795 (filter-map cache-filename->peer
796 (directory-list cache-object-dir))))
797
798(: peers-mentioned (-> (Listof Msg) (Setof Peer)))
799(define (peers-mentioned msgs)
e2840743 800 (make-immutable-peers (append* (map Msg-mentions msgs))))
d3ac9e11 801
56de6228
SK
802(: log-writer-stop (-> Thread Void))
803(define (log-writer-stop log-writer)
804 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
805 (thread-wait log-writer))
806
0d3f753c
SK
807(: log-writer-start (-> Log-Level Thread))
808(define (log-writer-start level)
56de6228
SK
809 (let* ([logger
810 (make-logger #f #f level #f)]
811 [log-receiver
812 (make-log-receiver logger level)]
813 [log-writer
814 (thread
815 (λ ()
816 (parameterize
817 ([date-display-format 'iso-8601])
818 (let loop ()
819 (match-define (vector level msg _ topic) (sync log-receiver))
820 (unless (equal? topic 'stop)
821 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
822 (loop))))))])
823 (current-logger logger)
824 log-writer))
01e4c499 825
e8856d5c
SK
826(: crawl (-> Void))
827(define (crawl)
e2840743 828 (let* ([peers-all-file
e8856d5c
SK
829 (build-path tt-home-dir "peers-all")]
830 [peers-mentioned-file
831 (build-path tt-home-dir "peers-mentioned")]
832 [peers-parsed-file
833 (build-path tt-home-dir "peers-parsed")]
50f0609d
SK
834 [peers-cached-file
835 (build-path tt-home-dir "peers-cached")]
836 [peers-cached
837 (peers-cached)]
838 [cached-timeline
839 (peers->timeline peers-cached)]
e8856d5c 840 [peers-mentioned-curr
50f0609d 841 (peers-mentioned cached-timeline)]
e8856d5c
SK
842 [peers-mentioned-prev
843 (file->peers peers-mentioned-file)]
844 [peers-mentioned
50f0609d
SK
845 (peers-union peers-mentioned-prev
846 peers-mentioned-curr)]
e8856d5c
SK
847 [peers-all-prev
848 (file->peers peers-all-file)]
849 [peers-all
50f0609d
SK
850 (peers-union peers-mentioned
851 peers-all-prev
852 peers-cached)]
e8856d5c 853 [peers-discovered
e2840743
SK
854 (set-subtract peers-all
855 peers-all-prev)]
e8856d5c 856 [peers-parsed
e2840743 857 (for/set ([p peers-all] #:when (> (length (peer->msgs p)) 0)) p)])
e8856d5c 858 ; TODO Deeper de-duping
50f0609d 859 (log-info "Known peers cached ~a" (set-count peers-cached))
e2840743
SK
860 (log-info "Known peers mentioned: ~a" (set-count peers-mentioned))
861 (log-info "Known peers parsed ~a" (set-count peers-parsed))
862 (log-info "Known peers total: ~a" (set-count peers-all))
e8856d5c
SK
863 (log-info "Discovered ~a new peers:~n~a"
864 (set-count peers-discovered)
865 (pretty-format (map
e2840743
SK
866 (match-lambda
867 [(Peer n _ u c) (list n u c)])
e8856d5c 868 (set->list peers-discovered))))
50f0609d
SK
869 (peers->file peers-cached
870 peers-cached-file)
e8856d5c
SK
871 (peers->file peers-mentioned
872 peers-mentioned-file)
873 (peers->file peers-parsed
874 peers-parsed-file)
875 (peers->file peers-all
876 peers-all-file)))
877
878(: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
879(define (read file-paths ts-min ts-max order out-format)
880 (let* ([peers
881 (paths->peers file-paths)]
882 [msgs
883 (timeline-sort (peers->timeline peers) order)]
884 [include?
885 (λ (m)
886 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
887 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
888 (timeline-print out-format (filter include? msgs))))
889
890(: upload (-> Void))
891(define (upload)
892 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
893 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
894 (exit 0)
895 (exit 1)))
896
897(: download (-> (Listof String) Positive-Integer Positive-Float Void))
898(define (download file-paths num-workers timeout)
899 (let ([peers (paths->peers file-paths)])
900 (define-values (_res _cpu real-ms _gc)
901 (time-apply timeline-download (list num-workers timeout peers)))
902 (log-info "Downloaded timelines from ~a peers in ~a seconds."
e2840743 903 (set-count peers)
e8856d5c
SK
904 (/ real-ms 1000.0))))
905
906(: dispatch (-> String Void))
907(define (dispatch command)
908 (match command
909 [(or "d" "download")
910 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
911 ; started noticing significant slowdowns. Reducing to 5 seems to help.
912 (let ([num-workers 5]
913 [timeout 10.0])
914 (command-line
915 #:program "tt download"
916 #:once-each
917 [("-j" "--jobs")
918 njobs "Number of concurrent jobs."
919 (set! num-workers (string->number njobs))]
920 [("-t" "--timeout")
921 seconds "Timeout seconds per request."
922 (set! timeout (string->number seconds))]
923 #:args file-paths
924 (download file-paths num-workers timeout)))]
925 [(or "u" "upload")
926 (command-line
927 #:program "tt upload" #:args () (upload))]
928 [(or "r" "read")
929 (let ([out-format 'multi-line]
930 [order 'old->new]
931 [ts-min #f]
932 [ts-max #f])
933 (command-line
934 #:program "tt read"
935 #:once-each
936 [("-r" "--rev")
937 "Reverse displayed timeline order."
938 (set! order 'new->old)]
939 [("-m" "--min")
940 m "Earliest time to display (ignore anything before it)."
941 (set! ts-min (rfc3339->epoch m))]
942 [("-x" "--max")
943 x "Latest time to display (ignore anything after it)."
944 (set! ts-max (rfc3339->epoch x))]
945 #:once-any
946 [("-s" "--short")
947 "Short output format"
948 (set! out-format 'single-line)]
949 [("-l" "--long")
950 "Long output format"
951 (set! out-format 'multi-line)]
952 #:args file-paths
953 (read file-paths ts-min ts-max order out-format)))]
954 [(or "c" "crawl")
955 (command-line
956 #:program "tt crawl" #:args () (crawl))]
957 [command
958 (eprintf "Error: invalid command: ~v\n" command)
959 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
960 (exit 1)]))
961
24c6a76b 962(module+ main
24f1f64b 963 (let ([log-level 'info])
c562bea3 964 (command-line
24f1f64b
SK
965 #:program
966 "tt"
c562bea3 967 #:once-each
01e4c499
SK
968 [("-d" "--debug")
969 "Enable debug log level."
970 (set! log-level 'debug)]
24f1f64b
SK
971 #:help-labels
972 ""
973 "and <command> is one of"
a60c484e 974 "r, read : Read the timeline (offline operation)."
4214c0f3 975 "d, download : Download the timeline."
edadb804 976 ; TODO Add path dynamically
0868c39a 977 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
a60c484e 978 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
24f1f64b
SK
979 ""
980 #:args (command . args)
0d3f753c 981 (define log-writer (log-writer-start log-level))
4214c0f3 982 (current-command-line-arguments (list->vector args))
7296ed94 983 (set-user-agent-str (build-path tt-home-dir "me"))
e8856d5c
SK
984 ; TODO dispatch should return status with which we should exit after cleanups
985 (dispatch command)
0d3f753c 986 (log-writer-stop log-writer))))
This page took 0.240558 seconds and 4 git commands to generate.