Revert to list as a primary peers container
[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 [(and (not n1) (not n2)) p1]
174 [(and n1 n2 ) p1]
175 [(and n1 (not n2)) p1]
176 [(and (not n1) n2) p2]
177 [else
178 (raise 'impossible)])])
179 (merge (cons p ps)))]))
180 (sort (map merge (hash-values groups))
181 (match-lambda**
182 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
183
184 (module+ test
185 (let* ([u1 "http://foo/bar"]
186 [u2 "http://baz/quux"]
187 [p1 (Peer #f (string->url u1) u1 #f)]
188 [p2 (Peer "a" (string->url u1) u1 #f)]
189 [p3 (Peer "b" (string->url u2) u2 #f)]
190 [s1 (list p1)]
191 [s2 (list p2 p3)])
192 (check-equal? (list p3 p2) (peers-merge s1 s2))
193 (check-equal? (list p3 p2) (peers-merge s2 s1))))
194
195 (: tt-home-dir Path-String)
196 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
197
198 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
199 (define (concurrent-filter-map num-workers f xs)
200 ; TODO preserve order of elements OR communicate that reorder is expected
201 ; TODO switch from mailboxes to channels
202 (define (make-worker id f)
203 (define parent (current-thread))
204 (λ ()
205 (define self : Thread (current-thread))
206 (: work (∀ (α) (-> α)))
207 (define (work)
208 (thread-send parent (cons 'next self))
209 (match (thread-receive)
210 ['done (thread-send parent (cons 'exit id))]
211 [(cons 'unit x) (begin
212 (define y (f x))
213 (when y (thread-send parent (cons 'result y)))
214 (work))]))
215 (work)))
216 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
217 (define (dispatch ws xs ys)
218 (if (empty? ws)
219 ys
220 (match (thread-receive)
221 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
222 [(cons 'result y) (dispatch ws xs (cons y ys))]
223 [(cons 'next thd) (match xs
224 ['() (begin
225 (thread-send thd 'done)
226 (dispatch ws xs ys))]
227 [(cons x xs) (begin
228 (thread-send thd (cons 'unit x))
229 (dispatch ws xs ys))])])))
230 (define workers (range num-workers))
231 (define threads (map (λ (id) (thread (make-worker id f))) workers))
232 (define results (dispatch workers xs '()))
233 (for-each thread-wait threads)
234 results)
235
236 (module+ test
237 (let* ([f (λ (x) (if (even? x) x #f))]
238 [xs (range 11)]
239 [actual (sort (concurrent-filter-map 10 f xs) <)]
240 [expected (sort ( filter-map f xs) <)])
241 (check-equal? actual expected "concurrent-filter-map")))
242
243 (: msg-print (-> Out-Format Integer Msg Void))
244 (define msg-print
245 (let* ([colors (vector 36 33)]
246 [n (vector-length colors)])
247 (λ (out-format color-i msg)
248 (let ([color (vector-ref colors (modulo color-i n))]
249 [nick (Peer-nick (Msg-from msg))]
250 [uri (Peer-uri-str (Msg-from msg))]
251 [text (Msg-text msg)])
252 (match out-format
253 ['single-line
254 (let ([nick (if nick nick uri)])
255 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
256 (parameterize
257 ([date-display-format 'iso-8601])
258 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
259 nick color text))]
260 ['multi-line
261 (let ([nick (if nick (string-append nick " ") "")])
262 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
263 (parameterize
264 ([date-display-format 'rfc2822])
265 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
266 (Msg-ts-orig msg)
267 nick uri color text))])))))
268
269 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
270 (define rfc3339->epoch
271 (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}))?$")])
272 (λ (ts)
273 (match (regexp-match re ts)
274 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
275 (let*
276 ([tz-offset
277 (match* (tz-whole tz-sign tz-HH tz-MM)
278 [("Z" #f #f #f)
279 0]
280 [(_ (or "-" "+") (? identity h) (? identity m))
281 (let ([h (string->number h)]
282 [m (string->number m)]
283 ; Reverse to get back to UTC:
284 [op (match tz-sign ["+" -] ["-" +])])
285 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
286 [(a b c d)
287 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
288 0])]
289 [ts-orig ts]
290 [local-time? #f]
291 [ts-epoch (find-seconds (if SS (string->number SS) 0)
292 (string->number MM)
293 (string->number HH)
294 (string->number dd)
295 (string->number mm)
296 (string->number yyyy)
297 local-time?)])
298 (+ ts-epoch tz-offset))]
299 [_
300 (log-debug "Invalid timestamp: ~v" ts)
301 #f]))))
302
303 (: str->msg (-> Peer String (Option Msg)))
304 (define str->msg
305 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
306 (λ (from str)
307 (define from-str (peer->str from))
308 (define str-head (substring str 0 (min 100 (string-length str))))
309 (with-handlers*
310 ([exn:fail?
311 (λ (e)
312 (log-debug
313 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
314 str-head from-str e)
315 #f)])
316 (match (regexp-match re str)
317 [(list _wholething ts-orig text)
318 (let ([ts-epoch (rfc3339->epoch ts-orig)])
319 (if ts-epoch
320 (let ([mentions
321 (filter-map
322 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
323 [(list _wholething nick-uri)
324 (str->peer nick-uri)]))
325 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
326 (Msg ts-epoch ts-orig from text mentions))
327 (begin
328 (log-debug
329 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
330 from-str str-head)
331 #f)))]
332 [_
333 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
334 #f])))))
335
336 (module+ test
337 ; TODO Test for when missing-nick case
338 (let* ([tzs (for*/list ([d '("-" "+")]
339 [h '("5" "05")]
340 [m '("00" ":00" "57" ":57")])
341 (string-append d h m))]
342 [tzs (list* "" "Z" tzs)])
343 (for* ([n '("fake-nick")]
344 [u '("http://fake-uri")]
345 [p (list (Peer n (string->url u) u #f))]
346 [s '("" ":10")]
347 [f '("" ".1337")]
348 [z tzs]
349 [sep (list "\t" " ")]
350 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
351 (let* ([ts (string-append "2020-11-18T22:22"
352 (if (non-empty-string? s) s ":00")
353 z)]
354 [m (str->msg p (string-append ts sep txt))])
355 (check-not-false m)
356 (check-equal? (Msg-from m) p)
357 (check-equal? (Msg-text m) txt)
358 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
359 )))
360
361 (let* ([ts "2020-11-18T22:22:09-0500"]
362 [tab " "]
363 [text "Lorem ipsum"]
364 [nick "foo"]
365 [uri "http://bar/"]
366 [peer (Peer nick (string->url uri) uri #f)]
367 [actual (str->msg peer (string-append ts tab text))]
368 [expected (Msg 1605756129 ts peer text '())])
369 (check-equal?
370 (Msg-ts-epoch actual)
371 (Msg-ts-epoch expected)
372 "str->msg ts-epoch")
373 (check-equal?
374 (Msg-ts-orig actual)
375 (Msg-ts-orig expected)
376 "str->msg ts-orig")
377 (check-equal?
378 (Peer-nick (Msg-from actual))
379 (Peer-nick (Msg-from expected))
380 "str->msg nick")
381 (check-equal?
382 (Peer-uri (Msg-from actual))
383 (Peer-uri (Msg-from expected))
384 "str->msg uri")
385 (check-equal?
386 (Peer-uri-str (Msg-from actual))
387 (Peer-uri-str (Msg-from expected))
388 "str->msg uri-str")
389 (check-equal?
390 (Msg-text actual)
391 (Msg-text expected)
392 "str->msg text")))
393
394 (: str->lines (-> String (Listof String)))
395 (define (str->lines str)
396 (string-split str (regexp "[\r\n]+")))
397
398 (module+ test
399 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
400
401 (: str->msgs (-> Peer String (Listof Msg)))
402 (define (str->msgs peer str)
403 (filter-map (λ (line) (str->msg peer line))
404 (filter-comments (str->lines str))))
405
406 (: cache-dir Path-String)
407 (define cache-dir (build-path tt-home-dir "cache"))
408
409 (define cache-object-dir (build-path cache-dir "objects"))
410
411 (: url->cache-file-path-v1 (-> Url Path-String))
412 (define (url->cache-file-path-v1 uri)
413 (define (hash-sha1 str) : (-> String String)
414 (define in (open-input-string str))
415 (define digest (sha1 in))
416 (close-input-port in)
417 digest)
418 (build-path cache-object-dir (hash-sha1 (url->string uri))))
419
420 (: url->cache-file-path-v2 (-> Url Path-String))
421 (define (url->cache-file-path-v2 uri)
422 (build-path cache-object-dir (uri-encode (url->string uri))))
423
424 (define url->cache-object-path
425 url->cache-file-path-v2)
426
427 (define (url->cache-etag-path uri)
428 (build-path cache-dir "etags" (uri-encode (url->string uri))))
429
430 (define (url->cache-lmod-path uri)
431 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
432
433 (: uri-read-cached (-> Url (Option String)))
434 (define (uri-read-cached uri)
435 (define path-v1 (url->cache-file-path-v1 uri))
436 (define path-v2 (url->cache-file-path-v2 uri))
437 (when (file-exists? path-v1)
438 (rename-file-or-directory path-v1 path-v2 #t))
439 (if (file-exists? path-v2)
440 (file->string path-v2)
441 (begin
442 (log-debug "Cache file not found for URI: ~a" (url->string uri))
443 #f)))
444
445 (: str->url (-> String (Option String)))
446 (define (str->url s)
447 (with-handlers*
448 ([exn:fail? (λ (e) #f)])
449 (string->url s)))
450
451 (: peer->str (-> Peer String))
452 (define (peer->str peer)
453 (match-define (Peer n _ u c) peer)
454 (format "~a~a~a"
455 (if n (format "~a " n) "")
456 u
457 (if c (format " # ~a" c) "")))
458
459 (: str->peer (-> String (Option Peer)))
460 (define (str->peer str)
461 (log-debug "Parsing peer string: ~v" str)
462 (match
463 (regexp-match
464 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
465 str)
466 [(list _wholething
467 _nick-with-space
468 nick
469 url
470 _comment-with-hash
471 comment)
472 (match (str->url url)
473 [#f
474 (log-error "Invalid URI in peer string: ~v" str)
475 #f]
476 [url
477 (Peer nick url (url->string url) comment)])]
478 [_
479 (log-debug "Invalid peer string: ~v" str)
480 #f]))
481
482 (module+ test
483 (check-equal?
484 (str->peer "foo http://bar/file.txt # some rando")
485 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
486 (check-equal?
487 (str->peer "http://bar/file.txt # some rando")
488 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
489 (check-equal?
490 (str->peer "http://bar/file.txt #")
491 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
492 (check-equal?
493 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
494 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
495 (check-equal?
496 (str->peer "http://bar/file.txt")
497 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
498 (check-equal?
499 (str->peer "foo http://bar/file.txt")
500 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
501 (check-equal?
502 (str->peer "foo bar # baz")
503 #f)
504 (check-equal?
505 (str->peer "foo bar://baz # quux")
506 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
507 (check-equal?
508 (str->peer "foo bar//baz # quux")
509 #f))
510
511 (: filter-comments (-> (Listof String) (Listof String)))
512 (define (filter-comments lines)
513 (filter-not (λ (line) (string-prefix? line "#")) lines))
514
515 (: str->peers (-> String (Listof Peer)))
516 (define (str->peers str)
517 (filter-map str->peer (filter-comments (str->lines str))))
518
519 (: peers->file (-> (Listof Peers) Path-String Void))
520 (define (peers->file peers path)
521 (display-lines-to-file
522 (map peer->str
523 (sort peers
524 (match-lambda**
525 [((Peer n1 _ _ _) (Peer n2 _ _ _))
526 (string<? (if n1 n1 "")
527 (if n2 n2 ""))])))
528 path
529 #:exists 'replace))
530
531 (: file->peers (-> Path-String (Listof Peer)))
532 (define (file->peers file-path)
533 (if (file-exists? file-path)
534 (str->peers (file->string file-path))
535 (begin
536 (log-warning "File does not exist: ~v" (path->string file-path))
537 '())))
538
539 (define re-rfc2822
540 #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")
541
542 (: b->n (-> Bytes (Option Number)))
543 (define (b->n b)
544 (string->number (bytes->string/utf-8 b)))
545
546 (: mon->num (-> Bytes Natural))
547 (define/match (mon->num mon)
548 [(#"Jan") 1]
549 [(#"Feb") 2]
550 [(#"Mar") 3]
551 [(#"Apr") 4]
552 [(#"May") 5]
553 [(#"Jun") 6]
554 [(#"Jul") 7]
555 [(#"Aug") 8]
556 [(#"Sep") 9]
557 [(#"Oct") 10]
558 [(#"Nov") 11]
559 [(#"Dec") 12])
560
561 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
562 (define (rfc2822->epoch timestamp)
563 (match (regexp-match re-rfc2822 timestamp)
564 [(list _ _ dd mo yyyy HH MM SS)
565 #:when (and dd mo yyyy HH MM SS)
566 (find-seconds (b->n SS)
567 (b->n MM)
568 (b->n HH)
569 (b->n dd)
570 (mon->num mo)
571 (b->n yyyy)
572 #f)]
573 [_
574 #f]))
575
576 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
577 (define (header-get headers name)
578 (match (filter-map (curry extract-field name) headers)
579 [(list val) val]
580 [_ #f]))
581
582 (: uri-download-from-port
583 (-> Url (Listof (U Bytes String)) Input-Port
584 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
585 (define (uri-download-from-port u headers body-input)
586 (define u-str (url->string u))
587 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
588 (define cached-object-path (url->cache-object-path u))
589 (define cached-etag-path (url->cache-etag-path u))
590 (define cached-lmod-path (url->cache-lmod-path u))
591 (define etag (header-get headers #"ETag"))
592 (define lmod (header-get headers #"Last-Modified"))
593 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
594 (define lmod-prev (if (file-exists? cached-lmod-path)
595 (rfc2822->epoch (file->bytes cached-lmod-path))
596 #f))
597 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
598 (define cached?
599 (or (and etag
600 (file-exists? cached-etag-path)
601 (bytes=? etag (file->bytes cached-etag-path))
602 (begin
603 (log-debug "ETags match, skipping the rest of ~v" u-str)
604 #t))
605 (and lmod-curr
606 lmod-prev
607 (<= lmod-curr lmod-prev)
608 (begin
609 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
610 #t))))
611 (if (not cached?)
612 (begin
613 (log-debug
614 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
615 u-str etag lmod)
616 (make-parent-directory* cached-object-path)
617 (make-parent-directory* cached-etag-path)
618 (make-parent-directory* cached-lmod-path)
619 (call-with-output-file cached-object-path
620 (curry copy-port body-input)
621 #:exists 'replace)
622 (when etag
623 (display-to-file etag cached-etag-path #:exists 'replace))
624 (when lmod
625 (display-to-file lmod cached-lmod-path #:exists 'replace))
626 'downloaded-new)
627 'skipped-cached))
628
629 (: uri-download
630 (-> Positive-Float Url
631 (Result (U 'skipped-cached 'downloaded-new)
632 Any))) ; TODO Maybe more-precise error type?
633 (define (uri-download timeout u)
634 (define u-str (url->string u))
635 (define timeout-chan (make-channel))
636 (define result-chan (make-channel))
637 (define timeout-thread
638 (thread (λ ()
639 ; Doing this instead of sync/timeout to distinguish error values,
640 ; rather than just have #f to work with.
641 (sleep timeout)
642 (channel-put timeout-chan '(error . timeout)))))
643 (define result-thread
644 (thread (λ ()
645 ; XXX We timeout getting a response, but body download could
646 ; also take a long time and we might want to time that out as
647 ; well, but then we may end-up with partially downloaded
648 ; objects. But that could happen anyway if the server drops the
649 ; connection for whatever reason.
650 ;
651 ; Maybe that is OK once we start treating the
652 ; downloaded object as an addition to the stored set of
653 ; messages, rather than the final set of messages.
654
655 ; TODO message db
656 ; - 1st try can just be an in-memory set that gets written-to
657 ; and read-from disk as a whole.
658 (define result
659 (with-handlers
660 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
661 ([exn:fail:network?
662 (λ (e) `(error . (net-error . ,e)))]
663 [exn?
664 (λ (e) `(error . (other . ,e)))])
665 (define-values (status-line headers body-input)
666 (http-sendrecv/url
667 u
668 #:headers (list (format "User-Agent: ~a" user-agent-str))))
669 `(ok . ,(Resp status-line headers body-input))))
670 (channel-put result-chan result))))
671 (define result
672 (sync timeout-chan
673 result-chan))
674 (kill-thread result-thread)
675 (kill-thread timeout-thread)
676 (match result
677 [(cons 'error _)
678 result]
679 [(cons 'ok (Resp status-line headers body-input))
680 (log-debug "headers: ~v" headers)
681 (log-debug "status-line: ~v" status-line)
682 (define status
683 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
684 (log-debug "status: ~v" status)
685 ; TODO Handle redirects. Should be within same timeout as req and body.
686 (let ([result
687 (match status
688 [200
689 `(ok . ,(uri-download-from-port u headers body-input))]
690 [_
691 `(error . (http . ,status))])])
692 (close-input-port body-input)
693 result)]))
694
695 (: timeline-print (-> Out-Format (Listof Msg) Void))
696 (define (timeline-print out-format timeline)
697 (match timeline
698 ['()
699 (void)]
700 [(cons first-msg _)
701 (void (foldl (match-lambda**
702 [((and m (Msg _ _ from _ _)) (cons prev-from i))
703 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
704 (msg-print out-format i m)
705 (cons from i))])
706 (cons (Msg-from first-msg) 0)
707 timeline))]))
708
709 (: peer->msgs (-> Peer (Listof Msg)))
710 (define (peer->msgs peer)
711 (match-define (Peer nick uri uri-str _) peer)
712 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
713 (define msgs-data (uri-read-cached uri))
714 ; TODO Expire cache
715 (if msgs-data
716 (str->msgs peer msgs-data)
717 '()))
718
719 (: peer-download
720 (-> Positive-Float Peer
721 (Result (U 'skipped-cached 'downloaded-new)
722 Any)))
723 (define (peer-download timeout peer)
724 (match-define (Peer nick uri u _) peer)
725 (log-info "Download BEGIN URL:~a" u)
726 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
727 (time-apply uri-download (list timeout uri)))
728 (define result (car results))
729 (log-info "Download END in ~a seconds, URL:~a, result:~s"
730 (/ tm-real-ms 1000.0)
731 u
732 result)
733 result)
734
735 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
736 (define (timeline-download num-workers timeout peers)
737 (define results
738 (concurrent-filter-map num-workers
739 (λ (p) (cons p (peer-download timeout p)))
740 peers))
741 (define peers-ok
742 (filter-map (match-lambda
743 [(cons p (cons 'ok _)) p]
744 [(cons _ (cons 'error e)) #f])
745 results))
746 (define peers-err
747 (filter-map (match-lambda
748 [(cons _ (cons 'ok _))
749 #f]
750 [(cons p (cons 'error e))
751 (struct-copy Peer p [comment (format "~s" e)])])
752 results))
753 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
754 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
755
756 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
757 (define (peers->timeline peers)
758 (append* (filter-map peer->msgs peers)))
759
760 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
761 (define (timeline-sort msgs order)
762 (define cmp (match order
763 ['old->new <]
764 ['new->old >]))
765 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
766 (Msg-ts-epoch b)))))
767
768 (: paths->peers (-> (Listof String) (Listof Peer)))
769 (define (paths->peers paths)
770 (let* ([paths (match paths
771 ['()
772 (let ([peer-refs-file (build-path tt-home-dir "peers")])
773 (log-debug
774 "No peer ref file paths provided, defaulting to ~v"
775 (path->string peer-refs-file))
776 (list peer-refs-file))]
777 [paths
778 (log-debug "Peer ref file paths provided: ~v" paths)
779 (map string->path paths)])]
780 [peers (apply peers-merge (map file->peers paths))])
781 (log-info "Read-in ~a peers." (length peers))
782 peers))
783
784 (: cache-filename->peer (-> Path-String (Option Peer)))
785 (define (cache-filename->peer filename)
786 (define nick #f) ; TODO Look it up in the nick-db when it exists.
787 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
788 (match (str->url url-str)
789 [#f #f]
790 [url (Peer nick url url-str #f)]))
791
792 (: peers-cached (-> (Listof Peer)))
793 (define (peers-cached)
794 ; TODO Expire cache?
795 (filter-map cache-filename->peer (directory-list cache-object-dir)))
796
797 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
798 (define (peers-mentioned msgs)
799 (append* (map Msg-mentions msgs)))
800
801 (: log-writer-stop (-> Thread Void))
802 (define (log-writer-stop log-writer)
803 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
804 (thread-wait log-writer))
805
806 (: log-writer-start (-> Log-Level Thread))
807 (define (log-writer-start level)
808 (let* ([logger
809 (make-logger #f #f level #f)]
810 [log-receiver
811 (make-log-receiver logger level)]
812 [log-writer
813 (thread
814 (λ ()
815 (parameterize
816 ([date-display-format 'iso-8601])
817 (let loop ()
818 (match-define (vector level msg _ topic) (sync log-receiver))
819 (unless (equal? topic 'stop)
820 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
821 (loop))))))])
822 (current-logger logger)
823 log-writer))
824
825 (: crawl (-> Void))
826 (define (crawl)
827 ; TODO Test the non-io parts of crawling
828 (let* ([peers-all-file
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")]
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)]
840 [peers-mentioned-curr
841 (peers-mentioned cached-timeline)]
842 [peers-mentioned-prev
843 (file->peers peers-mentioned-file)]
844 [peers-mentioned
845 (peers-merge peers-mentioned-prev
846 peers-mentioned-curr)]
847 [peers-all-prev
848 (file->peers peers-all-file)]
849 [peers-all
850 (peers-merge peers-mentioned
851 peers-all-prev
852 peers-cached)]
853 [peers-discovered
854 (set->list (set-subtract (make-immutable-peers peers-all)
855 (make-immutable-peers peers-all-prev)))]
856 [peers-parsed
857 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
858 ; TODO Deeper de-duping
859 (log-info "Known peers cached ~a" (length peers-cached))
860 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
861 (log-info "Known peers parsed ~a" (length peers-parsed))
862 (log-info "Known peers total: ~a" (length peers-all))
863 (log-info "Discovered ~a new peers:~n~a"
864 (length peers-discovered)
865 (pretty-format (map
866 (match-lambda
867 [(Peer n _ u c) (list n u c)])
868 peers-discovered)))
869 (peers->file peers-cached
870 peers-cached-file)
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."
903 (length peers)
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
962 (module+ main
963 (let ([log-level 'info])
964 (command-line
965 #:program
966 "tt"
967 #:once-each
968 [("-d" "--debug")
969 "Enable debug log level."
970 (set! log-level 'debug)]
971 #:help-labels
972 ""
973 "and <command> is one of"
974 "r, read : Read the timeline (offline operation)."
975 "d, download : Download the timeline."
976 ; TODO Add path dynamically
977 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
978 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
979 ""
980 #:args (command . args)
981 (define log-writer (log-writer-start log-level))
982 (current-command-line-arguments (list->vector args))
983 (set-user-agent-str (build-path tt-home-dir "me"))
984 ; TODO dispatch should return status with which we should exit after cleanups
985 (dispatch command)
986 (log-writer-stop log-writer))))
This page took 0.136865 seconds and 4 git commands to generate.