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-debug "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))))
285 (: uri-read-cached (-> Url (Option String)))
286 (define (uri-read-cached uri)
287 (define path-v1 (url->cache-file-path-v1 uri))
288 (define path-v2 (url->cache-file-path-v2 uri))
289 (when (file-exists? path-v1)
290 (rename-file-or-directory path-v1 path-v2 #t))
291 (if (file-exists? path-v2)
292 (file->string path-v2)
294 (log-debug "Cache file not found for URI: ~a" (url->string uri))
297 (: str->url (-> String (Option String)))
300 ([exn:fail? (λ (e) #f)])
303 (: str->peer (String (Option Peer)))
304 (define (str->peer str)
305 (log-debug "Parsing peer string: ~v" str)
308 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
316 (match (str->url url)
318 (log-error "Invalid URI in peer string: ~v" str)
320 [url (Peer nick url comment)])]
322 (log-debug "Invalid peer string: ~v" str)
327 (str->peer "foo http://bar/file.txt # some rando")
328 (Peer "foo" (str->url "http://bar/file.txt") "some rando"))
330 (str->peer "http://bar/file.txt # some rando")
331 (Peer #f (str->url "http://bar/file.txt") "some rando"))
333 (str->peer "http://bar/file.txt #")
334 (Peer #f (str->url "http://bar/file.txt") ""))
336 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
337 (Peer #f (str->url "http://bar/file.txt#") #f))
339 (str->peer "http://bar/file.txt")
340 (Peer #f (str->url "http://bar/file.txt") #f))
342 (str->peer "foo http://bar/file.txt")
343 (Peer "foo" (str->url "http://bar/file.txt") #f))
345 (str->peer "foo bar # baz")
348 (str->peer "foo bar://baz # quux")
349 (Peer "foo" (str->url "bar://baz") "quux"))
351 (str->peer "foo bar//baz # quux")
354 (: filter-comments (-> (Listof String) (Listof String)))
355 (define (filter-comments lines)
356 (filter-not (λ (line) (string-prefix? line "#")) lines))
358 (: str->peers (-> String (Listof Peer)))
359 (define (str->peers str)
360 (filter-map str->peer (filter-comments (str->lines str))))
362 (: peers->file (-> (Listof Peers) Path-String Void))
363 (define (peers->file peers path)
364 (display-lines-to-file
368 (if n (format "~a " n) "")
370 (if c (format " # ~a" c) ""))])
375 (: file->peers (-> Path-String (Listof Peer)))
376 (define (file->peers file-path)
377 (if (file-exists? file-path)
378 (str->peers (file->string file-path))
380 (log-warning "File does not exist: ~v" (path->string file-path))
384 #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")
386 (: b->n (-> Bytes (Option Number)))
388 (string->number (bytes->string/utf-8 b)))
390 (: mon->num (-> Bytes Natural))
391 (define/match (mon->num mon)
405 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
406 (define (rfc2822->epoch timestamp)
407 (match (regexp-match re-rfc2822 timestamp)
408 [(list _ _ dd mo yyyy HH MM SS)
409 #:when (and dd mo yyyy HH MM SS)
410 (find-seconds (b->n SS)
420 (: user-agent String)
424 [prog-version (info:#%info-lookup 'version)]
425 [prog-uri "https://github.com/xandkar/tt"]
426 [user-peer-file (build-path tt-home-dir "me")]
428 (if (file-exists? user-peer-file)
429 (match (first (file->peers user-peer-file))
430 [(Peer #f u _) (format "+~a" (url->string u) )]
431 [(Peer n u _) (format "+~a; @~a" (url->string u) n)])
432 (format "+~a" prog-uri))])
433 (format "~a/~a (~a)" prog-name prog-version user)))
435 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
436 (define (header-get headers name)
437 (match (filter-map (curry extract-field name) headers)
441 (: uri-download-from-port
442 (-> Url (Listof (U Bytes String)) Input-Port
443 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
444 (define (uri-download-from-port u headers body-input)
445 (define u-str (url->string u))
446 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
447 (define cached-object-path (url->cache-object-path u))
448 (define cached-etag-path (url->cache-etag-path u))
449 (define cached-lmod-path (url->cache-lmod-path u))
450 (define etag (header-get headers #"ETag"))
451 (define lmod (header-get headers #"Last-Modified"))
452 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
453 (define lmod-prev (if (file-exists? cached-lmod-path)
454 (rfc2822->epoch (file->bytes cached-lmod-path))
456 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
459 (file-exists? cached-etag-path)
460 (bytes=? etag (file->bytes cached-etag-path))
462 (log-debug "ETags match, skipping the rest of ~v" u-str)
466 (<= lmod-curr lmod-prev)
468 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
473 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
475 (make-parent-directory* cached-object-path)
476 (make-parent-directory* cached-etag-path)
477 (make-parent-directory* cached-lmod-path)
478 (call-with-output-file cached-object-path
479 (curry copy-port body-input)
482 (display-to-file etag cached-etag-path #:exists 'replace))
484 (display-to-file lmod cached-lmod-path #:exists 'replace))
489 (-> Positive-Float Url
490 (Result (U 'skipped-cached 'downloaded-new)
491 Any))) ; TODO Maybe more-precise error type?
492 (define (uri-download timeout u)
493 (define u-str (url->string u))
494 (define timeout-chan (make-channel))
495 (define result-chan (make-channel))
496 (define timeout-thread
498 ; Doing this instead of sync/timeout to distinguish error values,
499 ; rather than just have #f to work with.
501 (channel-put timeout-chan '(error . timeout)))))
502 (define result-thread
504 ; XXX We timeout getting a response, but body download could
505 ; also take a long time and we might want to time that out as
506 ; well, but then we may end-up with partially downloaded
507 ; objects. But that could happen anyway if the server drops the
508 ; connection for whatever reason.
510 ; Maybe that is OK once we start treating the
511 ; downloaded object as an addition to the stored set of
512 ; messages, rather than the final set of messages.
515 ; - 1st try can just be an in-memory set that gets written-to
516 ; and read-from disk as a whole.
519 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
521 (λ (e) `(error . (net-error . ,e)))]
523 (λ (e) `(error . (other . ,e)))])
524 (define-values (status-line headers body-input)
527 #:headers (list (format "User-Agent: ~a" user-agent))))
528 `(ok . ,(Resp status-line headers body-input))))
529 (channel-put result-chan result))))
533 (kill-thread result-thread)
534 (kill-thread timeout-thread)
538 [(cons 'ok (Resp status-line headers body-input))
539 (log-debug "headers: ~v" headers)
540 (log-debug "status-line: ~v" status-line)
542 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
543 (log-debug "status: ~v" status)
544 ; TODO Handle redirects. Should be within same timeout as req and body.
548 `(ok . ,(uri-download-from-port u headers body-input))]
550 `(error . (http . ,status))])])
551 (close-input-port body-input)
554 (: timeline-print (-> Out-Format (Listof Msg) Void))
555 (define (timeline-print out-format timeline)
556 (void (foldl (match-lambda**
557 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
558 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
559 (msg-print out-format i m)
564 (: peer->msgs (-> Peer (Listof Msg)))
565 (define (peer->msgs peer)
566 (match-define (Peer nick uri _) peer)
567 (log-debug "Reading peer nick:~v uri:~v" nick (url->string uri))
568 (define msgs-data (uri-read-cached uri))
571 (str->msgs nick uri msgs-data)
575 (-> Positive-Float Peer
576 (Result (U 'skipped-cached 'downloaded-new)
578 (define (peer-download timeout peer)
579 (match-define (Peer nick uri _) peer)
580 (define u (url->string uri))
581 (log-info "Download BEGIN URL:~a" u)
582 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
583 (time-apply uri-download (list timeout uri)))
584 (define result (car results))
585 (log-info "Download END in ~a seconds, URL:~a, result:~s"
586 (/ tm-real-ms 1000.0)
591 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
592 (define (timeline-download num-workers timeout peers)
594 (concurrent-filter-map num-workers
595 (λ (p) (cons p (peer-download timeout p)))
598 (filter-map (match-lambda
599 [(cons p (cons 'ok _)) p]
600 [(cons _ (cons 'error e)) #f])
603 (filter-map (match-lambda
604 [(cons _ (cons 'ok _))
606 [(cons p (cons 'error e))
607 (struct-copy Peer p [comment (format "~s" e)])])
609 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
610 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
612 (: uniq (∀ (α) (-> (Listof α) (Listof α))))
614 (set->list (list->set xs)))
616 (: peers->timeline (-> (listof Peer) (listof Msg)))
617 (define (peers->timeline peers)
618 (append* (filter-map peer->msgs peers)))
620 (: timeline-sort (-> (listof Msg) timeline-order (Listof Msgs)))
621 (define (timeline-sort msgs order)
622 (define cmp (match order
625 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
628 (: paths->peers (-> (Listof String) (Listof Peer)))
629 (define (paths->peers paths)
630 (let* ([paths (match paths
632 (let ([peer-refs-file (build-path tt-home-dir "peers")])
634 "No peer ref file paths provided, defaulting to ~v"
635 (path->string peer-refs-file))
636 (list peer-refs-file))]
638 (log-debug "Peer ref file paths provided: ~v" paths)
639 (map string->path paths)])]
640 [peers (append* (map file->peers paths))])
641 (log-info "Read-in ~a peers." (length peers))
644 (: mentioned-peers-in-cache (-> (Listof Peer)))
645 (define (mentioned-peers-in-cache)
648 (append* (map (λ (filename)
649 (define path (build-path cache-object-dir filename))
650 (define size (/ (file-size path) 1000000.0))
651 (log-debug "BEGIN parsing ~a MB from file: ~v"
654 (define t0 (current-inexact-milliseconds))
655 (define m (filter-map
657 (str->msg #f (cache-object-filename->url filename) line))
659 (file->lines path))))
660 (define t1 (current-inexact-milliseconds))
661 (log-debug "END parsing ~a MB in ~a seconds from file: ~v."
666 (log-debug "No messages found in ~a" (path->string path)))
668 (directory-list cache-object-dir))))
669 (uniq (append* (map Msg-mentions msgs))))
671 (: log-writer-stop (-> Thread Void))
672 (define (log-writer-stop log-writer)
673 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
674 (thread-wait log-writer))
676 (: log-writer-start (-> Log-Level Thread))
677 (define (log-writer-start level)
679 (make-logger #f #f level #f)]
681 (make-log-receiver logger level)]
686 ([date-display-format 'iso-8601])
688 (match-define (vector level msg _ topic) (sync log-receiver))
689 (unless (equal? topic 'stop)
690 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
692 (current-logger logger)
696 (let ([log-level 'info])
702 "Enable debug log level."
703 (set! log-level 'debug)]
706 "and <command> is one of"
707 "r, read : Read the timeline (offline operation)."
708 "d, download : Download the timeline."
709 ; TODO Add path dynamically
710 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
711 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
713 #:args (command . args)
714 (define log-writer (log-writer-start log-level))
715 (current-command-line-arguments (list->vector args))
718 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
719 ; started noticing significant slowdowns. Reducing to 5 seems to help.
720 (let ([num-workers 5]
727 njobs "Number of concurrent jobs."
728 (set! num-workers (string->number njobs))]
730 seconds "Timeout seconds per request."
731 (set! timeout (string->number seconds))]
733 (let ([peers (paths->peers file-paths)])
734 (define-values (_res _cpu real-ms _gc)
735 (time-apply timeline-download (list num-workers timeout peers)))
736 (log-info "Downloaded timelines from ~a peers in ~a seconds."
738 (/ real-ms 1000.0)))))]
744 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
748 (let ([out-format 'multi-line]
757 "Reverse displayed timeline order."
758 (set! order 'new->old)]
760 m "Earliest time to display (ignore anything before it)."
761 (set! ts-min (rfc3339->epoch m))]
763 x "Latest time to display (ignore anything after it)."
764 (set! ts-max (rfc3339->epoch x))]
767 "Short output format"
768 (set! out-format 'single-line)]
771 (set! out-format 'multi-line)]
774 (paths->peers file-paths)]
776 (timeline-sort (peers->timeline peers) order)]
778 (filter (λ (m) (and (if ts-min (>= (Msg-ts-epoch m)
781 (if ts-max (<= (Msg-ts-epoch m)
785 (timeline-print out-format timeline))))]
792 (λ (peers) (sort peers (match-lambda**
793 [((Peer n1 _ _) (Peer n2 _ _))
794 (string<? (if n1 n1 "")
797 (build-path tt-home-dir "peers-all")]
798 [peers-mentioned-file
799 (build-path tt-home-dir "peers-mentioned")]
801 (build-path tt-home-dir "peers-parsed")]
802 [peers-mentioned-curr
803 (mentioned-peers-in-cache)]
804 [peers-mentioned-prev
805 (file->peers peers-mentioned-file)]
807 (peers-sort (uniq (append peers-mentioned-prev
808 peers-mentioned-curr)))]
810 (file->peers peers-all-file)]
812 (list->set (append peers-mentioned
815 (set-subtract peers-all (list->set peers-all-prev))]
817 (peers-sort (set->list peers-all))]
820 (λ (p) (< 0 (length (peer->msgs p))))
822 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
823 (log-info "Known peers parsed ~a" (length peers-parsed))
824 (log-info "Known peers total: ~a" (length peers-all))
825 (log-info "Discovered ~a new peers:~n~a"
826 (set-count peers-discovered)
828 (λ (p) (cons (Peer-nick p)
829 (url->string (Peer-uri p))))
830 (set->list peers-discovered))))
831 (peers->file peers-mentioned
832 peers-mentioned-file)
833 (peers->file peers-parsed
835 (peers->file peers-all
838 (eprintf "Error: invalid command: ~v\n" command)
839 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
841 (log-writer-stop log-writer))))