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)]
44 ([status-line : String]
45 [headers : (Listof Bytes)]
46 [body-input : Input-Port])
49 (: tt-home-dir Path-String)
50 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
52 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
53 (define (concurrent-filter-map num-workers f xs)
54 ; TODO preserve order of elements OR communicate that reorder is expected
55 ; TODO switch from mailboxes to channels
56 (define (make-worker id f)
57 (define parent (current-thread))
59 (define self : Thread (current-thread))
60 (: work (∀ (α) (-> α)))
62 (thread-send parent (cons 'next self))
63 (match (thread-receive)
64 ['done (thread-send parent (cons 'exit id))]
65 [(cons 'unit x) (begin
67 (when y (thread-send parent (cons 'result y)))
70 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
71 (define (dispatch ws xs ys)
74 (match (thread-receive)
75 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
76 [(cons 'result y) (dispatch ws xs (cons y ys))]
77 [(cons 'next thd) (match xs
79 (thread-send thd 'done)
82 (thread-send thd (cons 'unit x))
83 (dispatch ws xs ys))])])))
84 (define workers (range num-workers))
85 (define threads (map (λ (id) (thread (make-worker id f))) workers))
86 (define results (dispatch workers xs '()))
87 (for-each thread-wait threads)
91 (let* ([f (λ (x) (if (even? x) x #f))]
93 [actual (sort (concurrent-filter-map 10 f xs) <)]
94 [expected (sort ( filter-map f xs) <)])
95 (check-equal? actual expected "concurrent-filter-map")))
97 (: msg-print (-> Out-Format Integer Msg Void))
99 (let* ([colors (vector 36 33)]
100 [n (vector-length colors)])
101 (λ (out-format color-i msg)
102 (let ([color (vector-ref colors (modulo color-i n))]
103 [nick (Msg-nick msg)]
104 [uri (url->string (Msg-uri msg))]
105 [text (Msg-text msg)]
106 [mentions (Msg-mentions msg)])
109 (let ([nick (if nick nick uri)])
110 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
112 ([date-display-format 'iso-8601])
113 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
116 (let ([nick (if nick (string-append nick " ") "")])
117 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
119 ([date-display-format 'rfc2822])
120 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
122 nick uri color text))])))))
124 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
125 (define rfc3339->epoch
126 (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}))?$")])
128 (match (regexp-match re ts)
129 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
132 (match* (tz-whole tz-sign tz-HH tz-MM)
135 [(_ (or "-" "+") (? identity h) (? identity m))
136 (let ([h (string->number h)]
137 [m (string->number m)]
138 ; Reverse to get back to UTC:
139 [op (match tz-sign ["+" -] ["-" +])])
140 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
142 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
146 [ts-epoch (find-seconds (if SS (string->number SS) 0)
151 (string->number yyyy)
153 (+ ts-epoch tz-offset))]
155 (log-error "Invalid timestamp: ~v" ts)
158 (: str->msg (-> (Option String) Url String (Option Msg)))
160 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
162 (define str-head (substring str 0 (min 100 (string-length str))))
167 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
168 str-head nick (url->string uri) e)
170 (match (regexp-match re str)
171 [(list _wholething ts-orig text)
172 (let ([ts-epoch (rfc3339->epoch ts-orig)])
176 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
177 [(list _wholething nick-uri)
178 (str->peer nick-uri)]))
179 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
180 (Msg ts-epoch ts-orig nick uri text mentions))
183 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
184 str-head nick (url->string uri))
187 (log-debug "Non-msg line from nick:~v, line:~a" nick str-head)
191 ; TODO Test for when missing-nick case
192 (let* ([tzs (for*/list ([d '("-" "+")]
194 [m '("00" ":00" "57" ":57")])
195 (string-append d h m))]
196 [tzs (list* "" "Z" tzs)])
197 (for* ([n '("fake-nick")]
202 [sep (list "\t" " ")]
203 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
204 (let* ([ts (string-append "2020-11-18T22:22"
205 (if (non-empty-string? s) s ":00")
207 [m (str->msg n u (string-append ts sep txt))])
209 (check-equal? (Msg-nick m) n)
210 (check-equal? (Msg-uri m) u)
211 (check-equal? (Msg-text m) txt)
212 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
215 (let* ([ts "2020-11-18T22:22:09-0500"]
220 [actual (str->msg nick uri (string-append ts tab text))]
221 [expected (Msg 1605756129 ts nick uri text '())])
223 (Msg-ts-epoch actual)
224 (Msg-ts-epoch expected)
228 (Msg-ts-orig expected)
243 (: str->lines (-> String (Listof String)))
244 (define (str->lines str)
245 (string-split str (regexp "[\r\n]+")))
248 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
250 (: str->msgs (-> (Option String) Url String (Listof Msg)))
251 (define (str->msgs nick uri str)
252 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
254 (: cache-dir Path-String)
255 (define cache-dir (build-path tt-home-dir "cache"))
257 (define cache-object-dir (build-path cache-dir "objects"))
259 (: url->cache-file-path-v1 (-> Url Path-String))
260 (define (url->cache-file-path-v1 uri)
261 (define (hash-sha1 str) : (-> String String)
262 (define in (open-input-string str))
263 (define digest (sha1 in))
264 (close-input-port in)
266 (build-path cache-object-dir (hash-sha1 (url->string uri))))
268 (: url->cache-file-path-v2 (-> Url Path-String))
269 (define (url->cache-file-path-v2 uri)
270 (build-path cache-object-dir (uri-encode (url->string uri))))
272 (define url->cache-object-path url->cache-file-path-v2)
274 (: cache-object-filename->url (-> Path-String Url))
275 (define (cache-object-filename->url name)
276 (string->url (uri-decode (path->string name))))
278 (define (url->cache-etag-path uri)
279 (build-path cache-dir "etags" (uri-encode (url->string uri))))
281 (define (url->cache-lmod-path uri)
282 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
285 (: uri-read-cached (-> Url 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-warning "Cache file not found for URI: ~a" (url->string uri))
297 (: uri? (-> String Boolean))
299 (regexp-match? #rx"^[a-z]+://.*" (string-downcase str)))
301 (: str->peer (String (Option Peer)))
302 (define (str->peer str)
303 (log-debug "Parsing peer string: ~v" str)
307 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
309 (match (string-split str)
310 [(list u) #:when (uri? u) (Peer #f (string->url u))]
311 [(list n u) #:when (uri? u) (Peer n (string->url u))]
313 (log-error "Invalid peer string: ~v" str)
317 (: filter-comments (-> (Listof String) (Listof String)))
318 (define (filter-comments lines)
319 (filter-not (λ (line) (string-prefix? line "#")) lines))
321 (: str->peers (-> String (Listof Peer)))
322 (define (str->peers str)
323 (filter-map str->peer (filter-comments (str->lines str))))
325 (: peers->file (-> (Listof Peers) Path-String Void))
326 (define (peers->file peers path)
327 (display-lines-to-file
330 (format "~a~a" (if n (format "~a " n) "") (url->string u))])
335 (: file->peers (-> Path-String (Listof Peer)))
336 (define (file->peers file-path)
337 (if (file-exists? file-path)
338 (str->peers (file->string file-path))
340 (log-warning "File does not exist: ~v" (path->string file-path))
344 #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")
346 (: b->n (-> Bytes (Option Number)))
348 (string->number (bytes->string/utf-8 b)))
350 (: mon->num (-> Bytes Natural))
351 (define/match (mon->num mon)
365 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
366 (define (rfc2822->epoch timestamp)
367 (match (regexp-match re-rfc2822 timestamp)
368 [(list _ _ dd mo yyyy HH MM SS)
369 #:when (and dd mo yyyy HH MM SS)
370 (find-seconds (b->n SS)
380 (: user-agent String)
384 [prog-version (info:#%info-lookup 'version)]
385 [prog-uri "https://github.com/xandkar/tt"]
386 [user-peer-file (build-path tt-home-dir "me")]
388 (if (file-exists? user-peer-file)
389 (match (first (file->peers user-peer-file))
390 [(Peer #f u) (format "+~a" (url->string u) )]
391 [(Peer n u) (format "+~a; @~a" (url->string u) n)])
392 (format "+~a" prog-uri))])
393 (format "~a/~a (~a)" prog-name prog-version user)))
395 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
396 (define (header-get headers name)
397 (match (filter-map (curry extract-field name) headers)
401 (: uri-download-from-port
402 (-> Url (Listof (U Bytes String)) Input-Port
403 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
404 (define (uri-download-from-port u headers body-input)
405 (define u-str (url->string u))
406 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
407 (define cached-object-path (url->cache-object-path u))
408 (define cached-etag-path (url->cache-etag-path u))
409 (define cached-lmod-path (url->cache-lmod-path u))
410 (define etag (header-get headers #"ETag"))
411 (define lmod (header-get headers #"Last-Modified"))
412 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
413 (define lmod-prev (if (file-exists? cached-lmod-path)
414 (rfc2822->epoch (file->bytes cached-lmod-path))
416 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
419 (file-exists? cached-etag-path)
420 (bytes=? etag (file->bytes cached-etag-path))
422 (log-debug "ETags match, skipping the rest of ~v" u-str)
426 (<= lmod-curr lmod-prev)
428 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
433 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
435 (make-parent-directory* cached-object-path)
436 (make-parent-directory* cached-etag-path)
437 (make-parent-directory* cached-lmod-path)
438 (call-with-output-file cached-object-path
439 (curry copy-port body-input)
442 (display-to-file etag cached-etag-path #:exists 'replace))
444 (display-to-file lmod cached-lmod-path #:exists 'replace))
449 (-> Positive-Float Url
450 (Result (U 'skipped-cached 'downloaded-new)
451 Any))) ; TODO Maybe more-precise error type?
452 (define (uri-download timeout u)
453 (define u-str (url->string u))
454 (define timeout-chan (make-channel))
455 (define result-chan (make-channel))
456 (define timeout-thread
458 ; Doing this instead of sync/timeout to distinguish error values,
459 ; rather than just have #f to work with.
461 (channel-put timeout-chan '(error . timeout)))))
462 (define result-thread
464 ; XXX We timeout getting a response, but body download could
465 ; also take a long time and we might want to time that out as
466 ; well, but then we may end-up with partially downloaded
467 ; objects. But that could happen anyway if the server drops the
468 ; connection for whatever reason.
470 ; Maybe that is OK once we start treating the
471 ; downloaded object as an addition to the stored set of
472 ; messages, rather than the final set of messages.
475 ; - 1st try can just be an in-memory set that gets written-to
476 ; and read-from disk as a whole.
479 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
481 (λ (e) `(error . (net-error . ,e)))]
483 (λ (e) `(error . (other . ,e)))])
484 (define-values (status-line headers body-input)
487 #:headers (list (format "User-Agent: ~a" user-agent))))
488 `(ok . ,(Resp status-line headers body-input))))
489 (channel-put result-chan result))))
493 (kill-thread result-thread)
494 (kill-thread timeout-thread)
498 [(cons 'ok (Resp status-line headers body-input))
499 (log-debug "headers: ~v" headers)
500 (log-debug "status-line: ~v" status-line)
502 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
503 (log-debug "status: ~v" status)
504 ; TODO Handle redirects. Should be within same timeout as req and body.
508 `(ok . ,(uri-download-from-port u headers body-input))]
510 `(error . (http . ,status))])])
511 (close-input-port body-input)
514 (: timeline-print (-> Out-Format (Listof Msg) Void))
515 (define (timeline-print out-format timeline)
516 (void (foldl (match-lambda**
517 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
518 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
519 (msg-print out-format i m)
524 (: peer->msgs (-> Peer (Listof Msg)))
525 (define (peer->msgs f)
526 (match-define (Peer nick uri) f)
527 (log-info "Reading peer nick:~v uri:~v" nick (url->string uri))
528 (str->msgs nick uri (uri-read-cached uri)))
531 (-> Positive-Float Peer
532 (Result (U 'skipped-cached 'downloaded-new)
534 (define (peer-download timeout peer)
535 (match-define (Peer nick uri) peer)
536 (define u (url->string uri))
537 (log-info "Download BEGIN URL:~a" u)
538 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
539 (time-apply uri-download (list timeout uri)))
540 (define result (car results))
541 (log-info "Download END in ~a seconds, URL:~a, result:~s"
542 (/ tm-real-ms 1000.0)
547 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
548 (define (timeline-download num-workers timeout peers)
550 (concurrent-filter-map num-workers
551 (λ (p) (cons p (peer-download timeout p)))
553 (define ok? (match-lambda
554 [(cons _ (cons 'ok _)) #t]
555 [(cons _ (cons 'error _)) #f]))
556 (define (err? r) (not (ok? r)))
557 (define peers-ok (map car (filter ok? results)))
558 (define peers-err (map car (filter err? results)))
559 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
560 ; TODO Append error as a comment: <nick> <uri> # <error>
561 ; TODO Support inline/trailing comments in peer files
562 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
564 (: uniq (∀ (α) (-> (Listof α) (Listof α))))
566 (set->list (list->set xs)))
568 (: peers->timeline (-> (listof Peer) (listof Msg)))
569 (define (peers->timeline peers)
570 (append* (filter-map peer->msgs peers)))
572 (: timeline-sort (-> (listof Msg) timeline-order (Listof Msgs)))
573 (define (timeline-sort msgs order)
574 (define cmp (match order
577 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
580 (: paths->peers (-> (Listof String) (Listof Peer)))
581 (define (paths->peers paths)
582 (let* ([paths (match paths
584 (let ([peer-refs-file (build-path tt-home-dir "peers")])
586 "No peer ref file paths provided, defaulting to ~v"
587 (path->string peer-refs-file))
588 (list peer-refs-file))]
590 (log-debug "Peer ref file paths provided: ~v" paths)
591 (map string->path paths)])]
592 [peers (append* (map file->peers paths))])
593 (log-info "Read-in ~a peers." (length peers))
596 (: mentioned-peers-in-cache (-> (Listof Peer)))
597 (define (mentioned-peers-in-cache)
599 (append* (map (λ (filename)
600 (define path (build-path cache-object-dir filename))
601 (define size (/ (file-size path) 1000000.0))
602 (log-info "BEGIN parsing ~a MB from file: ~v"
605 (define t0 (current-inexact-milliseconds))
606 (define m (filter-map
608 (str->msg #f (cache-object-filename->url filename) line))
610 (file->lines path))))
611 (define t1 (current-inexact-milliseconds))
612 (log-info "END parsing ~a MB in ~a seconds from file: ~v."
617 (log-warning "No messages found in ~a" (path->string path)))
619 (directory-list cache-object-dir))))
620 (uniq (append* (map Msg-mentions msgs))))
622 (: log-writer-stop (-> Thread Void))
623 (define (log-writer-stop log-writer)
624 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
625 (thread-wait log-writer))
627 (: log-writer-start (-> Log-Level Thread))
628 (define (log-writer-start level)
630 (make-logger #f #f level #f)]
632 (make-log-receiver logger level)]
637 ([date-display-format 'iso-8601])
639 (match-define (vector level msg _ topic) (sync log-receiver))
640 (unless (equal? topic 'stop)
641 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
643 (current-logger logger)
647 (let ([log-level 'info])
653 "Enable debug log level."
654 (set! log-level 'debug)]
657 "and <command> is one of"
658 "r, read : Read the timeline (offline operation)."
659 "d, download : Download the timeline."
660 ; TODO Add path dynamically
661 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
662 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
664 #:args (command . args)
665 (define log-writer (log-writer-start log-level))
666 (current-command-line-arguments (list->vector args))
669 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
670 ; started noticing significant slowdowns. Reducing to 5 seems to help.
671 (let ([num-workers 5]
678 njobs "Number of concurrent jobs."
679 (set! num-workers (string->number njobs))]
681 seconds "Timeout seconds per request."
682 (set! timeout (string->number seconds))]
684 (let ([peers (paths->peers file-paths)])
685 (define-values (_res _cpu real-ms _gc)
686 (time-apply timeline-download (list num-workers timeout peers)))
687 (log-info "Downloaded timelines from ~a peers in ~a seconds."
689 (/ real-ms 1000.0)))))]
695 (if (system (path->string (build-path tt-home-dir "upload")))
699 (let ([out-format 'multi-line]
708 "Reverse displayed timeline order."
709 (set! order 'new->old)]
711 m "Earliest time to display (ignore anything before it)."
712 (set! ts-min (rfc3339->epoch m))]
714 x "Latest time to display (ignore anything after it)."
715 (set! ts-max (rfc3339->epoch x))]
718 "Short output format"
719 (set! out-format 'single-line)]
722 (set! out-format 'multi-line)]
725 (paths->peers file-paths)]
727 (timeline-sort (peers->timeline peers) order)]
729 (filter (λ (m) (and (if ts-min (>= (Msg-ts-epoch m)
732 (if ts-max (<= (Msg-ts-epoch m)
736 (timeline-print out-format timeline))))]
743 (λ (peers) (sort peers (match-lambda**
744 [((Peer n1 _) (Peer n2 _))
745 (string<? (if n1 n1 "")
748 (build-path tt-home-dir "peers-all")]
749 [peers-mentioned-file
750 (build-path tt-home-dir "peers-mentioned")]
751 [peers-mentioned-curr
752 (mentioned-peers-in-cache)]
753 [peers-mentioned-prev
754 (file->peers peers-mentioned-file)]
756 (peers-sort (uniq (append peers-mentioned-prev
757 peers-mentioned-curr)))]
759 (file->peers peers-all-file)]
761 (list->set (append peers-mentioned
764 (set-subtract peers-all (list->set peers-all-prev))]
766 (peers-sort (set->list peers-all))])
767 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
768 (log-info "Known peers total: ~a" (length peers-all))
769 (log-info "Discovered ~a new peers:~n~a"
770 (set-count peers-discovered)
772 (λ (p) (cons (Peer-nick p)
773 (url->string (Peer-uri p))))
774 (set->list peers-discovered))))
775 (peers->file peers-mentioned
776 peers-mentioned-file)
777 (peers->file peers-all
780 (eprintf "Error: invalid command: ~v\n" command)
781 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
783 (log-writer-stop log-writer))))