1 #lang typed/racket/no-check
10 (require (prefix-in info: "info.rkt"))
18 (define-type Out-Format
22 (define-type Timeline-Order
29 [nick : (Option String)]
32 [mentions : (Listof Peer)]))
35 ([nick : (Option String)]
40 ([nick : (Option String)]
46 ; TODO Normalize dir var naming
47 (: tt-home-dir Path-String)
48 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
50 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
51 (define (concurrent-filter-map num-workers f xs)
52 ; TODO preserve order of elements OR communicate that reorder is expected
53 ; TODO switch from mailboxes to channels
54 (define (make-worker id f)
55 (define parent (current-thread))
57 (define self : Thread (current-thread))
58 (: work (∀ (α) (-> α)))
60 (thread-send parent (cons 'next self))
61 (match (thread-receive)
62 ['done (thread-send parent (cons 'exit id))]
63 [(cons 'unit x) (begin
65 (when y (thread-send parent (cons 'result y)))
68 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
69 (define (dispatch ws xs ys)
72 (match (thread-receive)
73 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
74 [(cons 'result y) (dispatch ws xs (cons y ys))]
75 [(cons 'next thd) (match xs
77 (thread-send thd 'done)
80 (thread-send thd (cons 'unit x))
81 (dispatch ws xs ys))])])))
82 (define workers (range num-workers))
83 (define threads (map (λ (id) (thread (make-worker id f))) workers))
84 (define results (dispatch workers xs '()))
85 (for-each thread-wait threads)
89 (let* ([f (λ (x) (if (even? x) x #f))]
91 [actual (sort (concurrent-filter-map 10 f xs) <)]
92 [expected (sort ( filter-map f xs) <)])
93 (check-equal? actual expected "concurrent-filter-map")))
95 (: msg-print (-> Out-Format Integer Msg Void))
97 (let* ([colors (vector 36 33)]
98 [n (vector-length colors)])
99 (λ (out-format color-i msg)
100 (let ([color (vector-ref colors (modulo color-i n))]
101 [nick (Msg-nick msg)]
102 [uri (url->string (Msg-uri msg))]
103 [text (Msg-text msg)]
104 [mentions (Msg-mentions msg)])
107 (let ([nick (if nick nick uri)])
108 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
110 ([date-display-format 'iso-8601])
111 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
114 (let ([nick (if nick (string-append nick " ") "")])
115 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
117 ([date-display-format 'rfc2822])
118 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
120 nick uri color text))])))))
122 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
123 (define rfc3339->epoch
124 (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}))?$")])
126 (match (regexp-match re ts)
127 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
130 (match* (tz-whole tz-sign tz-HH tz-MM)
133 [(_ (or "-" "+") (? identity h) (? identity m))
134 (let ([h (string->number h)]
135 [m (string->number m)]
136 ; Reverse to get back to UTC:
137 [op (match tz-sign ["+" -] ["-" +])])
138 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
140 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
144 [ts-epoch (find-seconds (if SS (string->number SS) 0)
149 (string->number yyyy)
151 (+ ts-epoch tz-offset))]
153 (log-error "Invalid timestamp: ~v" ts)
156 (: str->msg (-> (Option String) Url String (Option Msg)))
158 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
160 (define str-head (substring str 0 (min 100 (string-length str))))
165 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
166 str-head nick (url->string uri) e)
168 (match (regexp-match re str)
169 [(list _wholething ts-orig text)
170 (let ([ts-epoch (rfc3339->epoch ts-orig)])
174 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
175 [(list _wholething nick-uri)
176 (str->peer nick-uri)]))
177 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
178 (Msg ts-epoch ts-orig nick uri text mentions))
181 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
182 str-head nick (url->string uri))
185 (log-debug "Non-msg line from nick:~v, line:~a" nick str-head)
189 ; TODO Test for when missing-nick case
190 (let* ([tzs (for*/list ([d '("-" "+")]
192 [m '("00" ":00" "57" ":57")])
193 (string-append d h m))]
194 [tzs (list* "" "Z" tzs)])
195 (for* ([n '("fake-nick")]
200 [sep (list "\t" " ")]
201 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
202 (let* ([ts (string-append "2020-11-18T22:22"
203 (if (non-empty-string? s) s ":00")
205 [m (str->msg n u (string-append ts sep txt))])
207 (check-equal? (Msg-nick m) n)
208 (check-equal? (Msg-uri m) u)
209 (check-equal? (Msg-text m) txt)
210 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
213 (let* ([ts "2020-11-18T22:22:09-0500"]
218 [actual (str->msg nick uri (string-append ts tab text))]
219 [expected (Msg 1605756129 ts nick uri text '())])
221 (Msg-ts-epoch actual)
222 (Msg-ts-epoch expected)
226 (Msg-ts-orig expected)
241 (: str->lines (-> String (Listof String)))
242 (define (str->lines str)
243 (string-split str (regexp "[\r\n]+")))
246 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
248 (: str->msgs (-> (Option String) Url String (Listof Msg)))
249 (define (str->msgs nick uri str)
250 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
252 (: cache-dir Path-String)
253 (define cache-dir (build-path tt-home-dir "cache"))
255 (define cache-object-dir (build-path cache-dir "objects"))
257 (: url->cache-file-path-v1 (-> Url Path-String))
258 (define (url->cache-file-path-v1 uri)
259 (define (hash-sha1 str) : (-> String String)
260 (define in (open-input-string str))
261 (define digest (sha1 in))
262 (close-input-port in)
264 (build-path cache-object-dir (hash-sha1 (url->string uri))))
266 (: url->cache-file-path-v2 (-> Url Path-String))
267 (define (url->cache-file-path-v2 uri)
268 (build-path cache-object-dir (uri-encode (url->string uri))))
270 (define url->cache-object-path url->cache-file-path-v2)
272 (: cache-object-filename->url (-> Path-String Url))
273 (define (cache-object-filename->url name)
274 (string->url (uri-decode (path->string name))))
276 (define (url->cache-etag-path uri)
277 (build-path cache-dir "etags" (uri-encode (url->string uri))))
279 (define (url->cache-lmod-path uri)
280 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
283 (: uri-read-cached (-> Url String))
284 (define (uri-read-cached uri)
285 (define path-v1 (url->cache-file-path-v1 uri))
286 (define path-v2 (url->cache-file-path-v2 uri))
287 (when (file-exists? path-v1)
288 (rename-file-or-directory path-v1 path-v2 #t))
289 (if (file-exists? path-v2)
290 (file->string path-v2)
292 (log-warning "Cache file not found for URI: ~a" (url->string uri))
295 (: uri? (-> String Boolean))
297 (regexp-match? #rx"^[a-z]+://.*" (string-downcase str)))
299 (: str->peer (String (Option Peer)))
300 (define (str->peer str)
301 (log-debug "Parsing peer string: ~v" str)
305 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
307 (match (string-split str)
308 [(list u) #:when (uri? u) (Peer #f (string->url u))]
309 [(list n u) #:when (uri? u) (Peer n (string->url u))]
311 (log-error "Invalid peer string: ~v" str)
315 (: filter-comments (-> (Listof String) (Listof String)))
316 (define (filter-comments lines)
317 (filter-not (λ (line) (string-prefix? line "#")) lines))
319 (: str->peers (-> String (Listof Peer)))
320 (define (str->peers str)
321 (filter-map str->peer (filter-comments (str->lines str))))
323 (: peers->file (-> (Listof Peers) Path-String Void))
324 (define (peers->file peers path)
325 (display-lines-to-file
328 (format "~a~a" (if n (format "~a " n) "") (url->string u))])
333 (: file->peers (-> Path-String (Listof Peer)))
334 (define (file->peers file-path)
335 (if (file-exists? file-path)
336 (str->peers (file->string file-path))
338 (log-warning "File does not exist: ~v" (path->string file-path))
342 #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")
344 (: b->n (-> Bytes (Option Number)))
346 (string->number (bytes->string/utf-8 b)))
348 (: mon->num (-> Bytes Natural))
349 (define/match (mon->num mon)
363 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
364 (define (rfc2822->epoch timestamp)
365 (match (regexp-match re-rfc2822 timestamp)
366 [(list _ _ dd mo yyyy HH MM SS)
367 #:when (and dd mo yyyy HH MM SS)
368 (find-seconds (b->n SS)
378 (: user-agent String)
382 [prog-version (info:#%info-lookup 'version)]
383 [prog-uri "https://github.com/xandkar/tt"]
384 [user-peer-file (build-path tt-home-dir "me")]
386 (if (file-exists? user-peer-file)
387 (match (first (file->peers user-peer-file))
388 [(Peer #f u) (format "+~a" (url->string u) )]
389 [(Peer n u) (format "+~a; @~a" (url->string u) n)])
390 (format "+~a" prog-uri))])
391 (format "~a/~a (~a)" prog-name prog-version user)))
393 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
394 (define (header-get headers name)
395 (match (filter-map (curry extract-field name) headers)
399 (: uri-download (-> Url Void))
400 (define (uri-download u)
401 (define cached-object-path (url->cache-object-path u))
402 (define cached-etag-path (url->cache-etag-path u))
403 (define cached-lmod-path (url->cache-lmod-path u))
404 (log-debug "uri-download ~v into ~v" u cached-object-path)
405 (define-values (status-line headers body-input)
406 ; TODO Timeout. Currently hangs on slow connections.
407 (http-sendrecv/url u #:headers (list (format "User-Agent: ~a" user-agent))))
408 (log-debug "headers: ~v" headers)
409 (log-debug "status-line: ~v" status-line)
411 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
412 (log-debug "status: ~v" status)
413 ; TODO Handle redirects
416 (let* ([etag (header-get headers #"ETag")]
417 [lmod (header-get headers #"Last-Modified")]
418 [lmod-curr (if lmod (rfc2822->epoch lmod) #f)]
419 [lmod-prev (if (file-exists? cached-lmod-path)
420 (rfc2822->epoch (file->bytes cached-lmod-path))
422 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
423 (unless (or (and etag
424 (file-exists? cached-etag-path)
425 (bytes=? etag (file->bytes cached-etag-path))
427 (log-info "ETags match, skipping the rest of ~v" (url->string u))
431 (<= lmod-curr lmod-prev)
433 (log-info "Last-Modified <= current skipping the rest of ~v" (url->string u))
437 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
438 (url->string u) etag lmod)
439 (make-parent-directory* cached-object-path)
440 (make-parent-directory* cached-etag-path)
441 (make-parent-directory* cached-lmod-path)
442 (call-with-output-file cached-object-path
443 (curry copy-port body-input)
446 (display-to-file etag cached-etag-path #:exists 'replace))
448 (display-to-file lmod cached-lmod-path #:exists 'replace))))
449 (close-input-port body-input))]
453 (: timeline-print (-> Out-Format (Listof Msg) Void))
454 (define (timeline-print out-format timeline)
455 (void (foldl (match-lambda**
456 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
457 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
458 (msg-print out-format i m)
463 (: peer->msgs (-> Peer (Listof Msg)))
464 (define (peer->msgs f)
465 (match-define (Peer nick uri) f)
466 (log-info "Reading peer nick:~v uri:~v" nick (url->string uri))
467 (str->msgs nick uri (uri-read-cached uri)))
469 (: peer-download (-> Peer Void))
470 (define (peer-download f)
471 (match-define (Peer nick uri) f)
472 (define u (url->string uri))
473 (log-info "Downloading peer uri:~a" u)
477 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
481 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
483 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
484 (time-apply uri-download (list uri)))
485 (log-info "Peer downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
487 (: timeline-download (-> Integer (Listof Peer) Void))
488 (define (timeline-download num-workers peers)
489 ; TODO No need for map - can just iter
490 (void (concurrent-filter-map num-workers peer-download peers)))
492 (: uniq (∀ (α) (-> (Listof α) (Listof α))))
494 (set->list (list->set xs)))
496 (: peers->timeline (-> (listof Peer) (listof Msg)))
497 (define (peers->timeline peers)
498 (append* (filter-map peer->msgs peers)))
500 (: timeline-sort (-> (listof Msg) timeline-order (Listof Msgs)))
501 (define (timeline-sort msgs order)
502 (define cmp (match order
505 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
508 (: paths->peers (-> (Listof String) (Listof Peer)))
509 (define (paths->peers paths)
510 (let* ([paths (match paths
512 (let ([peer-refs-file (build-path tt-home-dir "peers")])
514 "No peer ref file paths provided, defaulting to ~v"
515 (path->string peer-refs-file))
516 (list peer-refs-file))]
518 (log-debug "Peer ref file paths provided: ~v" paths)
519 (map string->path paths)])]
520 [peers (append* (map file->peers paths))])
521 (log-info "Read-in ~a peers." (length peers))
524 (: mentioned-peers-in-cache (-> (Listof Peer)))
525 (define (mentioned-peers-in-cache)
527 (append* (map (λ (filename)
528 (define path (build-path cache-object-dir filename))
529 (define size (/ (file-size path) 1000000.0))
530 (log-info "BEGIN parsing ~a MB from file: ~v"
533 (define t0 (current-inexact-milliseconds))
534 (define m (filter-map
536 (str->msg #f (cache-object-filename->url filename) line))
538 (file->lines path))))
539 (define t1 (current-inexact-milliseconds))
540 (log-info "END parsing ~a MB in ~a seconds from file: ~v."
545 (log-warning "No messages found in ~a" (path->string path)))
547 (directory-list cache-object-dir))))
548 (uniq (append* (map Msg-mentions msgs))))
550 (: follower->peer (-> Follower Peer))
551 (define/match (follower->peer f)
552 [((Follower n u _ _)) (Peer n u)])
554 (: weblog-line->follower (-> String (Option Peer)))
555 (define weblog-line->follower
556 (let ([re #px"([^/]+)/([^ ]+) +\\(\\+([a-z]+://[^;]+); *@([^\\)]+)\\)"])
558 (match (regexp-match re log-line)
559 [(list _ client version uri nick)
560 (let ([f (Follower nick (string->url uri) client version)])
561 (log-debug "Found follower: ~v" f)
565 (define (weblog-file->peers file-path)
566 (define size (/ (file-size file-path) 1000000.0))
567 (log-info "BEGIN parsing ~a MB from file: ~v" size (path->string file-path))
568 (define t0 (current-inexact-milliseconds))
570 (let* ([prefilter-cmd-path
571 (build-path tt-home-dir "hooks" "web-log-prefilter")]
573 (match (process* prefilter-cmd-path file-path)
574 [(list in _out pid err ctrl)
576 (match (ctrl 'exit-code)
577 [(or 0 1) ; Assuming grep's: 0: found, 1: not found, 2: error
580 (log-warning "Prefilter hook failed: ~a" (port->string err))
581 (file->lines file-path)])])])
582 (map follower->peer (filter-map weblog-line->follower lines))))
583 (define t1 (current-inexact-milliseconds))
584 (log-info "END parsing ~a MB in ~a seconds from file: ~v."
587 (path->string file-path))
589 (log-warning "No peers found in ~a" (path->string file-path)))
592 (define (weblog-dir->peers dir-path)
594 (map weblog-file->peers
597 (define file-path (build-path dir-path filename))
598 (if (equal? 'file (file-or-directory-type file-path))
601 (if (directory-exists? dir-path)
602 (directory-list dir-path)
605 (define (follower-peers-in-web-logs log-dirs)
606 (uniq (append* (map weblog-dir->peers log-dirs))))
608 (: log-writer-stop (-> Thread Void))
609 (define (log-writer-stop log-writer)
610 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
611 (thread-wait log-writer))
613 (: log-writer-start (-> Log-Level Thread))
614 (define (log-writer-start level)
616 (make-logger #f #f level #f)]
618 (make-log-receiver logger level)]
623 ([date-display-format 'iso-8601])
625 (match-define (vector level msg _ topic) (sync log-receiver))
626 (unless (equal? topic 'stop)
627 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
629 (current-logger logger)
633 (let ([log-level 'info])
639 "Enable debug log level."
640 (set! log-level 'debug)]
643 "and <command> is one of"
644 "r, read : Read the timeline (offline operation)."
645 "d, download : Download the timeline."
646 ; TODO Add path dynamically
647 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
648 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
650 #:args (command . args)
651 (define log-writer (log-writer-start log-level))
652 (current-command-line-arguments (list->vector args))
655 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
656 ; started noticing significant slowdowns. Reducing to 5 seems to help.
657 (let ([num-workers 5])
663 njobs "Number of concurrent jobs."
664 (set! num-workers (string->number njobs))]
666 (let ([peers (paths->peers file-paths)])
667 (define-values (_res _cpu real-ms _gc)
668 (time-apply timeline-download (list num-workers peers)))
669 (log-info "Downloaded timelines from ~a peers in ~a seconds."
672 (let ([hook-path (build-path tt-home-dir "hooks" "download")])
673 (if (file-exists? hook-path)
674 (if (member 'execute (file-or-directory-permissions hook-path))
675 (if (system (path->string hook-path))
678 (log-warning "Download hook found, but not executable."))
679 (log-warning "Download hook not found.")))))]
685 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
689 (let ([out-format 'multi-line]
698 "Reverse displayed timeline order."
699 (set! order 'new->old)]
701 m "Earliest time to display (ignore anything before it)."
702 (set! ts-min (rfc3339->epoch m))]
704 x "Latest time to display (ignore anything after it)."
705 (set! ts-max (rfc3339->epoch x))]
708 "Short output format"
709 (set! out-format 'single-line)]
712 (set! out-format 'multi-line)]
715 (paths->peers file-paths)]
717 (timeline-sort (peers->timeline peers) order)]
719 (filter (λ (m) (and (if ts-min (>= (Msg-ts-epoch m)
722 (if ts-max (<= (Msg-ts-epoch m)
726 (timeline-print out-format timeline))))]
731 #:args log-files-directories
733 (λ (peers) (sort peers (match-lambda**
734 [((Peer n1 _) (Peer n2 _))
735 (string<? (if n1 n1 "")
737 ; TODO Tidy-up redundant set conversions
739 (build-path tt-home-dir "peers-all")]
740 [peers-mentioned-file
741 (build-path tt-home-dir "peers-mentioned")]
742 [peers-followers-file
743 (build-path tt-home-dir "peers-followers")]
744 [peers-followers-curr
745 (follower-peers-in-web-logs
746 (if (empty? log-files-directories)
747 (list (build-path tt-home-dir "web-logs"))
748 log-files-directories))]
749 [peers-mentioned-curr
750 (mentioned-peers-in-cache)]
751 [peers-mentioned-prev
752 (file->peers peers-mentioned-file)]
753 [peers-followers-prev
754 (file->peers peers-followers-file)]
756 (peers-sort (uniq (append peers-mentioned-prev
757 peers-mentioned-curr)))]
759 (file->peers peers-all-file)]
761 (list->set (append peers-followers-prev
762 peers-followers-curr))]
764 (list->set (append peers-mentioned
765 (set->list peers-followers)
767 [peers-discovered-followers
768 (set-subtract (list->set peers-followers)
769 (list->set peers-followers-prev))]
771 (set-subtract peers-all (list->set peers-all-prev))]
773 (peers-sort (set->list peers-all))])
774 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
775 (log-info "Known peers total: ~a" (length peers-all))
776 (log-info "Discovered ~a new followers:~n~a"
777 (set-count peers-discovered-followers)
779 (λ (p) (cons (Peer-nick p)
780 (url->string (Peer-uri p))))
781 (set->list peers-discovered-followers))))
782 (log-info "Discovered ~a new peers:~n~a"
783 (set-count peers-discovered)
785 (λ (p) (cons (Peer-nick p)
786 (url->string (Peer-uri p))))
787 (set->list peers-discovered))))
788 (peers->file (peers-sort (set->list peers-followers))
789 peers-followers-file)
790 (peers->file peers-mentioned
791 peers-mentioned-file)
792 (peers->file peers-all
795 (eprintf "Error: invalid command: ~v\n" command)
796 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
798 (log-writer-stop log-writer))))