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)])
66 (Prog "tt" (info:#%info-lookup 'version)))
70 (User (string->url "https://github.com/xandkar/tt") #f))
72 (: user->str (-> User String))
73 (define (user->str user)
74 (match-define (User u0 n) user)
75 (define u (url->string u0))
77 (format "+~a; @~a" u n)
80 (: user-agent->str (-> User-Agent String))
81 (define (user-agent->str ua)
82 (match-define (User-Agent u p) ua)
83 (format "~a/~a (~a)" (Prog-name p) (Prog-version p) (user->str u)))
85 (: user->user-agent User)
86 (define (user->user-agent user)
87 (User-Agent user prog))
89 (: user-agent-str String)
90 (define user-agent-str
91 (user-agent->str (user->user-agent user-default)))
93 (: set-user-agent-str (-> Path-String Void))
94 (define (set-user-agent-str filename)
95 (set! user-agent-str (user-agent->str (user->user-agent (file->user filename))))
96 (log-info "User-Agent string is now set to: ~v" user-agent-str))
98 (: file->user (-> Path-String User))
99 (define (file->user filename)
100 (if (file-exists? filename)
101 (match (file->peers filename)
104 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
110 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
116 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
122 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
127 (: peer->user (-> Peer User))
128 (define (peer->user p)
129 (match-define (Peer n u _ _) p)
132 (: peers-equal? (-> Peer Peer Boolean))
133 (define (peers-equal? p1 p2)
134 (equal? (Peer-uri-str p1)
137 (: peer-hash (-> Peer Fixnum))
138 (define (peer-hash p)
139 (equal-hash-code (Peer-uri-str p)))
141 (define-custom-set-types peers
145 ; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
146 ; the following contract violations:
148 ; custom-elem-contents: contract violation
149 ; expected: custom-elem?
152 ; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
153 ; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
154 ; /usr/share/racket/collects/racket/cmdline.rkt:191:51
155 ; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
157 ; TODO Investigate why and make a minimal reproducible test case.
159 (: peers-merge (-> (Listof Peer) * (Listof Peer)))
160 (define (peers-merge . peer-sets)
164 (hash-update groups (Peer-uri-str p) (λ (group) (cons p group)) '()))
166 (append* peer-sets)))
167 (define (merge peers)
169 ['() (raise 'impossible)]
172 (let* ([n1 (Peer-nick p1)]
175 ; TODO Try to pick from nicks db: preferred, otherwise seen
176 [(and (not n1) (not n2)) p1] ; TODO update with most-common nick
177 [(and n1 n2 ) p1] ; TODO compare which is more-common
178 [(and n1 (not n2)) p1]
179 [(and (not n1) n2) p2]
181 (raise 'impossible)])])
182 (merge (cons p ps)))]))
183 (sort (map merge (hash-values groups))
185 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
188 (let* ([u1 "http://foo/bar"]
189 [u2 "http://baz/quux"]
190 [p1 (Peer #f (string->url u1) u1 #f)]
191 [p2 (Peer "a" (string->url u1) u1 #f)]
192 [p3 (Peer "b" (string->url u2) u2 #f)]
195 (check-equal? (list p3 p2) (peers-merge s1 s2))
196 (check-equal? (list p3 p2) (peers-merge s2 s1))))
198 (: tt-home-dir Path-String)
199 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
201 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
202 (define (concurrent-filter-map num-workers f xs)
203 ; TODO preserve order of elements OR communicate that reorder is expected
204 ; TODO switch from mailboxes to channels
205 (define (make-worker id f)
206 (define parent (current-thread))
208 (define self : Thread (current-thread))
209 (: work (∀ (α) (-> α)))
211 (thread-send parent (cons 'next self))
212 (match (thread-receive)
213 ['done (thread-send parent (cons 'exit id))]
214 [(cons 'unit x) (begin
216 (when y (thread-send parent (cons 'result y)))
219 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
220 (define (dispatch ws xs ys)
223 (match (thread-receive)
224 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
225 [(cons 'result y) (dispatch ws xs (cons y ys))]
226 [(cons 'next thd) (match xs
228 (thread-send thd 'done)
229 (dispatch ws xs ys))]
231 (thread-send thd (cons 'unit x))
232 (dispatch ws xs ys))])])))
233 (define workers (range num-workers))
234 (define threads (map (λ (id) (thread (make-worker id f))) workers))
235 (define results (dispatch workers xs '()))
236 (for-each thread-wait threads)
240 (let* ([f (λ (x) (if (even? x) x #f))]
242 [actual (sort (concurrent-filter-map 10 f xs) <)]
243 [expected (sort ( filter-map f xs) <)])
244 (check-equal? actual expected "concurrent-filter-map")))
246 (: msg-print (-> Out-Format Integer Msg Void))
248 (let* ([colors (vector 36 33)]
249 [n (vector-length colors)])
250 (λ (out-format color-i msg)
251 (let ([color (vector-ref colors (modulo color-i n))]
252 [nick (Peer-nick (Msg-from msg))]
253 [uri (Peer-uri-str (Msg-from msg))]
254 [text (Msg-text msg)])
257 (let ([nick (if nick nick uri)])
258 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
260 ([date-display-format 'iso-8601])
261 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
264 (let ([nick (if nick (string-append nick " ") "")])
265 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
267 ([date-display-format 'rfc2822])
268 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
270 nick uri color text))])))))
272 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
273 (define rfc3339->epoch
274 (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}))?$")])
276 (match (regexp-match re ts)
277 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
280 (match* (tz-whole tz-sign tz-HH tz-MM)
283 [(_ (or "-" "+") (? identity h) (? identity m))
284 (let ([h (string->number h)]
285 [m (string->number m)]
286 ; Reverse to get back to UTC:
287 [op (match tz-sign ["+" -] ["-" +])])
288 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
290 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
294 [ts-epoch (find-seconds (if SS (string->number SS) 0)
299 (string->number yyyy)
301 (+ ts-epoch tz-offset))]
303 (log-debug "Invalid timestamp: ~v" ts)
306 (: str->msg (-> Peer String (Option Msg)))
308 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
310 (define from-str (peer->str from))
311 (define str-head (substring str 0 (min 100 (string-length str))))
316 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
319 (match (regexp-match re str)
320 [(list _wholething ts-orig text)
321 (let ([ts-epoch (rfc3339->epoch ts-orig)])
325 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
326 [(list _wholething nick-uri)
327 (str->peer nick-uri)]))
328 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
329 (Msg ts-epoch ts-orig from text mentions))
332 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
336 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
340 ; TODO Test for when missing-nick case
341 (let* ([tzs (for*/list ([d '("-" "+")]
343 [m '("00" ":00" "57" ":57")])
344 (string-append d h m))]
345 [tzs (list* "" "Z" tzs)])
346 (for* ([n '("fake-nick")]
347 [u '("http://fake-uri")]
348 [p (list (Peer n (string->url u) u #f))]
352 [sep (list "\t" " ")]
353 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
354 (let* ([ts (string-append "2020-11-18T22:22"
355 (if (non-empty-string? s) s ":00")
357 [m (str->msg p (string-append ts sep txt))])
359 (check-equal? (Msg-from m) p)
360 (check-equal? (Msg-text m) txt)
361 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
364 (let* ([ts "2020-11-18T22:22:09-0500"]
369 [peer (Peer nick (string->url uri) uri #f)]
370 [actual (str->msg peer (string-append ts tab text))]
371 [expected (Msg 1605756129 ts peer text '())])
373 (Msg-ts-epoch actual)
374 (Msg-ts-epoch expected)
378 (Msg-ts-orig expected)
381 (Peer-nick (Msg-from actual))
382 (Peer-nick (Msg-from expected))
385 (Peer-uri (Msg-from actual))
386 (Peer-uri (Msg-from expected))
389 (Peer-uri-str (Msg-from actual))
390 (Peer-uri-str (Msg-from expected))
397 (: str->lines (-> String (Listof String)))
398 (define (str->lines str)
399 (string-split str (regexp "[\r\n]+")))
402 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
404 ; TODO Should return 2 things: 1) msgs; 2) metadata parsed from comments
405 ; TODO Update peer nick based on metadata?
406 (: str->msgs (-> Peer String (Listof Msg)))
407 (define (str->msgs peer str)
408 (filter-map (λ (line) (str->msg peer line))
409 (filter-comments (str->lines str))))
411 (: cache-dir Path-String)
412 (define cache-dir (build-path tt-home-dir "cache"))
414 (define cache-object-dir (build-path cache-dir "objects"))
416 (: url->cache-file-path-v1 (-> Url Path-String))
417 (define (url->cache-file-path-v1 uri)
418 (define (hash-sha1 str) : (-> String String)
419 (define in (open-input-string str))
420 (define digest (sha1 in))
421 (close-input-port in)
423 (build-path cache-object-dir (hash-sha1 (url->string uri))))
425 (: url->cache-file-path-v2 (-> Url Path-String))
426 (define (url->cache-file-path-v2 uri)
427 (build-path cache-object-dir (uri-encode (url->string uri))))
429 (define url->cache-object-path
430 url->cache-file-path-v2)
432 (define (url->cache-etag-path uri)
433 (build-path cache-dir "etags" (uri-encode (url->string uri))))
435 (define (url->cache-lmod-path uri)
436 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
438 (: uri-read-cached (-> Url (Option String)))
439 (define (uri-read-cached uri)
440 (define path-v1 (url->cache-file-path-v1 uri))
441 (define path-v2 (url->cache-file-path-v2 uri))
442 (when (file-exists? path-v1)
443 (rename-file-or-directory path-v1 path-v2 #t))
444 (if (file-exists? path-v2)
445 (file->string path-v2)
447 (log-debug "Cache file not found for URI: ~a" (url->string uri))
450 (: str->url (-> String (Option String)))
453 ([exn:fail? (λ (e) #f)])
456 (: peer->str (-> Peer String))
457 (define (peer->str peer)
458 (match-define (Peer n _ u c) peer)
460 (if n (format "~a " n) "")
462 (if c (format " # ~a" c) "")))
464 (: str->peer (-> String (Option Peer)))
465 (define (str->peer str)
466 (log-debug "Parsing peer string: ~v" str)
469 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
477 (match (str->url url)
479 (log-error "Invalid URI in peer string: ~v" str)
482 (Peer nick url (url->string url) comment)])]
484 (log-debug "Invalid peer string: ~v" str)
489 (str->peer "foo http://bar/file.txt # some rando")
490 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
492 (str->peer "http://bar/file.txt # some rando")
493 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
495 (str->peer "http://bar/file.txt #")
496 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
498 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
499 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
501 (str->peer "http://bar/file.txt")
502 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
504 (str->peer "foo http://bar/file.txt")
505 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
507 (str->peer "foo bar # baz")
510 (str->peer "foo bar://baz # quux")
511 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
513 (str->peer "foo bar//baz # quux")
516 (: filter-comments (-> (Listof String) (Listof String)))
517 (define (filter-comments lines)
518 (filter-not (λ (line) (string-prefix? line "#")) lines))
520 (: str->peers (-> String (Listof Peer)))
521 (define (str->peers str)
522 (filter-map str->peer (filter-comments (str->lines str))))
524 (: peers->file (-> (Listof Peers) Path-String Void))
525 (define (peers->file peers path)
526 (display-lines-to-file
530 [((Peer n1 _ _ _) (Peer n2 _ _ _))
531 (string<? (if n1 n1 "")
536 (: file->peers (-> Path-String (Listof Peer)))
537 (define (file->peers file-path)
538 (if (file-exists? file-path)
539 (str->peers (file->string file-path))
541 (log-warning "File does not exist: ~v" (path->string file-path))
545 #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")
547 (: b->n (-> Bytes (Option Number)))
549 (string->number (bytes->string/utf-8 b)))
551 (: mon->num (-> Bytes Natural))
552 (define/match (mon->num mon)
566 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
567 (define (rfc2822->epoch timestamp)
568 (match (regexp-match re-rfc2822 timestamp)
569 [(list _ _ dd mo yyyy HH MM SS)
570 #:when (and dd mo yyyy HH MM SS)
571 (find-seconds (b->n SS)
581 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
582 (define (header-get headers name)
583 (match (filter-map (curry extract-field name) headers)
587 (: uri-download-from-port
588 (-> Url (Listof (U Bytes String)) Input-Port
589 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
590 (define (uri-download-from-port u headers body-input)
591 ; TODO Update message db from here? or where?
592 ; - 1st try can just be an in-memory set that gets written-to
593 ; and read-from disk as a whole.
594 (define u-str (url->string u))
595 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
596 (define cached-object-path (url->cache-object-path u))
597 (define cached-etag-path (url->cache-etag-path u))
598 (define cached-lmod-path (url->cache-lmod-path u))
599 (define etag (header-get headers #"ETag"))
600 (define lmod (header-get headers #"Last-Modified"))
601 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
602 (define lmod-prev (if (file-exists? cached-lmod-path)
603 (rfc2822->epoch (file->bytes cached-lmod-path))
605 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
608 (file-exists? cached-etag-path)
609 (bytes=? etag (file->bytes cached-etag-path))
611 (log-debug "ETags match, skipping the rest of ~v" u-str)
615 (<= lmod-curr lmod-prev)
617 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
622 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
624 (make-parent-directory* cached-object-path)
625 (make-parent-directory* cached-etag-path)
626 (make-parent-directory* cached-lmod-path)
627 (call-with-output-file cached-object-path
628 (curry copy-port body-input)
631 (display-to-file etag cached-etag-path #:exists 'replace))
633 (display-to-file lmod cached-lmod-path #:exists 'replace))
638 (-> Positive-Float Url
639 (Result (U 'skipped-cached 'downloaded-new)
640 Any))) ; TODO Maybe more-precise error type?
641 (define (uri-download timeout u)
642 (define u-str (url->string u))
643 (define timeout-chan (make-channel))
644 (define result-chan (make-channel))
645 (define timeout-thread
647 ; Doing this instead of sync/timeout to distinguish error values,
648 ; rather than just have #f to work with.
650 (channel-put timeout-chan '(error . timeout)))))
651 (define result-thread
655 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
657 (λ (e) `(error . (net-error . ,e)))]
659 (λ (e) `(error . (other . ,e)))])
660 (define-values (status-line headers body-input)
663 #:headers (list (format "User-Agent: ~a" user-agent-str))))
664 (log-debug "headers: ~v" headers)
665 (log-debug "status-line: ~v" status-line)
667 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
668 (log-debug "status: ~v" status)
670 ; TODO Handle redirects.
671 ; TODO Should a redirect update a peer URL?
674 `(ok . ,(uri-download-from-port u headers body-input))]
676 `(error . (http-not-ok . ,status))])])
677 (close-input-port body-input)
679 (channel-put result-chan result))))
680 (define result (sync timeout-chan result-chan))
681 (kill-thread result-thread)
682 (kill-thread timeout-thread)
685 (: timeline-print (-> Out-Format (Listof Msg) Void))
686 (define (timeline-print out-format timeline)
691 (void (foldl (match-lambda**
692 [((and m (Msg _ _ from _ _)) (cons prev-from i))
693 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
694 (msg-print out-format i m)
696 (cons (Msg-from first-msg) 0)
699 (: peer->msgs (-> Peer (Listof Msg)))
700 (define (peer->msgs peer)
701 (match-define (Peer nick uri uri-str _) peer)
702 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
703 (define msgs-data (uri-read-cached uri))
706 (str->msgs peer msgs-data)
710 (-> Positive-Float Peer
711 (Result (U 'skipped-cached 'downloaded-new)
713 (define (peer-download timeout peer)
714 (match-define (Peer nick uri u _) peer)
715 (log-info "Download BEGIN URL:~a" u)
716 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
717 (time-apply uri-download (list timeout uri)))
718 (define result (car results))
719 (log-info "Download END in ~a seconds, URL:~a, result:~s"
720 (/ tm-real-ms 1000.0)
725 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
726 (define (timeline-download num-workers timeout peers)
728 (concurrent-filter-map num-workers
729 (λ (p) (cons p (peer-download timeout p)))
732 (filter-map (match-lambda
733 [(cons p (cons 'ok _)) p]
734 [(cons _ (cons 'error e)) #f])
737 (filter-map (match-lambda
738 [(cons _ (cons 'ok _))
740 [(cons p (cons 'error e))
741 (struct-copy Peer p [comment (format "~s" e)])])
743 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
744 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
746 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
747 (define (peers->timeline peers)
748 (append* (filter-map peer->msgs peers)))
750 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
751 (define (timeline-sort msgs order)
752 (define cmp (match order
755 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
758 (: paths->peers (-> (Listof String) (Listof Peer)))
759 (define (paths->peers paths)
760 (let* ([paths (match paths
762 (let ([peer-refs-file (build-path tt-home-dir "peers")])
764 "No peer ref file paths provided, defaulting to ~v"
765 (path->string peer-refs-file))
766 (list peer-refs-file))]
768 (log-debug "Peer ref file paths provided: ~v" paths)
769 (map string->path paths)])]
770 [peers (apply peers-merge (map file->peers paths))])
771 (log-info "Read-in ~a peers." (length peers))
774 (: cache-filename->peer (-> Path-String (Option Peer)))
775 (define (cache-filename->peer filename)
776 (define nick #f) ; TODO Look it up in the nick-db when it exists.
777 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
778 (match (str->url url-str)
780 [url (Peer nick url url-str #f)]))
782 (: peers-cached (-> (Listof Peer)))
783 (define (peers-cached)
785 (filter-map cache-filename->peer (directory-list cache-object-dir)))
787 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
788 (define (peers-mentioned msgs)
789 (append* (map Msg-mentions msgs)))
791 (: log-writer-stop (-> Thread Void))
792 (define (log-writer-stop log-writer)
793 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
794 (thread-wait log-writer))
796 (: log-writer-start (-> Log-Level Thread))
797 (define (log-writer-start level)
799 (make-logger #f #f level #f)]
801 (make-log-receiver logger level)]
806 ([date-display-format 'iso-8601])
808 (match-define (vector level msg _ topic) (sync log-receiver))
809 (unless (equal? topic 'stop)
810 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
812 (current-logger logger)
815 (: msgs->nick-hist (-> (Listof Msg) Nick-Hist))
816 (define (msgs->nick-hist msgs)
818 (λ (msg url->nick->hist)
819 (match-define (Msg curr _ from _ mentions) msg)
821 (λ (peer url->nick->hist)
822 (match-define (Peer nick url _ _) peer)
824 (hash-update url->nick->hist
827 (hash-update nick->hist
831 (Hist (+ 1 freq) (max prev curr))])
836 (cons from mentions)))
840 (: update-nicks-history-files (-> Nick-Hist Void))
841 (define (update-nicks-history-files nick-hist)
845 (define path (build-path tt-home-dir "nicks" "seen" (uri-encode (url->string url))))
846 (make-parent-directory* path)
847 (display-lines-to-file
849 [(cons nick (Hist freq last))
850 (format "~a ~a ~a" nick freq last)])
851 (sort (hash->list nick->hist)
853 [((cons _ (Hist a _)) (cons _ (Hist b _)))
856 #:exists 'replace))))
858 (: nick-hist-most-by (-> Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
859 (define (nick-hist-most-by url->nick->hist url by)
860 (match (hash-ref url->nick->hist url #f)
863 (match (sort (hash->list nick->hist)
864 (λ (a b) (> (by (cdr a))
867 [(cons (cons nick _) _) nick])]))
869 (: nick-hist-latest (-> Nick-Hist Url (Option String)))
870 (define (nick-hist-latest nick-hist url)
871 (nick-hist-most-by nick-hist url Hist-last))
873 (: nick-hist-common (-> Nick-Hist Url (Option String)))
874 (define (nick-hist-common nick-hist url)
875 (nick-hist-most-by nick-hist url Hist-freq))
877 (: peers-update-nick-to-common (-> Nick-Hist (Listof Peer) (Listof Peer)))
878 (define (peers-update-nick-to-common nick-hist peers)
881 (match (nick-hist-common nick-hist (Peer-uri p))
883 [n (struct-copy Peer p [nick n])]))
887 (let* ([url-str "http://foo"]
888 [url (string->url url-str)]
892 [ts-str-1 "2021-11-29T23:29:08-0500"]
893 [ts-str-2 "2021-11-29T23:30:00-0500"]
894 [ts-1 (rfc3339->epoch ts-str-1)]
895 [ts-2 (rfc3339->epoch ts-str-2)]
899 (str->msg (str->peer "test http://test")
900 (string-append ts-str " Hi @<" nick " " url-str ">"))])
901 (list (cons ts-str-2 nick1)
902 (cons ts-str-1 nick2)
903 (cons ts-str-1 nick2)
904 (cons ts-str-1 nick3)
905 (cons ts-str-1 nick3)
906 (cons ts-str-1 nick3)))]
908 (msgs->nick-hist msgs)])
909 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
910 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
911 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
912 (check-equal? (nick-hist-common hist url) nick3)
913 (check-equal? (nick-hist-latest hist url) nick1)))
917 ; TODO Test the non-io parts of crawling
918 (let* ([peers-all-file
919 (build-path tt-home-dir "peers-all")]
920 [peers-mentioned-file
921 (build-path tt-home-dir "peers-mentioned")]
923 (build-path tt-home-dir "peers-parsed")]
925 (build-path tt-home-dir "peers-cached")]
929 (peers->timeline peers-cached)]
931 (msgs->nick-hist cached-timeline)]
932 [peers-mentioned-curr
933 (peers-mentioned cached-timeline)]
934 [peers-mentioned-prev
935 (file->peers peers-mentioned-file)]
937 (file->peers peers-all-file)]
939 (peers-merge peers-mentioned-prev
940 peers-mentioned-curr)]
942 (peers-update-nick-to-common
944 (peers-merge peers-mentioned
948 (set->list (set-subtract (make-immutable-peers peers-all)
949 (make-immutable-peers peers-all-prev)))]
951 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
952 ; TODO Deeper de-duping
953 (log-info "Known peers cached ~a" (length peers-cached))
954 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
955 (log-info "Known peers parsed ~a" (length peers-parsed))
956 (log-info "Known peers total: ~a" (length peers-all))
957 (log-info "Discovered ~a new peers:~n~a"
958 (length peers-discovered)
961 [(Peer n _ u c) (list n u c)])
963 (update-nicks-history-files nick-hist)
964 (peers->file peers-cached
966 (peers->file peers-mentioned
967 peers-mentioned-file)
968 (peers->file peers-parsed
970 (peers->file peers-all
973 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
974 (define (read file-paths ts-min ts-max order out-format)
976 (paths->peers file-paths)]
978 (timeline-sort (peers->timeline peers) order)]
981 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
982 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
983 (timeline-print out-format (filter include? msgs))))
987 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
988 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
992 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
993 (define (download file-paths num-workers timeout)
994 (let ([peers (paths->peers file-paths)])
995 (define-values (_res _cpu real-ms _gc)
996 (time-apply timeline-download (list num-workers timeout peers)))
997 (log-info "Downloaded timelines from ~a peers in ~a seconds."
999 (/ real-ms 1000.0))))
1001 (: dispatch (-> String Void))
1002 (define (dispatch command)
1004 [(or "d" "download")
1005 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
1006 ; started noticing significant slowdowns. Reducing to 5 seems to help.
1007 (let ([num-workers 5]
1010 #:program "tt download"
1013 njobs "Number of concurrent jobs."
1014 (set! num-workers (string->number njobs))]
1016 seconds "Timeout seconds per request."
1017 (set! timeout (string->number seconds))]
1019 (download file-paths num-workers timeout)))]
1022 #:program "tt upload" #:args () (upload))]
1024 (let ([out-format 'multi-line]
1032 "Reverse displayed timeline order."
1033 (set! order 'new->old)]
1035 m "Earliest time to display (ignore anything before it)."
1036 (set! ts-min (rfc3339->epoch m))]
1038 x "Latest time to display (ignore anything after it)."
1039 (set! ts-max (rfc3339->epoch x))]
1042 "Short output format"
1043 (set! out-format 'single-line)]
1045 "Long output format"
1046 (set! out-format 'multi-line)]
1048 (read file-paths ts-min ts-max order out-format)))]
1051 #:program "tt crawl" #:args () (crawl))]
1053 (eprintf "Error: invalid command: ~v\n" command)
1054 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1058 (let ([log-level 'info])
1064 "Enable debug log level."
1065 (set! log-level 'debug)]
1068 "and <command> is one of"
1069 "r, read : Read the timeline (offline operation)."
1070 "d, download : Download the timeline."
1071 ; TODO Add path dynamically
1072 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
1073 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
1075 #:args (command . args)
1076 (define log-writer (log-writer-start log-level))
1077 (current-command-line-arguments (list->vector args))
1078 (set-user-agent-str (build-path tt-home-dir "me"))
1079 ; TODO dispatch should return status with which we should exit after cleanups
1081 (log-writer-stop log-writer))))