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 α)
31 ([freq : Nonnegative-Integer]
32 [last : Nonnegative-Integer])
35 (define-type Nick-Hist
36 (Immutable-HashTable Url (Immutable-HashTable (Option String) Hist)))
40 [nick : (Option String)]))
55 [mentions : (Listof Peer)]))
58 ([nick : (Option String)]
61 [comment : (Option String)])
65 ([status-line : String]
66 [headers : (Listof Bytes)]
67 [body-input : Input-Port])
72 (Prog "tt" (info:#%info-lookup 'version)))
76 (User (string->url "https://github.com/xandkar/tt") #f))
78 (: user->str (-> User String))
79 (define (user->str user)
80 (match-define (User u0 n) user)
81 (define u (url->string u0))
83 (format "+~a; @~a" u n)
86 (: user-agent->str (-> User-Agent String))
87 (define (user-agent->str ua)
88 (match-define (User-Agent u p) ua)
89 (format "~a/~a (~a)" (Prog-name p) (Prog-version p) (user->str u)))
91 (: user->user-agent User)
92 (define (user->user-agent user)
93 (User-Agent user prog))
95 (: user-agent-str String)
96 (define user-agent-str
97 (user-agent->str (user->user-agent user-default)))
99 (: set-user-agent-str (-> Path-String Void))
100 (define (set-user-agent-str filename)
101 (set! user-agent-str (user-agent->str (user->user-agent (file->user filename))))
102 (log-info "User-Agent string is now set to: ~v" user-agent-str))
104 (: file->user (-> Path-String User))
105 (define (file->user filename)
106 (if (file-exists? filename)
107 (match (file->peers filename)
110 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
116 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
122 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
128 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
133 (: peer->user (-> Peer User))
134 (define (peer->user p)
135 (match-define (Peer n u _ _) p)
138 (: peers-equal? (-> Peer Peer Boolean))
139 (define (peers-equal? p1 p2)
140 (equal? (Peer-uri-str p1)
143 (: peer-hash (-> Peer Fixnum))
144 (define (peer-hash p)
145 (equal-hash-code (Peer-uri-str p)))
147 (define-custom-set-types peers
151 ; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
152 ; the following contract violations:
154 ; custom-elem-contents: contract violation
155 ; expected: custom-elem?
158 ; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
159 ; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
160 ; /usr/share/racket/collects/racket/cmdline.rkt:191:51
161 ; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
163 ; TODO Investigate why and make a minimal reproducible test case.
165 (: peers-merge (-> (Listof Peer) * (Listof Peer)))
166 (define (peers-merge . peer-sets)
170 (hash-update groups (Peer-uri-str p) (λ (group) (cons p group)) '()))
172 (append* peer-sets)))
173 (define (merge peers)
175 ['() (raise 'impossible)]
178 (let* ([n1 (Peer-nick p1)]
181 ; TODO Try to pick from nicks db: preferred, otherwise seen
182 [(and (not n1) (not n2)) p1] ; TODO update with most-common nick
183 [(and n1 n2 ) p1] ; TODO compare which is more-common
184 [(and n1 (not n2)) p1]
185 [(and (not n1) n2) p2]
187 (raise 'impossible)])])
188 (merge (cons p ps)))]))
189 (sort (map merge (hash-values groups))
191 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
194 (let* ([u1 "http://foo/bar"]
195 [u2 "http://baz/quux"]
196 [p1 (Peer #f (string->url u1) u1 #f)]
197 [p2 (Peer "a" (string->url u1) u1 #f)]
198 [p3 (Peer "b" (string->url u2) u2 #f)]
201 (check-equal? (list p3 p2) (peers-merge s1 s2))
202 (check-equal? (list p3 p2) (peers-merge s2 s1))))
204 (: tt-home-dir Path-String)
205 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
207 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
208 (define (concurrent-filter-map num-workers f xs)
209 ; TODO preserve order of elements OR communicate that reorder is expected
210 ; TODO switch from mailboxes to channels
211 (define (make-worker id f)
212 (define parent (current-thread))
214 (define self : Thread (current-thread))
215 (: work (∀ (α) (-> α)))
217 (thread-send parent (cons 'next self))
218 (match (thread-receive)
219 ['done (thread-send parent (cons 'exit id))]
220 [(cons 'unit x) (begin
222 (when y (thread-send parent (cons 'result y)))
225 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
226 (define (dispatch ws xs ys)
229 (match (thread-receive)
230 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
231 [(cons 'result y) (dispatch ws xs (cons y ys))]
232 [(cons 'next thd) (match xs
234 (thread-send thd 'done)
235 (dispatch ws xs ys))]
237 (thread-send thd (cons 'unit x))
238 (dispatch ws xs ys))])])))
239 (define workers (range num-workers))
240 (define threads (map (λ (id) (thread (make-worker id f))) workers))
241 (define results (dispatch workers xs '()))
242 (for-each thread-wait threads)
246 (let* ([f (λ (x) (if (even? x) x #f))]
248 [actual (sort (concurrent-filter-map 10 f xs) <)]
249 [expected (sort ( filter-map f xs) <)])
250 (check-equal? actual expected "concurrent-filter-map")))
252 (: msg-print (-> Out-Format Integer Msg Void))
254 (let* ([colors (vector 36 33)]
255 [n (vector-length colors)])
256 (λ (out-format color-i msg)
257 (let ([color (vector-ref colors (modulo color-i n))]
258 [nick (Peer-nick (Msg-from msg))]
259 [uri (Peer-uri-str (Msg-from msg))]
260 [text (Msg-text msg)])
263 (let ([nick (if nick nick uri)])
264 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
266 ([date-display-format 'iso-8601])
267 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
270 (let ([nick (if nick (string-append nick " ") "")])
271 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
273 ([date-display-format 'rfc2822])
274 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
276 nick uri color text))])))))
278 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
279 (define rfc3339->epoch
280 (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}))?$")])
282 (match (regexp-match re ts)
283 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
286 (match* (tz-whole tz-sign tz-HH tz-MM)
289 [(_ (or "-" "+") (? identity h) (? identity m))
290 (let ([h (string->number h)]
291 [m (string->number m)]
292 ; Reverse to get back to UTC:
293 [op (match tz-sign ["+" -] ["-" +])])
294 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
296 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
300 [ts-epoch (find-seconds (if SS (string->number SS) 0)
305 (string->number yyyy)
307 (+ ts-epoch tz-offset))]
309 (log-debug "Invalid timestamp: ~v" ts)
312 (: str->msg (-> Peer String (Option Msg)))
314 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
316 (define from-str (peer->str from))
317 (define str-head (substring str 0 (min 100 (string-length str))))
322 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
325 (match (regexp-match re str)
326 [(list _wholething ts-orig text)
327 (let ([ts-epoch (rfc3339->epoch ts-orig)])
331 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
332 [(list _wholething nick-uri)
333 (str->peer nick-uri)]))
334 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
335 (Msg ts-epoch ts-orig from text mentions))
338 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
342 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
346 ; TODO Test for when missing-nick case
347 (let* ([tzs (for*/list ([d '("-" "+")]
349 [m '("00" ":00" "57" ":57")])
350 (string-append d h m))]
351 [tzs (list* "" "Z" tzs)])
352 (for* ([n '("fake-nick")]
353 [u '("http://fake-uri")]
354 [p (list (Peer n (string->url u) u #f))]
358 [sep (list "\t" " ")]
359 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
360 (let* ([ts (string-append "2020-11-18T22:22"
361 (if (non-empty-string? s) s ":00")
363 [m (str->msg p (string-append ts sep txt))])
365 (check-equal? (Msg-from m) p)
366 (check-equal? (Msg-text m) txt)
367 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
370 (let* ([ts "2020-11-18T22:22:09-0500"]
375 [peer (Peer nick (string->url uri) uri #f)]
376 [actual (str->msg peer (string-append ts tab text))]
377 [expected (Msg 1605756129 ts peer text '())])
379 (Msg-ts-epoch actual)
380 (Msg-ts-epoch expected)
384 (Msg-ts-orig expected)
387 (Peer-nick (Msg-from actual))
388 (Peer-nick (Msg-from expected))
391 (Peer-uri (Msg-from actual))
392 (Peer-uri (Msg-from expected))
395 (Peer-uri-str (Msg-from actual))
396 (Peer-uri-str (Msg-from expected))
403 (: str->lines (-> String (Listof String)))
404 (define (str->lines str)
405 (string-split str (regexp "[\r\n]+")))
408 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
410 (: str->msgs (-> Peer String (Listof Msg)))
411 (define (str->msgs peer str)
412 (filter-map (λ (line) (str->msg peer line))
413 (filter-comments (str->lines str))))
415 (: cache-dir Path-String)
416 (define cache-dir (build-path tt-home-dir "cache"))
418 (define cache-object-dir (build-path cache-dir "objects"))
420 (: url->cache-file-path-v1 (-> Url Path-String))
421 (define (url->cache-file-path-v1 uri)
422 (define (hash-sha1 str) : (-> String String)
423 (define in (open-input-string str))
424 (define digest (sha1 in))
425 (close-input-port in)
427 (build-path cache-object-dir (hash-sha1 (url->string uri))))
429 (: url->cache-file-path-v2 (-> Url Path-String))
430 (define (url->cache-file-path-v2 uri)
431 (build-path cache-object-dir (uri-encode (url->string uri))))
433 (define url->cache-object-path
434 url->cache-file-path-v2)
436 (define (url->cache-etag-path uri)
437 (build-path cache-dir "etags" (uri-encode (url->string uri))))
439 (define (url->cache-lmod-path uri)
440 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
442 (: uri-read-cached (-> Url (Option String)))
443 (define (uri-read-cached uri)
444 (define path-v1 (url->cache-file-path-v1 uri))
445 (define path-v2 (url->cache-file-path-v2 uri))
446 (when (file-exists? path-v1)
447 (rename-file-or-directory path-v1 path-v2 #t))
448 (if (file-exists? path-v2)
449 (file->string path-v2)
451 (log-debug "Cache file not found for URI: ~a" (url->string uri))
454 (: str->url (-> String (Option String)))
457 ([exn:fail? (λ (e) #f)])
460 (: peer->str (-> Peer String))
461 (define (peer->str peer)
462 (match-define (Peer n _ u c) peer)
464 (if n (format "~a " n) "")
466 (if c (format " # ~a" c) "")))
468 (: str->peer (-> String (Option Peer)))
469 (define (str->peer str)
470 (log-debug "Parsing peer string: ~v" str)
473 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
481 (match (str->url url)
483 (log-error "Invalid URI in peer string: ~v" str)
486 (Peer nick url (url->string url) comment)])]
488 (log-debug "Invalid peer string: ~v" str)
493 (str->peer "foo http://bar/file.txt # some rando")
494 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
496 (str->peer "http://bar/file.txt # some rando")
497 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
499 (str->peer "http://bar/file.txt #")
500 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
502 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
503 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
505 (str->peer "http://bar/file.txt")
506 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
508 (str->peer "foo http://bar/file.txt")
509 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
511 (str->peer "foo bar # baz")
514 (str->peer "foo bar://baz # quux")
515 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
517 (str->peer "foo bar//baz # quux")
520 (: filter-comments (-> (Listof String) (Listof String)))
521 (define (filter-comments lines)
522 (filter-not (λ (line) (string-prefix? line "#")) lines))
524 (: str->peers (-> String (Listof Peer)))
525 (define (str->peers str)
526 (filter-map str->peer (filter-comments (str->lines str))))
528 (: peers->file (-> (Listof Peers) Path-String Void))
529 (define (peers->file peers path)
530 (display-lines-to-file
534 [((Peer n1 _ _ _) (Peer n2 _ _ _))
535 (string<? (if n1 n1 "")
540 (: file->peers (-> Path-String (Listof Peer)))
541 (define (file->peers file-path)
542 (if (file-exists? file-path)
543 (str->peers (file->string file-path))
545 (log-warning "File does not exist: ~v" (path->string file-path))
549 #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")
551 (: b->n (-> Bytes (Option Number)))
553 (string->number (bytes->string/utf-8 b)))
555 (: mon->num (-> Bytes Natural))
556 (define/match (mon->num mon)
570 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
571 (define (rfc2822->epoch timestamp)
572 (match (regexp-match re-rfc2822 timestamp)
573 [(list _ _ dd mo yyyy HH MM SS)
574 #:when (and dd mo yyyy HH MM SS)
575 (find-seconds (b->n SS)
585 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
586 (define (header-get headers name)
587 (match (filter-map (curry extract-field name) headers)
591 (: uri-download-from-port
592 (-> Url (Listof (U Bytes String)) Input-Port
593 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
594 (define (uri-download-from-port u headers body-input)
595 (define u-str (url->string u))
596 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
597 (define cached-object-path (url->cache-object-path u))
598 (define cached-etag-path (url->cache-etag-path u))
599 (define cached-lmod-path (url->cache-lmod-path u))
600 (define etag (header-get headers #"ETag"))
601 (define lmod (header-get headers #"Last-Modified"))
602 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
603 (define lmod-prev (if (file-exists? cached-lmod-path)
604 (rfc2822->epoch (file->bytes cached-lmod-path))
606 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
609 (file-exists? cached-etag-path)
610 (bytes=? etag (file->bytes cached-etag-path))
612 (log-debug "ETags match, skipping the rest of ~v" u-str)
616 (<= lmod-curr lmod-prev)
618 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
623 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
625 (make-parent-directory* cached-object-path)
626 (make-parent-directory* cached-etag-path)
627 (make-parent-directory* cached-lmod-path)
628 (call-with-output-file cached-object-path
629 (curry copy-port body-input)
632 (display-to-file etag cached-etag-path #:exists 'replace))
634 (display-to-file lmod cached-lmod-path #:exists 'replace))
639 (-> Positive-Float Url
640 (Result (U 'skipped-cached 'downloaded-new)
641 Any))) ; TODO Maybe more-precise error type?
642 (define (uri-download timeout u)
643 (define u-str (url->string u))
644 (define timeout-chan (make-channel))
645 (define result-chan (make-channel))
646 (define timeout-thread
648 ; Doing this instead of sync/timeout to distinguish error values,
649 ; rather than just have #f to work with.
651 (channel-put timeout-chan '(error . timeout)))))
652 (define result-thread
654 ; XXX We timeout getting a response, but body download could
655 ; also take a long time and we might want to time that out as
656 ; well, but then we may end-up with partially downloaded
657 ; objects. But that could happen anyway if the server drops the
658 ; connection for whatever reason.
660 ; Maybe that is OK once we start treating the
661 ; downloaded object as an addition to the stored set of
662 ; messages, rather than the final set of messages.
665 ; - 1st try can just be an in-memory set that gets written-to
666 ; and read-from disk as a whole.
669 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
671 (λ (e) `(error . (net-error . ,e)))]
673 (λ (e) `(error . (other . ,e)))])
674 (define-values (status-line headers body-input)
677 #:headers (list (format "User-Agent: ~a" user-agent-str))))
678 `(ok . ,(Resp status-line headers body-input))))
679 (channel-put result-chan result))))
683 (kill-thread result-thread)
684 (kill-thread timeout-thread)
688 [(cons 'ok (Resp status-line headers body-input))
689 (log-debug "headers: ~v" headers)
690 (log-debug "status-line: ~v" status-line)
692 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
693 (log-debug "status: ~v" status)
694 ; TODO Handle redirects. Should be within same timeout as req and body.
698 `(ok . ,(uri-download-from-port u headers body-input))]
700 `(error . (http . ,status))])])
701 (close-input-port body-input)
704 (: timeline-print (-> Out-Format (Listof Msg) Void))
705 (define (timeline-print out-format timeline)
710 (void (foldl (match-lambda**
711 [((and m (Msg _ _ from _ _)) (cons prev-from i))
712 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
713 (msg-print out-format i m)
715 (cons (Msg-from first-msg) 0)
718 (: peer->msgs (-> Peer (Listof Msg)))
719 (define (peer->msgs peer)
720 (match-define (Peer nick uri uri-str _) peer)
721 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
722 (define msgs-data (uri-read-cached uri))
725 (str->msgs peer msgs-data)
729 (-> Positive-Float Peer
730 (Result (U 'skipped-cached 'downloaded-new)
732 (define (peer-download timeout peer)
733 (match-define (Peer nick uri u _) peer)
734 (log-info "Download BEGIN URL:~a" u)
735 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
736 (time-apply uri-download (list timeout uri)))
737 (define result (car results))
738 (log-info "Download END in ~a seconds, URL:~a, result:~s"
739 (/ tm-real-ms 1000.0)
744 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
745 (define (timeline-download num-workers timeout peers)
747 (concurrent-filter-map num-workers
748 (λ (p) (cons p (peer-download timeout p)))
751 (filter-map (match-lambda
752 [(cons p (cons 'ok _)) p]
753 [(cons _ (cons 'error e)) #f])
756 (filter-map (match-lambda
757 [(cons _ (cons 'ok _))
759 [(cons p (cons 'error e))
760 (struct-copy Peer p [comment (format "~s" e)])])
762 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
763 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
765 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
766 (define (peers->timeline peers)
767 (append* (filter-map peer->msgs peers)))
769 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
770 (define (timeline-sort msgs order)
771 (define cmp (match order
774 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
777 (: paths->peers (-> (Listof String) (Listof Peer)))
778 (define (paths->peers paths)
779 (let* ([paths (match paths
781 (let ([peer-refs-file (build-path tt-home-dir "peers")])
783 "No peer ref file paths provided, defaulting to ~v"
784 (path->string peer-refs-file))
785 (list peer-refs-file))]
787 (log-debug "Peer ref file paths provided: ~v" paths)
788 (map string->path paths)])]
789 [peers (apply peers-merge (map file->peers paths))])
790 (log-info "Read-in ~a peers." (length peers))
793 (: cache-filename->peer (-> Path-String (Option Peer)))
794 (define (cache-filename->peer filename)
795 (define nick #f) ; TODO Look it up in the nick-db when it exists.
796 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
797 (match (str->url url-str)
799 [url (Peer nick url url-str #f)]))
801 (: peers-cached (-> (Listof Peer)))
802 (define (peers-cached)
804 (filter-map cache-filename->peer (directory-list cache-object-dir)))
806 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
807 (define (peers-mentioned msgs)
808 (append* (map Msg-mentions msgs)))
810 (: log-writer-stop (-> Thread Void))
811 (define (log-writer-stop log-writer)
812 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
813 (thread-wait log-writer))
815 (: log-writer-start (-> Log-Level Thread))
816 (define (log-writer-start level)
818 (make-logger #f #f level #f)]
820 (make-log-receiver logger level)]
825 ([date-display-format 'iso-8601])
827 (match-define (vector level msg _ topic) (sync log-receiver))
828 (unless (equal? topic 'stop)
829 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
831 (current-logger logger)
834 (: msgs->nick-hist (-> (Listof Msg) Nick-Hist))
835 (define (msgs->nick-hist msgs)
837 (λ (msg url->nick->hist)
838 (match-define (Msg curr _ from _ mentions) msg)
840 (λ (peer url->nick->hist)
841 (match-define (Peer nick url _ _) peer)
843 (hash-update url->nick->hist
846 (hash-update nick->hist
850 (Hist (+ 1 freq) (max prev curr))])
855 (cons from mentions)))
859 (: update-nicks-history (-> (Listof Msg) Void))
860 (define (update-nicks-history msgs)
862 (msgs->nick-hist msgs)
864 (define path (build-path tt-home-dir "nicks" "seen" (uri-encode (url->string url))))
865 (make-parent-directory* path)
866 (display-lines-to-file
868 [(cons nick (Hist freq last))
869 (format "~a ~a ~a" nick freq last)])
870 (sort (hash->list nick->hist)
872 [((cons _ (Hist a _)) (cons _ (Hist b _)))
875 #:exists 'replace))))
877 (: nick-hist-most-by (-> Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
878 (define (nick-hist-most-by url->nick->hist url by)
879 (match (hash-ref url->nick->hist url #f)
882 (match (sort (hash->list nick->hist)
883 (λ (a b) (> (by (cdr a))
886 [(cons (cons nick _) _) nick])]))
888 (: nick-hist-latest (-> Nick-Hist Url (Option String)))
889 (define (nick-hist-latest nick-hist url)
890 (nick-hist-most-by nick-hist url Hist-last))
892 (: nick-hist-common (-> Nick-Hist Url (Option String)))
893 (define (nick-hist-common nick-hist url)
894 (nick-hist-most-by nick-hist url Hist-freq))
897 (let* ([url-str "http://foo"]
898 [url (string->url url-str)]
902 [ts-str-1 "2021-11-29T23:29:08-0500"]
903 [ts-str-2 "2021-11-29T23:30:00-0500"]
904 [ts-1 (rfc3339->epoch ts-str-1)]
905 [ts-2 (rfc3339->epoch ts-str-2)]
909 (str->msg (str->peer "test http://test")
910 (string-append ts-str " Hi @<" nick " " url-str ">"))])
911 (list (cons ts-str-2 nick1)
912 (cons ts-str-1 nick2)
913 (cons ts-str-1 nick2)
914 (cons ts-str-1 nick3)
915 (cons ts-str-1 nick3)
916 (cons ts-str-1 nick3)))]
918 (msgs->nick-hist msgs)])
919 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
920 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
921 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
922 (check-equal? (nick-hist-common hist url) nick3)
923 (check-equal? (nick-hist-latest hist url) nick1)))
927 ; TODO Test the non-io parts of crawling
928 (let* ([peers-all-file
929 (build-path tt-home-dir "peers-all")]
930 [peers-mentioned-file
931 (build-path tt-home-dir "peers-mentioned")]
933 (build-path tt-home-dir "peers-parsed")]
935 (build-path tt-home-dir "peers-cached")]
939 (peers->timeline peers-cached)]
940 [peers-mentioned-curr
941 (peers-mentioned cached-timeline)]
942 [peers-mentioned-prev
943 (file->peers peers-mentioned-file)]
945 (file->peers peers-all-file)]
948 ; XXX Updating nicks before running peers-merge,
949 ; since peers-merge is expected to refer to it in the future.
950 (update-nicks-history cached-timeline)
951 (peers-merge peers-mentioned-prev
952 peers-mentioned-curr))]
954 (peers-merge peers-mentioned
958 (set->list (set-subtract (make-immutable-peers peers-all)
959 (make-immutable-peers peers-all-prev)))]
961 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
962 ; TODO Deeper de-duping
963 (log-info "Known peers cached ~a" (length peers-cached))
964 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
965 (log-info "Known peers parsed ~a" (length peers-parsed))
966 (log-info "Known peers total: ~a" (length peers-all))
967 (log-info "Discovered ~a new peers:~n~a"
968 (length peers-discovered)
971 [(Peer n _ u c) (list n u c)])
973 (peers->file peers-cached
975 (peers->file peers-mentioned
976 peers-mentioned-file)
977 (peers->file peers-parsed
979 (peers->file peers-all
982 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
983 (define (read file-paths ts-min ts-max order out-format)
985 (paths->peers file-paths)]
987 (timeline-sort (peers->timeline peers) order)]
990 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
991 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
992 (timeline-print out-format (filter include? msgs))))
996 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
997 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
1001 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
1002 (define (download file-paths num-workers timeout)
1003 (let ([peers (paths->peers file-paths)])
1004 (define-values (_res _cpu real-ms _gc)
1005 (time-apply timeline-download (list num-workers timeout peers)))
1006 (log-info "Downloaded timelines from ~a peers in ~a seconds."
1008 (/ real-ms 1000.0))))
1010 (: dispatch (-> String Void))
1011 (define (dispatch command)
1013 [(or "d" "download")
1014 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
1015 ; started noticing significant slowdowns. Reducing to 5 seems to help.
1016 (let ([num-workers 5]
1019 #:program "tt download"
1022 njobs "Number of concurrent jobs."
1023 (set! num-workers (string->number njobs))]
1025 seconds "Timeout seconds per request."
1026 (set! timeout (string->number seconds))]
1028 (download file-paths num-workers timeout)))]
1031 #:program "tt upload" #:args () (upload))]
1033 (let ([out-format 'multi-line]
1041 "Reverse displayed timeline order."
1042 (set! order 'new->old)]
1044 m "Earliest time to display (ignore anything before it)."
1045 (set! ts-min (rfc3339->epoch m))]
1047 x "Latest time to display (ignore anything after it)."
1048 (set! ts-max (rfc3339->epoch x))]
1051 "Short output format"
1052 (set! out-format 'single-line)]
1054 "Long output format"
1055 (set! out-format 'multi-line)]
1057 (read file-paths ts-min ts-max order out-format)))]
1060 #:program "tt crawl" #:args () (crawl))]
1062 (eprintf "Error: invalid command: ~v\n" command)
1063 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1067 (let ([log-level 'info])
1073 "Enable debug log level."
1074 (set! log-level 'debug)]
1077 "and <command> is one of"
1078 "r, read : Read the timeline (offline operation)."
1079 "d, download : Download the timeline."
1080 ; TODO Add path dynamically
1081 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
1082 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
1084 #:args (command . args)
1085 (define log-writer (log-writer-start log-level))
1086 (current-command-line-arguments (list->vector args))
1087 (set-user-agent-str (build-path tt-home-dir "me"))
1088 ; TODO dispatch should return status with which we should exit after cleanups
1090 (log-writer-stop log-writer))))