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