1 #lang typed/racket/no-check
10 (require (prefix-in info: "info.rkt"))
18 (define-type Out-Format
22 (define-type Timeline-Order
27 (∀ (α β) (U (cons 'ok α)
33 [nick : (Option String)]
36 [mentions : (Listof Peer)]))
39 ([nick : (Option String)]
41 [comment : (Option String)])
45 ([status-line : String]
46 [headers : (Listof Bytes)]
47 [body-input : Input-Port])
50 (: tt-home-dir Path-String)
51 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
53 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
54 (define (concurrent-filter-map num-workers f xs)
55 ; TODO preserve order of elements OR communicate that reorder is expected
56 ; TODO switch from mailboxes to channels
57 (define (make-worker id f)
58 (define parent (current-thread))
60 (define self : Thread (current-thread))
61 (: work (∀ (α) (-> α)))
63 (thread-send parent (cons 'next self))
64 (match (thread-receive)
65 ['done (thread-send parent (cons 'exit id))]
66 [(cons 'unit x) (begin
68 (when y (thread-send parent (cons 'result y)))
71 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
72 (define (dispatch ws xs ys)
75 (match (thread-receive)
76 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
77 [(cons 'result y) (dispatch ws xs (cons y ys))]
78 [(cons 'next thd) (match xs
80 (thread-send thd 'done)
83 (thread-send thd (cons 'unit x))
84 (dispatch ws xs ys))])])))
85 (define workers (range num-workers))
86 (define threads (map (λ (id) (thread (make-worker id f))) workers))
87 (define results (dispatch workers xs '()))
88 (for-each thread-wait threads)
92 (let* ([f (λ (x) (if (even? x) x #f))]
94 [actual (sort (concurrent-filter-map 10 f xs) <)]
95 [expected (sort ( filter-map f xs) <)])
96 (check-equal? actual expected "concurrent-filter-map")))
98 (: msg-print (-> Out-Format Integer Msg Void))
100 (let* ([colors (vector 36 33)]
101 [n (vector-length colors)])
102 (λ (out-format color-i msg)
103 (let ([color (vector-ref colors (modulo color-i n))]
104 [nick (Msg-nick msg)]
105 [uri (url->string (Msg-uri msg))]
106 [text (Msg-text msg)]
107 [mentions (Msg-mentions msg)])
110 (let ([nick (if nick nick uri)])
111 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
113 ([date-display-format 'iso-8601])
114 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
117 (let ([nick (if nick (string-append nick " ") "")])
118 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
120 ([date-display-format 'rfc2822])
121 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
123 nick uri color text))])))))
125 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
126 (define rfc3339->epoch
127 (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}))?$")])
129 (match (regexp-match re ts)
130 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
133 (match* (tz-whole tz-sign tz-HH tz-MM)
136 [(_ (or "-" "+") (? identity h) (? identity m))
137 (let ([h (string->number h)]
138 [m (string->number m)]
139 ; Reverse to get back to UTC:
140 [op (match tz-sign ["+" -] ["-" +])])
141 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
143 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
147 [ts-epoch (find-seconds (if SS (string->number SS) 0)
152 (string->number yyyy)
154 (+ ts-epoch tz-offset))]
156 (log-error "Invalid timestamp: ~v" ts)
159 (: str->msg (-> (Option String) Url String (Option Msg)))
161 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
163 (define str-head (substring str 0 (min 100 (string-length str))))
168 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
169 str-head nick (url->string uri) e)
171 (match (regexp-match re str)
172 [(list _wholething ts-orig text)
173 (let ([ts-epoch (rfc3339->epoch ts-orig)])
177 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
178 [(list _wholething nick-uri)
179 (str->peer nick-uri)]))
180 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
181 (Msg ts-epoch ts-orig nick uri text mentions))
184 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
185 str-head nick (url->string uri))
188 (log-debug "Non-msg line from nick:~v, line:~a" nick str-head)
192 ; TODO Test for when missing-nick case
193 (let* ([tzs (for*/list ([d '("-" "+")]
195 [m '("00" ":00" "57" ":57")])
196 (string-append d h m))]
197 [tzs (list* "" "Z" tzs)])
198 (for* ([n '("fake-nick")]
203 [sep (list "\t" " ")]
204 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
205 (let* ([ts (string-append "2020-11-18T22:22"
206 (if (non-empty-string? s) s ":00")
208 [m (str->msg n u (string-append ts sep txt))])
210 (check-equal? (Msg-nick m) n)
211 (check-equal? (Msg-uri m) u)
212 (check-equal? (Msg-text m) txt)
213 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
216 (let* ([ts "2020-11-18T22:22:09-0500"]
221 [actual (str->msg nick uri (string-append ts tab text))]
222 [expected (Msg 1605756129 ts nick uri text '())])
224 (Msg-ts-epoch actual)
225 (Msg-ts-epoch expected)
229 (Msg-ts-orig expected)
244 (: str->lines (-> String (Listof String)))
245 (define (str->lines str)
246 (string-split str (regexp "[\r\n]+")))
249 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
251 (: str->msgs (-> (Option String) Url String (Listof Msg)))
252 (define (str->msgs nick uri str)
253 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
255 (: cache-dir Path-String)
256 (define cache-dir (build-path tt-home-dir "cache"))
258 (define cache-object-dir (build-path cache-dir "objects"))
260 (: url->cache-file-path-v1 (-> Url Path-String))
261 (define (url->cache-file-path-v1 uri)
262 (define (hash-sha1 str) : (-> String String)
263 (define in (open-input-string str))
264 (define digest (sha1 in))
265 (close-input-port in)
267 (build-path cache-object-dir (hash-sha1 (url->string uri))))
269 (: url->cache-file-path-v2 (-> Url Path-String))
270 (define (url->cache-file-path-v2 uri)
271 (build-path cache-object-dir (uri-encode (url->string uri))))
273 (define url->cache-object-path url->cache-file-path-v2)
275 (: cache-object-filename->url (-> Path-String Url))
276 (define (cache-object-filename->url name)
277 (string->url (uri-decode (path->string name))))
279 (define (url->cache-etag-path uri)
280 (build-path cache-dir "etags" (uri-encode (url->string uri))))
282 (define (url->cache-lmod-path uri)
283 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
286 (: uri-read-cached (-> Url String))
287 (define (uri-read-cached uri)
288 (define path-v1 (url->cache-file-path-v1 uri))
289 (define path-v2 (url->cache-file-path-v2 uri))
290 (when (file-exists? path-v1)
291 (rename-file-or-directory path-v1 path-v2 #t))
292 (if (file-exists? path-v2)
293 (file->string path-v2)
295 (log-warning "Cache file not found for URI: ~a" (url->string uri))
298 (: str->url (-> String (Option String)))
301 ([exn:fail? (λ (e) #f)])
304 (: str->peer (String (Option Peer)))
305 (define (str->peer str)
306 (log-debug "Parsing peer string: ~v" str)
309 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
317 (match (str->url url)
319 (log-error "Invalid URI in peer string: ~v" str)
321 [url (Peer nick url comment)])]
323 (log-error "Invalid peer string: ~v" str)
328 (str->peer "foo http://bar/file.txt # some rando")
329 (Peer "foo" (str->url "http://bar/file.txt") "some rando"))
331 (str->peer "http://bar/file.txt # some rando")
332 (Peer #f (str->url "http://bar/file.txt") "some rando"))
334 (str->peer "http://bar/file.txt #")
335 (Peer #f (str->url "http://bar/file.txt") ""))
337 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
338 (Peer #f (str->url "http://bar/file.txt#") #f))
340 (str->peer "http://bar/file.txt")
341 (Peer #f (str->url "http://bar/file.txt") #f))
343 (str->peer "foo http://bar/file.txt")
344 (Peer "foo" (str->url "http://bar/file.txt") #f))
346 (str->peer "foo bar # baz")
349 (str->peer "foo bar://baz # quux")
350 (Peer "foo" (str->url "bar://baz") "quux"))
352 (str->peer "foo bar//baz # quux")
355 (: filter-comments (-> (Listof String) (Listof String)))
356 (define (filter-comments lines)
357 (filter-not (λ (line) (string-prefix? line "#")) lines))
359 (: str->peers (-> String (Listof Peer)))
360 (define (str->peers str)
361 (filter-map str->peer (filter-comments (str->lines str))))
363 (: peers->file (-> (Listof Peers) Path-String Void))
364 (define (peers->file peers path)
365 (display-lines-to-file
369 (if n (format "~a " n) "")
371 (if c (format " # ~a" c) ""))])
376 (: file->peers (-> Path-String (Listof Peer)))
377 (define (file->peers file-path)
378 (if (file-exists? file-path)
379 (str->peers (file->string file-path))
381 (log-warning "File does not exist: ~v" (path->string file-path))
385 #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")
387 (: b->n (-> Bytes (Option Number)))
389 (string->number (bytes->string/utf-8 b)))
391 (: mon->num (-> Bytes Natural))
392 (define/match (mon->num mon)
406 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
407 (define (rfc2822->epoch timestamp)
408 (match (regexp-match re-rfc2822 timestamp)
409 [(list _ _ dd mo yyyy HH MM SS)
410 #:when (and dd mo yyyy HH MM SS)
411 (find-seconds (b->n SS)
421 (: user-agent String)
425 [prog-version (info:#%info-lookup 'version)]
426 [prog-uri "https://github.com/xandkar/tt"]
427 [user-peer-file (build-path tt-home-dir "me")]
429 (if (file-exists? user-peer-file)
430 (match (first (file->peers user-peer-file))
431 [(Peer #f u _) (format "+~a" (url->string u) )]
432 [(Peer n u _) (format "+~a; @~a" (url->string u) n)])
433 (format "+~a" prog-uri))])
434 (format "~a/~a (~a)" prog-name prog-version user)))
436 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
437 (define (header-get headers name)
438 (match (filter-map (curry extract-field name) headers)
442 (: uri-download-from-port
443 (-> Url (Listof (U Bytes String)) Input-Port
444 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
445 (define (uri-download-from-port u headers body-input)
446 (define u-str (url->string u))
447 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
448 (define cached-object-path (url->cache-object-path u))
449 (define cached-etag-path (url->cache-etag-path u))
450 (define cached-lmod-path (url->cache-lmod-path u))
451 (define etag (header-get headers #"ETag"))
452 (define lmod (header-get headers #"Last-Modified"))
453 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
454 (define lmod-prev (if (file-exists? cached-lmod-path)
455 (rfc2822->epoch (file->bytes cached-lmod-path))
457 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
460 (file-exists? cached-etag-path)
461 (bytes=? etag (file->bytes cached-etag-path))
463 (log-debug "ETags match, skipping the rest of ~v" u-str)
467 (<= lmod-curr lmod-prev)
469 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
474 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
476 (make-parent-directory* cached-object-path)
477 (make-parent-directory* cached-etag-path)
478 (make-parent-directory* cached-lmod-path)
479 (call-with-output-file cached-object-path
480 (curry copy-port body-input)
483 (display-to-file etag cached-etag-path #:exists 'replace))
485 (display-to-file lmod cached-lmod-path #:exists 'replace))
490 (-> Positive-Float Url
491 (Result (U 'skipped-cached 'downloaded-new)
492 Any))) ; TODO Maybe more-precise error type?
493 (define (uri-download timeout u)
494 (define u-str (url->string u))
495 (define timeout-chan (make-channel))
496 (define result-chan (make-channel))
497 (define timeout-thread
499 ; Doing this instead of sync/timeout to distinguish error values,
500 ; rather than just have #f to work with.
502 (channel-put timeout-chan '(error . timeout)))))
503 (define result-thread
505 ; XXX We timeout getting a response, but body download could
506 ; also take a long time and we might want to time that out as
507 ; well, but then we may end-up with partially downloaded
508 ; objects. But that could happen anyway if the server drops the
509 ; connection for whatever reason.
511 ; Maybe that is OK once we start treating the
512 ; downloaded object as an addition to the stored set of
513 ; messages, rather than the final set of messages.
516 ; - 1st try can just be an in-memory set that gets written-to
517 ; and read-from disk as a whole.
520 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
522 (λ (e) `(error . (net-error . ,e)))]
524 (λ (e) `(error . (other . ,e)))])
525 (define-values (status-line headers body-input)
528 #:headers (list (format "User-Agent: ~a" user-agent))))
529 `(ok . ,(Resp status-line headers body-input))))
530 (channel-put result-chan result))))
534 (kill-thread result-thread)
535 (kill-thread timeout-thread)
539 [(cons 'ok (Resp status-line headers body-input))
540 (log-debug "headers: ~v" headers)
541 (log-debug "status-line: ~v" status-line)
543 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
544 (log-debug "status: ~v" status)
545 ; TODO Handle redirects. Should be within same timeout as req and body.
549 `(ok . ,(uri-download-from-port u headers body-input))]
551 `(error . (http . ,status))])])
552 (close-input-port body-input)
555 (: timeline-print (-> Out-Format (Listof Msg) Void))
556 (define (timeline-print out-format timeline)
557 (void (foldl (match-lambda**
558 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
559 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
560 (msg-print out-format i m)
565 (: peer->msgs (-> Peer (Listof Msg)))
566 (define (peer->msgs peer)
567 (match-define (Peer nick uri _) peer)
568 (log-info "Reading peer nick:~v uri:~v" nick (url->string uri))
569 (str->msgs nick uri (uri-read-cached uri)))
572 (-> Positive-Float Peer
573 (Result (U 'skipped-cached 'downloaded-new)
575 (define (peer-download timeout peer)
576 (match-define (Peer nick uri _) peer)
577 (define u (url->string uri))
578 (log-info "Download BEGIN URL:~a" u)
579 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
580 (time-apply uri-download (list timeout uri)))
581 (define result (car results))
582 (log-info "Download END in ~a seconds, URL:~a, result:~s"
583 (/ tm-real-ms 1000.0)
588 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
589 (define (timeline-download num-workers timeout peers)
591 (concurrent-filter-map num-workers
592 (λ (p) (cons p (peer-download timeout p)))
595 (filter-map (match-lambda
596 [(cons p (cons 'ok _)) p]
597 [(cons _ (cons 'error e)) #f])
600 (filter-map (match-lambda
601 [(cons _ (cons 'ok _))
603 [(cons p (cons 'error e))
604 (struct-copy Peer p [comment (format "~s" e)])])
606 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
607 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
609 (: uniq (∀ (α) (-> (Listof α) (Listof α))))
611 (set->list (list->set xs)))
613 (: peers->timeline (-> (listof Peer) (listof Msg)))
614 (define (peers->timeline peers)
615 (append* (filter-map peer->msgs peers)))
617 (: timeline-sort (-> (listof Msg) timeline-order (Listof Msgs)))
618 (define (timeline-sort msgs order)
619 (define cmp (match order
622 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
625 (: paths->peers (-> (Listof String) (Listof Peer)))
626 (define (paths->peers paths)
627 (let* ([paths (match paths
629 (let ([peer-refs-file (build-path tt-home-dir "peers")])
631 "No peer ref file paths provided, defaulting to ~v"
632 (path->string peer-refs-file))
633 (list peer-refs-file))]
635 (log-debug "Peer ref file paths provided: ~v" paths)
636 (map string->path paths)])]
637 [peers (append* (map file->peers paths))])
638 (log-info "Read-in ~a peers." (length peers))
641 (: mentioned-peers-in-cache (-> (Listof Peer)))
642 (define (mentioned-peers-in-cache)
644 (append* (map (λ (filename)
645 (define path (build-path cache-object-dir filename))
646 (define size (/ (file-size path) 1000000.0))
647 (log-info "BEGIN parsing ~a MB from file: ~v"
650 (define t0 (current-inexact-milliseconds))
651 (define m (filter-map
653 (str->msg #f (cache-object-filename->url filename) line))
655 (file->lines path))))
656 (define t1 (current-inexact-milliseconds))
657 (log-info "END parsing ~a MB in ~a seconds from file: ~v."
662 (log-warning "No messages found in ~a" (path->string path)))
664 (directory-list cache-object-dir))))
665 (uniq (append* (map Msg-mentions msgs))))
667 (: log-writer-stop (-> Thread Void))
668 (define (log-writer-stop log-writer)
669 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
670 (thread-wait log-writer))
672 (: log-writer-start (-> Log-Level Thread))
673 (define (log-writer-start level)
675 (make-logger #f #f level #f)]
677 (make-log-receiver logger level)]
682 ([date-display-format 'iso-8601])
684 (match-define (vector level msg _ topic) (sync log-receiver))
685 (unless (equal? topic 'stop)
686 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
688 (current-logger logger)
692 (let ([log-level 'info])
698 "Enable debug log level."
699 (set! log-level 'debug)]
702 "and <command> is one of"
703 "r, read : Read the timeline (offline operation)."
704 "d, download : Download the timeline."
705 ; TODO Add path dynamically
706 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
707 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
709 #:args (command . args)
710 (define log-writer (log-writer-start log-level))
711 (current-command-line-arguments (list->vector args))
714 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
715 ; started noticing significant slowdowns. Reducing to 5 seems to help.
716 (let ([num-workers 5]
723 njobs "Number of concurrent jobs."
724 (set! num-workers (string->number njobs))]
726 seconds "Timeout seconds per request."
727 (set! timeout (string->number seconds))]
729 (let ([peers (paths->peers file-paths)])
730 (define-values (_res _cpu real-ms _gc)
731 (time-apply timeline-download (list num-workers timeout peers)))
732 (log-info "Downloaded timelines from ~a peers in ~a seconds."
734 (/ real-ms 1000.0)))))]
740 (if (system (path->string (build-path tt-home-dir "upload")))
744 (let ([out-format 'multi-line]
753 "Reverse displayed timeline order."
754 (set! order 'new->old)]
756 m "Earliest time to display (ignore anything before it)."
757 (set! ts-min (rfc3339->epoch m))]
759 x "Latest time to display (ignore anything after it)."
760 (set! ts-max (rfc3339->epoch x))]
763 "Short output format"
764 (set! out-format 'single-line)]
767 (set! out-format 'multi-line)]
770 (paths->peers file-paths)]
772 (timeline-sort (peers->timeline peers) order)]
774 (filter (λ (m) (and (if ts-min (>= (Msg-ts-epoch m)
777 (if ts-max (<= (Msg-ts-epoch m)
781 (timeline-print out-format timeline))))]
788 (λ (peers) (sort peers (match-lambda**
789 [((Peer n1 _ _) (Peer n2 _ _))
790 (string<? (if n1 n1 "")
793 (build-path tt-home-dir "peers-all")]
794 [peers-mentioned-file
795 (build-path tt-home-dir "peers-mentioned")]
796 [peers-mentioned-curr
797 (mentioned-peers-in-cache)]
798 [peers-mentioned-prev
799 (file->peers peers-mentioned-file)]
801 (peers-sort (uniq (append peers-mentioned-prev
802 peers-mentioned-curr)))]
804 (file->peers peers-all-file)]
806 (list->set (append peers-mentioned
809 (set-subtract peers-all (list->set peers-all-prev))]
811 (peers-sort (set->list peers-all))])
812 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
813 (log-info "Known peers total: ~a" (length peers-all))
814 (log-info "Discovered ~a new peers:~n~a"
815 (set-count peers-discovered)
817 (λ (p) (cons (Peer-nick p)
818 (url->string (Peer-uri p))))
819 (set->list peers-discovered))))
820 (peers->file peers-mentioned
821 peers-mentioned-file)
822 (peers->file peers-all
825 (eprintf "Error: invalid command: ~v\n" command)
826 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
828 (log-writer-stop log-writer))))