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 α)
30 (define-type Download-Result
31 (Result (U 'skipped-cached 'downloaded-new)
33 (Pair 'unsupported-url-scheme String)
34 (Pair 'http-not-ok Positive-Integer)
39 ([freq : Nonnegative-Integer]
40 [last : Nonnegative-Integer])
43 (define-type Url-Nick-Hist
44 (Immutable-HashTable Url (Immutable-HashTable (Option String) Hist)))
48 [nick : (Option String)]))
63 [mentions : (Listof Peer)]))
66 ([nick : (Option String)]
69 [comment : (Option String)])
74 (Prog "tt" (info:#%info-lookup 'version)))
78 (User (string->url "https://github.com/xandkar/tt") #f))
80 (: user->str (-> User String))
81 (define (user->str user)
82 (match-define (User u0 n) user)
83 (define u (url->string u0))
85 (format "+~a; @~a" u n)
88 (: user-agent->str (-> User-Agent String))
89 (define (user-agent->str ua)
90 (match-define (User-Agent u p) ua)
91 (format "~a/~a (~a)" (Prog-name p) (Prog-version p) (user->str u)))
93 (: user->user-agent User)
94 (define (user->user-agent user)
95 (User-Agent user prog))
97 (: user-agent-str String)
98 (define user-agent-str
99 (user-agent->str (user->user-agent user-default)))
101 (: set-user-agent-str (-> Path-String Void))
102 (define (set-user-agent-str filename)
103 (set! user-agent-str (user-agent->str (user->user-agent (file->user filename))))
104 (log-info "User-Agent string is now set to: ~v" user-agent-str))
106 (: file->user (-> Path-String User))
107 (define (file->user filename)
108 (if (file-exists? filename)
109 (match (file->peers filename)
112 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
118 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
124 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
130 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
135 (: peer->user (-> Peer User))
136 (define (peer->user p)
137 (match-define (Peer n u _ _) p)
140 (: peers-equal? (-> Peer Peer Boolean))
141 (define (peers-equal? p1 p2)
142 (equal? (Peer-uri-str p1)
145 (: peer-hash (-> Peer Fixnum))
146 (define (peer-hash p)
147 (equal-hash-code (Peer-uri-str p)))
149 (define-custom-set-types peers
153 ; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
154 ; the following contract violations:
156 ; custom-elem-contents: contract violation
157 ; expected: custom-elem?
160 ; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
161 ; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
162 ; /usr/share/racket/collects/racket/cmdline.rkt:191:51
163 ; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
165 ; TODO Investigate why and make a minimal reproducible test case.
167 (: peers-merge (-> (Listof Peer) * (Listof Peer)))
168 (define (peers-merge . peer-sets)
172 (hash-update groups (Peer-uri-str p) (λ (group) (cons p group)) '()))
174 (append* peer-sets)))
175 (define (merge peers)
177 ['() (raise 'impossible)]
180 (let* ([n1 (Peer-nick p1)]
183 ; TODO Try to pick from nicks db: preferred, otherwise seen
184 [(and (not n1) (not n2)) p1] ; TODO update with most-common nick
185 [(and n1 n2 ) p1] ; TODO compare which is more-common
186 [(and n1 (not n2)) p1]
187 [(and (not n1) n2) p2]
189 (raise 'impossible)])])
190 (merge (cons p ps)))]))
191 (sort (map merge (hash-values groups))
193 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
196 (let* ([u1 "http://foo/bar"]
197 [u2 "http://baz/quux"]
198 [p1 (Peer #f (string->url u1) u1 #f)]
199 [p2 (Peer "a" (string->url u1) u1 #f)]
200 [p3 (Peer "b" (string->url u2) u2 #f)]
203 (check-equal? (list p3 p2) (peers-merge s1 s2))
204 (check-equal? (list p3 p2) (peers-merge s2 s1))))
206 (: tt-home-dir Path-String)
207 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
209 (: pub-peers-dir Path-String)
210 (define pub-peers-dir (build-path tt-home-dir "peers"))
212 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
213 (define (concurrent-filter-map num-workers f xs)
214 ; TODO preserve order of elements OR communicate that reorder is expected
215 ; TODO switch from mailboxes to channels
216 (define (make-worker id f)
217 (define parent (current-thread))
219 (define self : Thread (current-thread))
220 (: work (∀ (α) (-> α)))
222 (thread-send parent (cons 'next self))
223 (match (thread-receive)
224 ['done (thread-send parent (cons 'exit id))]
225 [(cons 'unit x) (begin
227 (when y (thread-send parent (cons 'result y)))
230 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
231 (define (dispatch ws xs ys)
234 (match (thread-receive)
235 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
236 [(cons 'result y) (dispatch ws xs (cons y ys))]
237 [(cons 'next thd) (match xs
239 (thread-send thd 'done)
240 (dispatch ws xs ys))]
242 (thread-send thd (cons 'unit x))
243 (dispatch ws xs ys))])])))
244 (define workers (range num-workers))
245 (define threads (map (λ (id) (thread (make-worker id f))) workers))
246 (define results (dispatch workers xs '()))
247 (for-each thread-wait threads)
251 (let* ([f (λ (x) (if (even? x) x #f))]
253 [actual (sort (concurrent-filter-map 10 f xs) <)]
254 [expected (sort ( filter-map f xs) <)])
255 (check-equal? actual expected "concurrent-filter-map")))
257 (: msg-print (-> Out-Format Integer Msg Void))
259 (let* ([colors (vector 36 33)]
260 [n (vector-length colors)])
261 (λ (out-format color-i msg)
262 (let ([color (vector-ref colors (modulo color-i n))]
263 [nick (Peer-nick (Msg-from msg))]
264 [uri (Peer-uri-str (Msg-from msg))]
265 [text (Msg-text msg)])
268 (let ([nick (if nick nick uri)])
269 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
271 ([date-display-format 'iso-8601])
272 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
275 (let ([nick (if nick (string-append nick " ") "")])
276 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
278 ([date-display-format 'rfc2822])
279 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
281 nick uri color text))])))))
283 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
284 (define rfc3339->epoch
285 (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}))?$")])
287 (match (regexp-match re ts)
288 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
291 (match* (tz-whole tz-sign tz-HH tz-MM)
294 [(_ (or "-" "+") (? identity h) (? identity m))
295 (let ([h (string->number h)]
296 [m (string->number m)]
297 ; Reverse to get back to UTC:
298 [op (match tz-sign ["+" -] ["-" +])])
299 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
301 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
305 [ts-epoch (find-seconds (if SS (string->number SS) 0)
310 (string->number yyyy)
312 (+ ts-epoch tz-offset))]
314 (log-debug "Invalid timestamp: ~v" ts)
317 (: str->msg (-> Peer String (Option Msg)))
319 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
321 (define from-str (peer->str from))
322 (define str-head (substring str 0 (min 100 (string-length str))))
327 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
330 (match (regexp-match re str)
331 [(list _wholething ts-orig text)
332 (let ([ts-epoch (rfc3339->epoch ts-orig)])
336 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
337 [(list _wholething nick-uri)
338 (str->peer nick-uri)]))
339 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
340 (Msg ts-epoch ts-orig from text mentions))
343 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
347 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
351 ; TODO Test for when missing-nick case
352 (let* ([tzs (for*/list ([d '("-" "+")]
354 [m '("00" ":00" "57" ":57")])
355 (string-append d h m))]
356 [tzs (list* "" "Z" tzs)])
357 (for* ([n '("fake-nick")]
358 [u '("http://fake-uri")]
359 [p (list (Peer n (string->url u) u #f))]
363 [sep (list "\t" " ")]
364 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
365 (let* ([ts (string-append "2020-11-18T22:22"
366 (if (non-empty-string? s) s ":00")
368 [m (str->msg p (string-append ts sep txt))])
370 (check-equal? (Msg-from m) p)
371 (check-equal? (Msg-text m) txt)
372 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
375 (let* ([ts "2020-11-18T22:22:09-0500"]
380 [peer (Peer nick (string->url uri) uri #f)]
381 [actual (str->msg peer (string-append ts tab text))]
382 [expected (Msg 1605756129 ts peer text '())])
384 (Msg-ts-epoch actual)
385 (Msg-ts-epoch expected)
389 (Msg-ts-orig expected)
392 (Peer-nick (Msg-from actual))
393 (Peer-nick (Msg-from expected))
396 (Peer-uri (Msg-from actual))
397 (Peer-uri (Msg-from expected))
400 (Peer-uri-str (Msg-from actual))
401 (Peer-uri-str (Msg-from expected))
408 (: str->lines (-> String (Listof String)))
409 (define (str->lines str)
410 (string-split str (regexp "[\r\n]+")))
413 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
415 ; TODO Should return 2 things: 1) msgs; 2) metadata parsed from comments
416 ; TODO Update peer nick based on metadata?
417 (: str->msgs (-> Peer String (Listof Msg)))
418 (define (str->msgs peer str)
419 (filter-map (λ (line) (str->msg peer line))
420 (filter-comments (str->lines str))))
422 (: cache-dir Path-String)
423 (define cache-dir (build-path tt-home-dir "cache"))
425 (define cache-object-dir (build-path cache-dir "objects"))
427 (: url->cache-file-path-v1 (-> Url Path-String))
428 (define (url->cache-file-path-v1 uri)
429 (define (hash-sha1 str) : (-> String String)
430 (define in (open-input-string str))
431 (define digest (sha1 in))
432 (close-input-port in)
434 (build-path cache-object-dir (hash-sha1 (url->string uri))))
436 (: url->cache-file-path-v2 (-> Url Path-String))
437 (define (url->cache-file-path-v2 uri)
438 (build-path cache-object-dir (uri-encode (url->string uri))))
440 (define url->cache-object-path
441 url->cache-file-path-v2)
443 (define (url->cache-etag-path uri)
444 (build-path cache-dir "etags" (uri-encode (url->string uri))))
446 (define (url->cache-lmod-path uri)
447 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
449 (: uri-read-cached (-> Url (Option String)))
450 (define (uri-read-cached uri)
451 (define path-v1 (url->cache-file-path-v1 uri))
452 (define path-v2 (url->cache-file-path-v2 uri))
453 (when (file-exists? path-v1)
454 (rename-file-or-directory path-v1 path-v2 #t))
455 (if (file-exists? path-v2)
456 (file->string path-v2)
458 (log-debug "Cache file not found for URI: ~a" (url->string uri))
461 (: str->url (-> String (Option String)))
464 ([exn:fail? (λ (e) #f)])
467 (: peer->str (-> Peer String))
468 (define (peer->str peer)
469 (match-define (Peer n _ u c) peer)
471 (if n (format "~a " n) "")
473 (if c (format " # ~a" c) "")))
475 (: str->peer (-> String (Option Peer)))
476 (define (str->peer str)
477 (log-debug "Parsing peer string: ~v" str)
480 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
488 (match (str->url url)
490 (log-error "Invalid URI in peer string: ~v" str)
493 (Peer nick url (url->string url) comment)])]
495 (log-debug "Invalid peer string: ~v" str)
500 (str->peer "foo http://bar/file.txt # some rando")
501 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
503 (str->peer "http://bar/file.txt # some rando")
504 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
506 (str->peer "http://bar/file.txt #")
507 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
509 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
510 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
512 (str->peer "http://bar/file.txt")
513 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
515 (str->peer "foo http://bar/file.txt")
516 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
518 (str->peer "foo bar # baz")
521 (str->peer "foo bar://baz # quux")
522 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
524 (str->peer "foo bar//baz # quux")
527 (: filter-comments (-> (Listof String) (Listof String)))
528 (define (filter-comments lines)
529 (filter-not (λ (line) (string-prefix? line "#")) lines))
531 (: str->peers (-> String (Listof Peer)))
532 (define (str->peers str)
533 (filter-map str->peer (filter-comments (str->lines str))))
535 (: peers->file (-> (Listof Peers) Path-String Void))
536 (define (peers->file peers path)
537 (make-parent-directory* path)
538 (display-lines-to-file
542 [((Peer n1 _ _ _) (Peer n2 _ _ _))
543 (string<? (if n1 n1 "")
548 (: file->peers (-> Path-String (Listof Peer)))
549 (define (file->peers file-path)
550 (if (file-exists? file-path)
551 (str->peers (file->string file-path))
553 (log-warning "File does not exist: ~v" (path->string file-path))
557 #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")
559 (: b->n (-> Bytes (Option Number)))
561 (string->number (bytes->string/utf-8 b)))
563 (: mon->num (-> Bytes Natural))
564 (define/match (mon->num mon)
578 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
579 (define (rfc2822->epoch timestamp)
580 (match (regexp-match re-rfc2822 timestamp)
581 [(list _ _ dd mo yyyy HH MM SS)
582 #:when (and dd mo yyyy HH MM SS)
583 (find-seconds (b->n SS)
593 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
594 (define (header-get headers name)
595 (match (filter-map (curry extract-field name) headers)
599 (: uri-download-http-from-port
600 (-> Url (Listof (U Bytes String)) Input-Port
601 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
602 (define (uri-download-http-from-port u headers body-input)
603 ; TODO Update message db from here? or where?
604 ; - 1st try can just be an in-memory set that gets written-to
605 ; and read-from disk as a whole.
606 (define u-str (url->string u))
607 (log-debug "uri-download-http-from-port ~v into ~v" u-str cached-object-path)
608 (define cached-object-path (url->cache-object-path u))
609 (define cached-etag-path (url->cache-etag-path u))
610 (define cached-lmod-path (url->cache-lmod-path u))
611 (define etag (header-get headers #"ETag"))
612 (define lmod (header-get headers #"Last-Modified"))
613 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
614 (define lmod-prev (if (file-exists? cached-lmod-path)
615 (rfc2822->epoch (file->bytes cached-lmod-path))
617 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
620 (file-exists? cached-etag-path)
621 (bytes=? etag (file->bytes cached-etag-path))
623 (log-debug "ETags match, skipping the rest of ~v" u-str)
627 (<= lmod-curr lmod-prev)
629 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
634 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
636 (make-parent-directory* cached-object-path)
637 (make-parent-directory* cached-etag-path)
638 (make-parent-directory* cached-lmod-path)
639 (call-with-output-file cached-object-path
640 (curry copy-port body-input)
643 (display-to-file etag cached-etag-path #:exists 'replace))
645 (display-to-file lmod cached-lmod-path #:exists 'replace))
649 (: uri-download-http (-> Positive-Float Url Download-Result))
650 (define (uri-download-http timeout u)
651 (define u-str (url->string u))
652 (define timeout-chan (make-channel))
653 (define result-chan (make-channel))
654 (define timeout-thread
656 ; Doing this instead of sync/timeout to distinguish error values,
657 ; rather than just have #f to work with.
659 (channel-put timeout-chan '(error . timeout)))))
660 (define result-thread
664 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
666 (λ (e) `(error . (net-error . ,e)))]
668 (λ (e) `(error . (other . ,e)))])
669 (define-values (status-line headers body-input)
672 #:headers (list (format "User-Agent: ~a" user-agent-str))))
673 (log-debug "headers: ~v" headers)
674 (log-debug "status-line: ~v" status-line)
676 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
677 (log-debug "status: ~v" status)
679 ; TODO Handle redirects.
680 ; TODO Should a redirect update a peer URL?
683 `(ok . ,(uri-download-http-from-port u headers body-input))]
685 `(error . (http-not-ok . ,status))])])
686 (close-input-port body-input)
688 (channel-put result-chan result))))
689 (define result (sync timeout-chan result-chan))
690 (kill-thread result-thread)
691 (kill-thread timeout-thread)
694 (: uri-download (-> Positive-Float Url Download-Result))
695 (define (uri-download timeout u)
696 (match (url-scheme u)
697 ; TODO Support Gopher.
699 (uri-download-http timeout u)]
701 `(error . (unsupported-url-scheme . ,scheme))]))
703 (: timeline-print (-> Out-Format (Listof Msg) Void))
704 (define (timeline-print out-format timeline)
709 (void (foldl (match-lambda**
710 [((and m (Msg _ _ from _ _)) (cons prev-from i))
711 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
712 (msg-print out-format i m)
714 (cons (Msg-from first-msg) 0)
717 (: peer->msgs (-> Peer (Listof Msg)))
718 (define (peer->msgs peer)
719 (match-define (Peer nick uri uri-str _) peer)
720 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
721 (define msgs-data (uri-read-cached uri))
724 (str->msgs peer msgs-data)
728 (-> Positive-Float Peer
729 (Result (U 'skipped-cached 'downloaded-new)
731 (define (peer-download timeout peer)
732 (match-define (Peer nick uri u _) peer)
733 (log-info "Download BEGIN URL:~a" u)
734 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
735 (time-apply uri-download (list timeout uri)))
736 (define result (car results))
737 (log-info "Download END in ~a seconds, URL:~a, result:~s"
738 (/ tm-real-ms 1000.0)
743 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
744 (define (timeline-download num-workers timeout peers)
746 (concurrent-filter-map num-workers
747 (λ (p) (cons p (peer-download timeout p)))
750 (filter-map (match-lambda
751 [(cons p (cons 'ok _)) p]
752 [(cons _ (cons 'error e)) #f])
755 (filter-map (match-lambda
756 [(cons _ (cons 'ok _))
758 [(cons p (cons 'error e))
759 (struct-copy Peer p [comment (format "~s" e)])])
761 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok.txt"))
762 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err.txt")))
764 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
765 (define (peers->timeline peers)
766 (append* (filter-map peer->msgs peers)))
768 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
769 (define (timeline-sort msgs order)
770 (define cmp (match order
773 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
776 (: paths->peers (-> (Listof String) (Listof Peer)))
777 (define (paths->peers paths)
778 (let* ([paths (match paths
780 (let ([peer-refs-file (build-path tt-home-dir "following.txt")])
782 "No peer ref file paths provided, defaulting to ~v"
783 (path->string peer-refs-file))
784 (list peer-refs-file))]
786 (log-debug "Peer ref file paths provided: ~v" paths)
787 (map string->path paths)])]
788 [peers (apply peers-merge (map file->peers paths))])
789 (log-info "Read-in ~a peers." (length peers))
792 (: cache-filename->peer (-> Path-String (Option Peer)))
793 (define (cache-filename->peer filename)
794 (define nick #f) ; TODO Look it up in the nick-db when it exists.
795 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
796 (match (str->url url-str)
798 [url (Peer nick url url-str #f)]))
800 (: peers-cached (-> (Listof Peer)))
801 (define (peers-cached)
803 (filter-map cache-filename->peer (directory-list cache-object-dir)))
805 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
806 (define (peers-mentioned msgs)
807 (append* (map Msg-mentions msgs)))
809 (: peers-filter-denied-domains (-> (Listof Peer) (Listof Peer)))
810 (define (peers-filter-denied-domains peers)
811 (define deny-file (build-path tt-home-dir "domains-deny.txt"))
813 (list->set (map string-trim (filter-comments (file->lines deny-file)))))
814 (define denied-domain-patterns
815 (set-map denied-hosts (λ (h) (pregexp (string-append "\\." h "$")))))
818 (define host (url-host (Peer-uri p)))
819 (not (or (set-member? denied-hosts host)
820 (ormap (λ (d) (regexp-match? d host)) denied-domain-patterns))))
823 (: log-writer-stop (-> Thread Void))
824 (define (log-writer-stop log-writer)
825 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
826 (thread-wait log-writer))
828 (: log-writer-start (-> Log-Level Thread))
829 (define (log-writer-start level)
831 (make-logger #f #f level #f)]
833 (make-log-receiver logger level)]
838 ([date-display-format 'iso-8601])
840 (match-define (vector level msg _ topic) (sync log-receiver))
841 (unless (equal? topic 'stop)
842 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
844 (current-logger logger)
847 (: msgs->nick-hist (-> (Listof Msg) Url-Nick-Hist))
848 (define (msgs->nick-hist msgs)
850 (λ (msg url->nick->hist)
851 (match-define (Msg curr _ from _ mentions) msg)
853 (λ (peer url->nick->hist)
854 (match-define (Peer nick url _ _) peer)
856 (hash-update url->nick->hist
859 (hash-update nick->hist
863 (Hist (+ 1 freq) (max prev curr))])
868 (cons from mentions)))
872 (: url-nick-hist->file (-> Url-Nick-Hist Path-String Void))
873 (define (url-nick-hist->file unh filepath)
874 (define out (open-output-file filepath #:exists 'replace))
877 [(cons url nick->hist)
878 (displayln (url->string url) out)
879 (for-each (match-lambda
880 [(cons nick (Hist freq last))
881 (displayln (format " ~a ~a ~a" nick freq last) out)])
882 (sort (hash->list nick->hist)
884 [((cons _ (Hist a _)) (cons _ (Hist b _)))
888 (λ (a b) (string<? (url-host (car a))
889 (url-host (car b))))))
890 (close-output-port out))
892 (: url-nick-hist->dir (-> Url-Nick-Hist Path-String Void))
893 (define (url-nick-hist->dir unh dirpath)
897 (define filename (string-append (uri-encode (url->string url)) ".txt"))
898 (define filepath (build-path dirpath filename))
899 (make-parent-directory* filepath)
900 (display-lines-to-file
902 [(cons nick (Hist freq last))
903 (format "~a ~a ~a" nick freq last)])
904 (sort (hash->list nick->hist)
906 [((cons _ (Hist a _)) (cons _ (Hist b _)))
909 #:exists 'replace))))
911 (: update-nicks-history-files (-> Url-Nick-Hist Void))
912 (define (update-nicks-history-files unh)
913 (define nicks-dir (build-path tt-home-dir "nicks"))
914 (url-nick-hist->file unh (build-path nicks-dir "seen.txt"))
915 (url-nick-hist->dir unh (build-path nicks-dir "seen")))
917 (: url-nick-hist-most-by (-> Url-Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
918 (define (url-nick-hist-most-by url->nick->hist url by)
919 (match (hash-ref url->nick->hist url #f)
922 (match (sort (hash->list nick->hist)
923 (λ (a b) (> (by (cdr a))
926 [(cons (cons nick _) _) nick])]))
928 (: url-nick-hist-latest (-> Url-Nick-Hist Url (Option String)))
929 (define (url-nick-hist-latest unh url)
930 (url-nick-hist-most-by unh url Hist-last))
932 (: url-nick-hist-common (-> Url-Nick-Hist Url (Option String)))
933 (define (url-nick-hist-common unh url)
934 (url-nick-hist-most-by unh url Hist-freq))
936 (: peers-update-nick-to-common (-> Url-Nick-Hist (Listof Peer) (Listof Peer)))
937 (define (peers-update-nick-to-common unh peers)
940 (match (url-nick-hist-common unh (Peer-uri p))
942 [n (struct-copy Peer p [nick n])]))
946 (let* ([url-str "http://foo"]
947 [url (string->url url-str)]
951 [ts-str-1 "2021-11-29T23:29:08-0500"]
952 [ts-str-2 "2021-11-29T23:30:00-0500"]
953 [ts-1 (rfc3339->epoch ts-str-1)]
954 [ts-2 (rfc3339->epoch ts-str-2)]
958 (str->msg (str->peer "test http://test")
959 (string-append ts-str " Hi @<" nick " " url-str ">"))])
960 (list (cons ts-str-2 nick1)
961 (cons ts-str-1 nick2)
962 (cons ts-str-1 nick2)
963 (cons ts-str-1 nick3)
964 (cons ts-str-1 nick3)
965 (cons ts-str-1 nick3)))]
967 (msgs->nick-hist msgs)])
968 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
969 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
970 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
971 (check-equal? (url-nick-hist-common hist url) nick3)
972 (check-equal? (url-nick-hist-latest hist url) nick1)))
976 ; TODO Test the non-io parts of crawling
977 (let* ([peers-all-file
978 (build-path pub-peers-dir "all.txt")]
979 [peers-mentioned-file
980 (build-path pub-peers-dir "mentioned.txt")]
982 (build-path pub-peers-dir "downloaded-and-parsed.txt")]
984 (build-path pub-peers-dir "downloaded.txt")]
988 (peers->timeline peers-cached)]
990 (msgs->nick-hist cached-timeline)]
991 [peers-mentioned-curr
992 (peers-mentioned cached-timeline)]
993 [peers-mentioned-prev
994 (file->peers peers-mentioned-file)]
996 (file->peers peers-all-file)]
998 (peers-merge peers-mentioned-prev
999 peers-mentioned-curr)]
1001 (peers-update-nick-to-common
1003 (peers-merge peers-mentioned
1007 (set->list (set-subtract (make-immutable-peers peers-all)
1008 (make-immutable-peers peers-all-prev)))]
1010 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
1011 ; TODO Deeper de-duping
1012 (log-info "Known peers cached ~a" (length peers-cached))
1013 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
1014 (log-info "Known peers parsed ~a" (length peers-parsed))
1015 (log-info "Known peers total: ~a" (length peers-all))
1016 (log-info "Discovered ~a new peers:~n~a"
1017 (length peers-discovered)
1020 [(Peer n _ u c) (list n u c)])
1022 (update-nicks-history-files url-nick-hist)
1023 (peers->file peers-cached
1025 (peers->file peers-mentioned
1026 peers-mentioned-file)
1027 (peers->file peers-parsed
1029 (peers->file peers-all
1032 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
1033 (define (read file-paths ts-min ts-max order out-format)
1035 (paths->peers file-paths)]
1037 (timeline-sort (peers->timeline peers) order)]
1040 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
1041 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
1042 (timeline-print out-format (filter include? msgs))))
1044 (: upload (-> Void))
1046 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
1047 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
1051 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
1052 (define (download file-paths num-workers timeout)
1053 (let* ([peers-given (paths->peers file-paths)]
1054 [peers-kept (peers-filter-denied-domains peers-given)]
1055 [peers-denied (set-subtract peers-given peers-kept)])
1056 (log-info "Denied ~a peers" (length peers-denied))
1057 (define-values (_res _cpu real-ms _gc)
1058 (time-apply timeline-download (list num-workers timeout peers-kept)))
1059 (log-info "Downloaded timelines from ~a peers in ~a seconds."
1061 (/ real-ms 1000.0))))
1063 (: dispatch (-> String Void))
1064 (define (dispatch command)
1066 [(or "d" "download")
1067 (let ([num-workers 20] ; 20 was fastest out of the tried: 1, 5, 10, 20, 25, 30.
1070 #:program "tt download"
1073 njobs "Number of concurrent jobs."
1074 (set! num-workers (string->number njobs))]
1076 seconds "Timeout seconds per request."
1077 (set! timeout (string->number seconds))]
1079 (download file-paths num-workers timeout)))]
1082 #:program "tt upload" #:args () (upload))]
1084 (let ([out-format 'multi-line]
1092 "Reverse displayed timeline order."
1093 (set! order 'new->old)]
1095 m "Earliest time to display (ignore anything before it)."
1096 (set! ts-min (rfc3339->epoch m))]
1098 x "Latest time to display (ignore anything after it)."
1099 (set! ts-max (rfc3339->epoch x))]
1102 "Short output format"
1103 (set! out-format 'single-line)]
1105 "Long output format"
1106 (set! out-format 'multi-line)]
1108 (read file-paths ts-min ts-max order out-format)))]
1111 #:program "tt crawl" #:args () (crawl))]
1113 (eprintf "Error: invalid command: ~v\n" command)
1114 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1118 (let ([log-level 'info])
1124 "Enable debug log level."
1125 (set! log-level 'debug)]
1128 "and <command> is one of"
1129 "r, read : Read the timeline (offline operation)."
1130 "d, download : Download the timeline."
1131 ; TODO Add path dynamically
1132 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
1133 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
1135 #:args (command . args)
1136 (define log-writer (log-writer-start log-level))
1137 (current-command-line-arguments (list->vector args))
1138 (set-user-agent-str (build-path tt-home-dir "user.txt"))
1139 ; TODO dispatch should return status with which we should exit after cleanups
1141 (log-writer-stop log-writer))))