Dedup read-in peers before using them
[tt.git] / tt.rkt
... / ...
CommitLineData
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(struct Msg
27 ([ts-epoch : Integer]
28 [ts-orig : String]
29 [nick : (Option String)]
30 [uri : Url]
31 [text : String]
32 [mentions : (Listof Peer)]))
33
34(struct Peer
35 ([nick : (Option String)]
36 [uri : Url])
37 #:transparent)
38
39(: tt-home-dir Path-String)
40(define tt-home-dir (build-path (expand-user-path "~") ".tt"))
41
42(: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
43(define (concurrent-filter-map num-workers f xs)
44 ; TODO preserve order of elements OR communicate that reorder is expected
45 ; TODO switch from mailboxes to channels
46 (define (make-worker id f)
47 (define parent (current-thread))
48 (λ ()
49 (define self : Thread (current-thread))
50 (: work (∀ (α) (-> α)))
51 (define (work)
52 (thread-send parent (cons 'next self))
53 (match (thread-receive)
54 ['done (thread-send parent (cons 'exit id))]
55 [(cons 'unit x) (begin
56 (define y (f x))
57 (when y (thread-send parent (cons 'result y)))
58 (work))]))
59 (work)))
60 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
61 (define (dispatch ws xs ys)
62 (if (empty? ws)
63 ys
64 (match (thread-receive)
65 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
66 [(cons 'result y) (dispatch ws xs (cons y ys))]
67 [(cons 'next thd) (match xs
68 ['() (begin
69 (thread-send thd 'done)
70 (dispatch ws xs ys))]
71 [(cons x xs) (begin
72 (thread-send thd (cons 'unit x))
73 (dispatch ws xs ys))])])))
74 (define workers (range num-workers))
75 (define threads (map (λ (id) (thread (make-worker id f))) workers))
76 (define results (dispatch workers xs '()))
77 (for-each thread-wait threads)
78 results)
79
80(module+ test
81 (let* ([f (λ (x) (if (even? x) x #f))]
82 [xs (range 11)]
83 [actual (sort (concurrent-filter-map 10 f xs) <)]
84 [expected (sort ( filter-map f xs) <)])
85 (check-equal? actual expected "concurrent-filter-map")))
86
87(: msg-print (-> Out-Format Integer Msg Void))
88(define msg-print
89 (let* ([colors (vector 36 33)]
90 [n (vector-length colors)])
91 (λ (out-format color-i msg)
92 (let ([color (vector-ref colors (modulo color-i n))]
93 [nick (Msg-nick msg)]
94 [uri (url->string (Msg-uri msg))]
95 [text (Msg-text msg)]
96 [mentions (Msg-mentions msg)])
97 (match out-format
98 ['single-line
99 (let ([nick (if nick nick uri)])
100 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
101 (parameterize
102 ([date-display-format 'iso-8601])
103 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
104 nick color text))]
105 ['multi-line
106 (let ([nick (if nick (string-append nick " ") "")])
107 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
108 (parameterize
109 ([date-display-format 'rfc2822])
110 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
111 (Msg-ts-orig msg)
112 nick uri color text))])))))
113
114(: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
115(define rfc3339->epoch
116 (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}))?$")])
117 (λ (ts)
118 (match (regexp-match re ts)
119 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
120 (let*
121 ([tz-offset
122 (match* (tz-whole tz-sign tz-HH tz-MM)
123 [("Z" #f #f #f)
124 0]
125 [(_ (or "-" "+") (? identity h) (? identity m))
126 (let ([h (string->number h)]
127 [m (string->number m)]
128 ; Reverse to get back to UTC:
129 [op (match tz-sign ["+" -] ["-" +])])
130 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
131 [(a b c d)
132 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
133 0])]
134 [ts-orig ts]
135 [local-time? #f]
136 [ts-epoch (find-seconds (if SS (string->number SS) 0)
137 (string->number MM)
138 (string->number HH)
139 (string->number dd)
140 (string->number mm)
141 (string->number yyyy)
142 local-time?)])
143 (+ ts-epoch tz-offset))]
144 [_
145 (log-error "Invalid timestamp: ~v" ts)
146 #f]))))
147
148(: str->msg (-> (Option String) Url String (Option Msg)))
149(define str->msg
150 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
151 (λ (nick uri str)
152 (with-handlers*
153 ([exn:fail?
154 (λ (e)
155 (log-error
156 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
157 str nick (url->string uri) e)
158 #f)])
159 (match (regexp-match re str)
160 [(list _wholething ts-orig text)
161 (let ([ts-epoch (rfc3339->epoch ts-orig)])
162 (if ts-epoch
163 (let ([mentions
164 (filter-map
165 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
166 [(list _wholething nick-uri)
167 (str->peer nick-uri)]))
168 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
169 (Msg ts-epoch ts-orig nick uri text mentions))
170 (begin
171 (log-error
172 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
173 str nick (url->string uri))
174 #f)))]
175 [_
176 (log-debug "Non-msg line from nick:~v, line:~a" nick str)
177 #f])))))
178
179(module+ test
180 ; TODO Test for when missing-nick case
181 (let* ([tzs (for*/list ([d '("-" "+")]
182 [h '("5" "05")]
183 [m '("00" ":00" "57" ":57")])
184 (string-append d h m))]
185 [tzs (list* "" "Z" tzs)])
186 (for* ([n '("fake-nick")]
187 [u '("fake-uri")]
188 [s '("" ":10")]
189 [f '("" ".1337")]
190 [z tzs]
191 [sep (list "\t" " ")]
192 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
193 (let* ([ts (string-append "2020-11-18T22:22"
194 (if (non-empty-string? s) s ":00")
195 z)]
196 [m (str->msg n u (string-append ts sep txt))])
197 (check-not-false m)
198 (check-equal? (Msg-nick m) n)
199 (check-equal? (Msg-uri m) u)
200 (check-equal? (Msg-text m) txt)
201 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
202 )))
203
204 (let* ([ts "2020-11-18T22:22:09-0500"]
205 [tab " "]
206 [text "Lorem ipsum"]
207 [nick "foo"]
208 [uri "bar"]
209 [actual (str->msg nick uri (string-append ts tab text))]
210 [expected (Msg 1605756129 ts nick uri text)])
211 (check-equal?
212 (Msg-ts-epoch actual)
213 (Msg-ts-epoch expected)
214 "str->msg ts-epoch")
215 (check-equal?
216 (Msg-ts-orig actual)
217 (Msg-ts-orig expected)
218 "str->msg ts-orig")
219 (check-equal?
220 (Msg-nick actual)
221 (Msg-nick expected)
222 "str->msg nick")
223 (check-equal?
224 (Msg-uri actual)
225 (Msg-uri expected)
226 "str->msg uri")
227 (check-equal?
228 (Msg-text actual)
229 (Msg-text expected)
230 "str->msg text")))
231
232(: str->lines (-> String (Listof String)))
233(define (str->lines str)
234 (string-split str (regexp "[\r\n]+")))
235
236(module+ test
237 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
238
239(: str->msgs (-> (Option String) Url String (Listof Msg)))
240(define (str->msgs nick uri str)
241 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
242
243(: cache-dir Path-String)
244(define cache-dir (build-path tt-home-dir "cache"))
245
246(define cache-object-dir (build-path cache-dir "objects"))
247
248(: url->cache-file-path-v1 (-> Url Path-String))
249(define (url->cache-file-path-v1 uri)
250 (define (hash-sha1 str) : (-> String String)
251 (define in (open-input-string str))
252 (define digest (sha1 in))
253 (close-input-port in)
254 digest)
255 (build-path cache-object-dir (hash-sha1 (url->string uri))))
256
257(: url->cache-file-path-v2 (-> Url Path-String))
258(define (url->cache-file-path-v2 uri)
259 (build-path cache-object-dir (uri-encode (url->string uri))))
260
261(define url->cache-object-path url->cache-file-path-v2)
262
263(define (url->cache-etag-path uri)
264 (build-path cache-dir "etags" (uri-encode (url->string uri))))
265
266(define (url->cache-lmod-path uri)
267 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
268
269; TODO Return Option
270(: uri-read-cached (-> Url String))
271(define (uri-read-cached uri)
272 (define path-v1 (url->cache-file-path-v1 uri))
273 (define path-v2 (url->cache-file-path-v2 uri))
274 (when (file-exists? path-v1)
275 (rename-file-or-directory path-v1 path-v2 #t))
276 (if (file-exists? path-v2)
277 (file->string path-v2)
278 (begin
279 (log-warning "Cache file not found for URI: ~a" (url->string uri))
280 "")))
281
282(: uri? (-> String Boolean))
283(define (uri? str)
284 (regexp-match? #rx"^[a-z]+://.*" (string-downcase str)))
285
286(: str->peer (String (Option Peer)))
287(define (str->peer str)
288 (log-debug "Parsing peer string: ~v" str)
289 (with-handlers*
290 ([exn:fail?
291 (λ (e)
292 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
293 #f)])
294 (match (string-split str)
295 [(list u) #:when (uri? u) (Peer #f (string->url u))]
296 [(list n u) #:when (uri? u) (Peer n (string->url u))]
297 [_
298 (log-error "Invalid peer string: ~v" str)
299 #f])))
300
301
302(: filter-comments (-> (Listof String) (Listof String)))
303(define (filter-comments lines)
304 (filter-not (λ (line) (string-prefix? line "#")) lines))
305
306(: str->peers (-> String (Listof Peer)))
307(define (str->peers str)
308 (filter-map str->peer (filter-comments (str->lines str))))
309
310(: peers->file (-> (Listof Peers) Path-String Void))
311(define (peers->file peers path)
312 (display-lines-to-file
313 (map (match-lambda
314 [(Peer n u)
315 (format "~a~a" (if n (format "~a " n) "") (url->string u))])
316 peers)
317 path
318 #:exists 'replace))
319
320(: file->peers (-> Path-String (Listof Peer)))
321(define (file->peers file-path)
322 (if (file-exists? file-path)
323 (str->peers (file->string file-path))
324 (begin
325 (log-warning "File does not exist: ~v" (path->string file-path))
326 '())))
327
328(define re-rfc2822
329 #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")
330
331(: b->n (-> Bytes (Option Number)))
332(define (b->n b)
333 (string->number (bytes->string/utf-8 b)))
334
335(: mon->num (-> Bytes Natural))
336(define/match (mon->num mon)
337 [(#"Jan") 1]
338 [(#"Feb") 2]
339 [(#"Mar") 3]
340 [(#"Apr") 4]
341 [(#"May") 5]
342 [(#"Jun") 6]
343 [(#"Jul") 7]
344 [(#"Aug") 8]
345 [(#"Sep") 9]
346 [(#"Oct") 10]
347 [(#"Nov") 11]
348 [(#"Dec") 12])
349
350(: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
351(define (rfc2822->epoch timestamp)
352 (match (regexp-match re-rfc2822 timestamp)
353 [(list _ _ dd mo yyyy HH MM SS)
354 #:when (and dd mo yyyy HH MM SS)
355 (find-seconds (b->n SS)
356 (b->n MM)
357 (b->n HH)
358 (b->n dd)
359 (mon->num mo)
360 (b->n yyyy)
361 #f)]
362 [_
363 #f]))
364
365(: user-agent String)
366(define user-agent
367 (let*
368 ([prog-name "tt"]
369 [prog-version (info:#%info-lookup 'version)]
370 [prog-uri "https://github.com/xandkar/tt"]
371 [user-peer-file (build-path tt-home-dir "me")]
372 [user
373 (if (file-exists? user-peer-file)
374 (match (first (file->peers user-peer-file))
375 [(Peer #f u) (format "+~a" (url->string u) )]
376 [(Peer n u) (format "+~a; @~a" (url->string u) n)])
377 (format "+~a" prog-uri))])
378 (format "~a/~a (~a)" prog-name prog-version user)))
379
380(: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
381(define (header-get headers name)
382 (match (filter-map (curry extract-field name) headers)
383 [(list val) val]
384 [_ #f]))
385
386(: uri-download (-> Url Void))
387(define (uri-download u)
388 (define cached-object-path (url->cache-object-path u))
389 (define cached-etag-path (url->cache-etag-path u))
390 (define cached-lmod-path (url->cache-lmod-path u))
391 (log-debug "uri-download ~v into ~v" u cached-object-path)
392 (define-values (status-line headers body-input)
393 ; TODO Timeout. Currently hangs on slow connections.
394 (http-sendrecv/url u #:headers (list (format "User-Agent: ~a" user-agent))))
395 (log-debug "headers: ~v" headers)
396 (log-debug "status-line: ~v" status-line)
397 (define status
398 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
399 (log-debug "status: ~v" status)
400 ; TODO Handle redirects
401 (match status
402 [200
403 (let* ([etag (header-get headers #"ETag")]
404 [lmod (header-get headers #"Last-Modified")]
405 [lmod-curr (if lmod (rfc2822->epoch lmod) #f)]
406 [lmod-prev (if (file-exists? cached-lmod-path)
407 (rfc2822->epoch (file->bytes cached-lmod-path))
408 #f)])
409 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
410 (unless (or (and etag
411 (file-exists? cached-etag-path)
412 (bytes=? etag (file->bytes cached-etag-path))
413 (begin
414 (log-info "ETags match, skipping the rest of ~v" (url->string u))
415 #t))
416 (and lmod-curr
417 lmod-prev
418 (<= lmod-curr lmod-prev)
419 (begin
420 (log-info "Last-Modified <= current skipping the rest of ~v" (url->string u))
421 #t)))
422 (begin
423 (log-info
424 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
425 (url->string u) etag lmod)
426 (make-parent-directory* cached-object-path)
427 (make-parent-directory* cached-etag-path)
428 (make-parent-directory* cached-lmod-path)
429 (call-with-output-file cached-object-path
430 (curry copy-port body-input)
431 #:exists 'replace)
432 (when etag
433 (display-to-file etag cached-etag-path #:exists 'replace))
434 (when lmod
435 (display-to-file lmod cached-lmod-path #:exists 'replace))))
436 (close-input-port body-input))]
437 [_
438 (raise status)]))
439
440(: timeline-print (-> Out-Format (Listof Msg) Void))
441(define (timeline-print out-format timeline)
442 (void (foldl (match-lambda**
443 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
444 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
445 (msg-print out-format i m)
446 (cons nick i))])
447 (cons "" 0)
448 timeline)))
449
450(: peer->msgs (-> Peer (Listof Msg)))
451(define (peer->msgs f)
452 (match-define (Peer nick uri) f)
453 (log-info "Reading peer nick:~v uri:~v" nick (url->string uri))
454 (str->msgs nick uri (uri-read-cached uri)))
455
456(: peer-download (-> Peer Void))
457(define (peer-download f)
458 (match-define (Peer nick uri) f)
459 (define u (url->string uri))
460 (log-info "Downloading peer uri:~a" u)
461 (with-handlers
462 ([exn:fail?
463 (λ (e)
464 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
465 #f)]
466 [integer?
467 (λ (status)
468 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
469 #f)])
470 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
471 (time-apply uri-download (list uri)))
472 (log-info "Peer downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
473
474(: timeline-download (-> Integer (Listof Peer) Void))
475(define (timeline-download num-workers peers)
476 ; TODO No need for map - can just iter
477 (void (concurrent-filter-map num-workers peer-download peers)))
478
479(: uniq (∀ (α) (-> (Listof α) (Listof α))))
480(define (uniq xs)
481 (set->list (list->set xs)))
482
483(: peers->timeline (-> (listof Peer) (listof Msg)))
484(define (peers->timeline peers)
485 (append* (filter-map peer->msgs peers)))
486
487(: timeline-sort (-> (listof Msg) timeline-order (Listof Msgs)))
488(define (timeline-sort msgs order)
489 (define cmp (match order
490 ['old->new <]
491 ['new->old >]))
492 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
493 (Msg-ts-epoch b)))))
494
495(: paths->peers (-> (Listof String) (Listof Peer)))
496(define (paths->peers paths)
497 (let* ([paths (match paths
498 ['()
499 (let ([peer-refs-file (build-path tt-home-dir "peers")])
500 (log-debug
501 "No peer ref file paths provided, defaulting to ~v"
502 (path->string peer-refs-file))
503 (list peer-refs-file))]
504 [paths
505 (log-debug "Peer ref file paths provided: ~v" paths)
506 (map string->path paths)])]
507 [peers (append* (map file->peers paths))])
508 (log-info "Read-in ~a peers." (length peers))
509 (uniq peers)))
510
511(: log-writer-stop (-> Thread Void))
512(define (log-writer-stop log-writer)
513 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
514 (thread-wait log-writer))
515
516(: log-writer-start (-> Log-Level Thread))
517(define (log-writer-start level)
518 (let* ([logger
519 (make-logger #f #f level #f)]
520 [log-receiver
521 (make-log-receiver logger level)]
522 [log-writer
523 (thread
524 (λ ()
525 (parameterize
526 ([date-display-format 'iso-8601])
527 (let loop ()
528 (match-define (vector level msg _ topic) (sync log-receiver))
529 (unless (equal? topic 'stop)
530 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
531 (loop))))))])
532 (current-logger logger)
533 log-writer))
534
535(module+ main
536 (let ([log-level 'info])
537 (command-line
538 #:program
539 "tt"
540 #:once-each
541 [("-d" "--debug")
542 "Enable debug log level."
543 (set! log-level 'debug)]
544 #:help-labels
545 ""
546 "and <command> is one of"
547 "r, read : Read the timeline (offline operation)."
548 "d, download : Download the timeline."
549 ; TODO Add path dynamically
550 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
551 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
552 ""
553 #:args (command . args)
554 (define log-writer (log-writer-start log-level))
555 (current-command-line-arguments (list->vector args))
556 (match command
557 [(or "d" "download")
558 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
559 ; started noticing significant slowdowns. Reducing to 5 seems to help.
560 (let ([num-workers 5])
561 (command-line
562 #:program
563 "tt download"
564 #:once-each
565 [("-j" "--jobs")
566 njobs "Number of concurrent jobs."
567 (set! num-workers (string->number njobs))]
568 #:args file-paths
569 (let ([peers (paths->peers file-paths)])
570 (define-values (_res _cpu real-ms _gc)
571 (time-apply timeline-download (list num-workers peers)))
572 (log-info "Downloaded timelines from ~a peers in ~a seconds."
573 (length peers)
574 (/ real-ms 1000.0)))))]
575 [(or "u" "upload")
576 (command-line
577 #:program
578 "tt upload"
579 #:args ()
580 (if (system (path->string (build-path tt-home-dir "upload")))
581 (exit 0)
582 (exit 1)))]
583 [(or "r" "read")
584 (let ([out-format 'multi-line]
585 [order 'old->new])
586 (command-line
587 #:program
588 "tt read"
589 #:once-each
590 [("-r" "--rev")
591 "Reverse displayed timeline order."
592 (set! order 'new->old)]
593 #:once-any
594 [("-s" "--short")
595 "Short output format"
596 (set! out-format 'single-line)]
597 [("-l" "--long")
598 "Long output format"
599 (set! out-format 'multi-line)]
600 #:args file-paths
601 (let* ([peers
602 (paths->peers file-paths)]
603 [timeline
604 (timeline-sort (peers->timeline peers) order)])
605 (timeline-print out-format timeline))))]
606 [(or "c" "crawl")
607 (command-line
608 #:program
609 "tt crawl"
610 #:args file-paths
611 (let* ([peers-all-file
612 (build-path tt-home-dir "peers-all")]
613 [peers-mentioned-file
614 (build-path tt-home-dir "peers-mentioned")]
615 [peers
616 (paths->peers
617 (match file-paths
618 ; TODO Refactor such that path->string not needed
619 ['() (list (path->string peers-all-file))]
620 [_ file-paths]))]
621 [timeline
622 (peers->timeline peers)]
623 [peers-mentioned-curr
624 (uniq (append* (map Msg-mentions timeline)))]
625 [peers-mentioned-prev
626 (file->peers peers-mentioned-file)]
627 [peers-mentioned
628 (uniq (append peers-mentioned-prev
629 peers-mentioned-curr))]
630 [peers-all-prev
631 (file->peers peers-all-file)]
632 [peers-all
633 (uniq (append peers
634 peers-mentioned
635 peers-all-prev))])
636 (peers->file peers-mentioned
637 peers-mentioned-file)
638 (peers->file peers-all
639 peers-all-file)))]
640 [command
641 (eprintf "Error: invalid command: ~v\n" command)
642 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
643 (exit 1)])
644 (log-writer-stop log-writer))))
This page took 0.032403 seconds and 4 git commands to generate.