Track nick usage frequency per URL
[tt.git] / tt.rkt
1 #lang typed/racket/no-check
2
3 (require openssl/sha1)
4 (require racket/date)
5 (require
6 net/head
7 net/uri-codec
8 net/url)
9
10 (require (prefix-in info: "info.rkt"))
11
12 (module+ test
13 (require rackunit))
14
15 (define-type Url
16 net/url-structs:url)
17
18 (define-type Out-Format
19 (U 'single-line
20 'multi-line))
21
22 (define-type Timeline-Order
23 (U 'old->new
24 'new->old))
25
26 (define-type Result
27 (∀ (α β) (U (cons 'ok α)
28 (cons 'error β))))
29
30 (struct Hist
31 ([freq : Nonnegative-Integer]
32 [last : Nonnegative-Integer])
33 #:transparent)
34
35 (define-type Nick-Hist
36 (Immutable-HashTable Url (Immutable-HashTable (Option String) Hist)))
37
38 (struct User
39 ([uri : Url]
40 [nick : (Option String)]))
41
42 (struct User-Agent
43 ([user : User]
44 [prog : Prog]))
45
46 (struct Prog
47 ([name : String]
48 [version : String]))
49
50 (struct Msg
51 ([ts-epoch : Integer]
52 [ts-orig : String]
53 [from : Peer]
54 [text : String]
55 [mentions : (Listof Peer)]))
56
57 (struct Peer
58 ([nick : (Option String)]
59 [uri : Url]
60 [uri-str : String]
61 [comment : (Option String)])
62 #:transparent)
63
64 (struct Resp
65 ([status-line : String]
66 [headers : (Listof Bytes)]
67 [body-input : Input-Port])
68 #:transparent)
69
70 (: prog Prog)
71 (define prog
72 (Prog "tt" (info:#%info-lookup 'version)))
73
74 (: user-default User)
75 (define user-default
76 (User (string->url "https://github.com/xandkar/tt") #f))
77
78 (: user->str (-> User String))
79 (define (user->str user)
80 (match-define (User u0 n) user)
81 (define u (url->string u0))
82 (if n
83 (format "+~a; @~a" u n)
84 (format "+~a" u )))
85
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)))
90
91 (: user->user-agent User)
92 (define (user->user-agent user)
93 (User-Agent user prog))
94
95 (: user-agent-str String)
96 (define user-agent-str
97 (user-agent->str (user->user-agent user-default)))
98
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))
103
104 (: file->user (-> Path-String User))
105 (define (file->user filename)
106 (if (file-exists? filename)
107 (match (file->peers filename)
108 [(list p)
109 (log-info
110 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
111 filename
112 (peer->str p))
113 (peer->user p)]
114 [(list* p _)
115 (log-warning
116 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
117 filename
118 (peer->str p))
119 (peer->user p)]
120 ['()
121 (log-warning
122 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
123 filename
124 user-default)
125 user-default])
126 (begin
127 (log-warning
128 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
129 filename
130 user-default)
131 user-default)))
132
133 (: peer->user (-> Peer User))
134 (define (peer->user p)
135 (match-define (Peer n u _ _) p)
136 (User u n))
137
138 (: peers-equal? (-> Peer Peer Boolean))
139 (define (peers-equal? p1 p2)
140 (equal? (Peer-uri-str p1)
141 (Peer-uri-str p2)))
142
143 (: peer-hash (-> Peer Fixnum))
144 (define (peer-hash p)
145 (equal-hash-code (Peer-uri-str p)))
146
147 (define-custom-set-types peers
148 #:elem? Peer?
149 peers-equal?
150 peer-hash)
151 ; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
152 ; the following contract violations:
153 ;
154 ; custom-elem-contents: contract violation
155 ; expected: custom-elem?
156 ; given: #f
157 ; context...:
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)
162 ;
163 ; TODO Investigate why and make a minimal reproducible test case.
164
165 (: peers-merge (-> (Listof Peer) * (Listof Peer)))
166 (define (peers-merge . peer-sets)
167 (define groups
168 (foldl
169 (λ (p groups)
170 (hash-update groups (Peer-uri-str p) (λ (group) (cons p group)) '()))
171 (hash)
172 (append* peer-sets)))
173 (define (merge peers)
174 (match peers
175 ['() (raise 'impossible)]
176 [(list p) p]
177 [(list* p1 p2 ps)
178 (let* ([n1 (Peer-nick p1)]
179 [n2 (Peer-nick p2)]
180 [p (cond
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]
186 [else
187 (raise 'impossible)])])
188 (merge (cons p ps)))]))
189 (sort (map merge (hash-values groups))
190 (match-lambda**
191 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
192
193 (module+ test
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)]
199 [s1 (list p1)]
200 [s2 (list p2 p3)])
201 (check-equal? (list p3 p2) (peers-merge s1 s2))
202 (check-equal? (list p3 p2) (peers-merge s2 s1))))
203
204 (: tt-home-dir Path-String)
205 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
206
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))
213 (λ ()
214 (define self : Thread (current-thread))
215 (: work (∀ (α) (-> α)))
216 (define (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
221 (define y (f x))
222 (when y (thread-send parent (cons 'result y)))
223 (work))]))
224 (work)))
225 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
226 (define (dispatch ws xs ys)
227 (if (empty? ws)
228 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
233 ['() (begin
234 (thread-send thd 'done)
235 (dispatch ws xs ys))]
236 [(cons x xs) (begin
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)
243 results)
244
245 (module+ test
246 (let* ([f (λ (x) (if (even? x) x #f))]
247 [xs (range 11)]
248 [actual (sort (concurrent-filter-map 10 f xs) <)]
249 [expected (sort ( filter-map f xs) <)])
250 (check-equal? actual expected "concurrent-filter-map")))
251
252 (: msg-print (-> Out-Format Integer Msg Void))
253 (define msg-print
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)])
261 (match out-format
262 ['single-line
263 (let ([nick (if nick nick uri)])
264 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
265 (parameterize
266 ([date-display-format 'iso-8601])
267 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
268 nick color text))]
269 ['multi-line
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"
272 (parameterize
273 ([date-display-format 'rfc2822])
274 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
275 (Msg-ts-orig msg)
276 nick uri color text))])))))
277
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}))?$")])
281 (λ (ts)
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)
284 (let*
285 ([tz-offset
286 (match* (tz-whole tz-sign tz-HH tz-MM)
287 [("Z" #f #f #f)
288 0]
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)))))]
295 [(a b c d)
296 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
297 0])]
298 [ts-orig ts]
299 [local-time? #f]
300 [ts-epoch (find-seconds (if SS (string->number SS) 0)
301 (string->number MM)
302 (string->number HH)
303 (string->number dd)
304 (string->number mm)
305 (string->number yyyy)
306 local-time?)])
307 (+ ts-epoch tz-offset))]
308 [_
309 (log-debug "Invalid timestamp: ~v" ts)
310 #f]))))
311
312 (: str->msg (-> Peer String (Option Msg)))
313 (define str->msg
314 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
315 (λ (from str)
316 (define from-str (peer->str from))
317 (define str-head (substring str 0 (min 100 (string-length str))))
318 (with-handlers*
319 ([exn:fail?
320 (λ (e)
321 (log-debug
322 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
323 str-head from-str e)
324 #f)])
325 (match (regexp-match re str)
326 [(list _wholething ts-orig text)
327 (let ([ts-epoch (rfc3339->epoch ts-orig)])
328 (if ts-epoch
329 (let ([mentions
330 (filter-map
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))
336 (begin
337 (log-debug
338 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
339 from-str str-head)
340 #f)))]
341 [_
342 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
343 #f])))))
344
345 (module+ test
346 ; TODO Test for when missing-nick case
347 (let* ([tzs (for*/list ([d '("-" "+")]
348 [h '("5" "05")]
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))]
355 [s '("" ":10")]
356 [f '("" ".1337")]
357 [z tzs]
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")
362 z)]
363 [m (str->msg p (string-append ts sep txt))])
364 (check-not-false m)
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))
368 )))
369
370 (let* ([ts "2020-11-18T22:22:09-0500"]
371 [tab " "]
372 [text "Lorem ipsum"]
373 [nick "foo"]
374 [uri "http://bar/"]
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 '())])
378 (check-equal?
379 (Msg-ts-epoch actual)
380 (Msg-ts-epoch expected)
381 "str->msg ts-epoch")
382 (check-equal?
383 (Msg-ts-orig actual)
384 (Msg-ts-orig expected)
385 "str->msg ts-orig")
386 (check-equal?
387 (Peer-nick (Msg-from actual))
388 (Peer-nick (Msg-from expected))
389 "str->msg nick")
390 (check-equal?
391 (Peer-uri (Msg-from actual))
392 (Peer-uri (Msg-from expected))
393 "str->msg uri")
394 (check-equal?
395 (Peer-uri-str (Msg-from actual))
396 (Peer-uri-str (Msg-from expected))
397 "str->msg uri-str")
398 (check-equal?
399 (Msg-text actual)
400 (Msg-text expected)
401 "str->msg text")))
402
403 (: str->lines (-> String (Listof String)))
404 (define (str->lines str)
405 (string-split str (regexp "[\r\n]+")))
406
407 (module+ test
408 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
409
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))))
414
415 (: cache-dir Path-String)
416 (define cache-dir (build-path tt-home-dir "cache"))
417
418 (define cache-object-dir (build-path cache-dir "objects"))
419
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)
426 digest)
427 (build-path cache-object-dir (hash-sha1 (url->string uri))))
428
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))))
432
433 (define url->cache-object-path
434 url->cache-file-path-v2)
435
436 (define (url->cache-etag-path uri)
437 (build-path cache-dir "etags" (uri-encode (url->string uri))))
438
439 (define (url->cache-lmod-path uri)
440 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
441
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)
450 (begin
451 (log-debug "Cache file not found for URI: ~a" (url->string uri))
452 #f)))
453
454 (: str->url (-> String (Option String)))
455 (define (str->url s)
456 (with-handlers*
457 ([exn:fail? (λ (e) #f)])
458 (string->url s)))
459
460 (: peer->str (-> Peer String))
461 (define (peer->str peer)
462 (match-define (Peer n _ u c) peer)
463 (format "~a~a~a"
464 (if n (format "~a " n) "")
465 u
466 (if c (format " # ~a" c) "")))
467
468 (: str->peer (-> String (Option Peer)))
469 (define (str->peer str)
470 (log-debug "Parsing peer string: ~v" str)
471 (match
472 (regexp-match
473 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
474 str)
475 [(list _wholething
476 _nick-with-space
477 nick
478 url
479 _comment-with-hash
480 comment)
481 (match (str->url url)
482 [#f
483 (log-error "Invalid URI in peer string: ~v" str)
484 #f]
485 [url
486 (Peer nick url (url->string url) comment)])]
487 [_
488 (log-debug "Invalid peer string: ~v" str)
489 #f]))
490
491 (module+ test
492 (check-equal?
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"))
495 (check-equal?
496 (str->peer "http://bar/file.txt # some rando")
497 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
498 (check-equal?
499 (str->peer "http://bar/file.txt #")
500 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
501 (check-equal?
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))
504 (check-equal?
505 (str->peer "http://bar/file.txt")
506 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
507 (check-equal?
508 (str->peer "foo http://bar/file.txt")
509 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
510 (check-equal?
511 (str->peer "foo bar # baz")
512 #f)
513 (check-equal?
514 (str->peer "foo bar://baz # quux")
515 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
516 (check-equal?
517 (str->peer "foo bar//baz # quux")
518 #f))
519
520 (: filter-comments (-> (Listof String) (Listof String)))
521 (define (filter-comments lines)
522 (filter-not (λ (line) (string-prefix? line "#")) lines))
523
524 (: str->peers (-> String (Listof Peer)))
525 (define (str->peers str)
526 (filter-map str->peer (filter-comments (str->lines str))))
527
528 (: peers->file (-> (Listof Peers) Path-String Void))
529 (define (peers->file peers path)
530 (display-lines-to-file
531 (map peer->str
532 (sort peers
533 (match-lambda**
534 [((Peer n1 _ _ _) (Peer n2 _ _ _))
535 (string<? (if n1 n1 "")
536 (if n2 n2 ""))])))
537 path
538 #:exists 'replace))
539
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))
544 (begin
545 (log-warning "File does not exist: ~v" (path->string file-path))
546 '())))
547
548 (define re-rfc2822
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")
550
551 (: b->n (-> Bytes (Option Number)))
552 (define (b->n b)
553 (string->number (bytes->string/utf-8 b)))
554
555 (: mon->num (-> Bytes Natural))
556 (define/match (mon->num mon)
557 [(#"Jan") 1]
558 [(#"Feb") 2]
559 [(#"Mar") 3]
560 [(#"Apr") 4]
561 [(#"May") 5]
562 [(#"Jun") 6]
563 [(#"Jul") 7]
564 [(#"Aug") 8]
565 [(#"Sep") 9]
566 [(#"Oct") 10]
567 [(#"Nov") 11]
568 [(#"Dec") 12])
569
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)
576 (b->n MM)
577 (b->n HH)
578 (b->n dd)
579 (mon->num mo)
580 (b->n yyyy)
581 #f)]
582 [_
583 #f]))
584
585 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
586 (define (header-get headers name)
587 (match (filter-map (curry extract-field name) headers)
588 [(list val) val]
589 [_ #f]))
590
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))
605 #f))
606 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
607 (define cached?
608 (or (and etag
609 (file-exists? cached-etag-path)
610 (bytes=? etag (file->bytes cached-etag-path))
611 (begin
612 (log-debug "ETags match, skipping the rest of ~v" u-str)
613 #t))
614 (and lmod-curr
615 lmod-prev
616 (<= lmod-curr lmod-prev)
617 (begin
618 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
619 #t))))
620 (if (not cached?)
621 (begin
622 (log-debug
623 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
624 u-str etag lmod)
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)
630 #:exists 'replace)
631 (when etag
632 (display-to-file etag cached-etag-path #:exists 'replace))
633 (when lmod
634 (display-to-file lmod cached-lmod-path #:exists 'replace))
635 'downloaded-new)
636 'skipped-cached))
637
638 (: uri-download
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
647 (thread (λ ()
648 ; Doing this instead of sync/timeout to distinguish error values,
649 ; rather than just have #f to work with.
650 (sleep timeout)
651 (channel-put timeout-chan '(error . timeout)))))
652 (define result-thread
653 (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.
659 ;
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.
663
664 ; TODO message db
665 ; - 1st try can just be an in-memory set that gets written-to
666 ; and read-from disk as a whole.
667 (define result
668 (with-handlers
669 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
670 ([exn:fail:network?
671 (λ (e) `(error . (net-error . ,e)))]
672 [exn?
673 (λ (e) `(error . (other . ,e)))])
674 (define-values (status-line headers body-input)
675 (http-sendrecv/url
676 u
677 #:headers (list (format "User-Agent: ~a" user-agent-str))))
678 `(ok . ,(Resp status-line headers body-input))))
679 (channel-put result-chan result))))
680 (define result
681 (sync timeout-chan
682 result-chan))
683 (kill-thread result-thread)
684 (kill-thread timeout-thread)
685 (match result
686 [(cons 'error _)
687 result]
688 [(cons 'ok (Resp status-line headers body-input))
689 (log-debug "headers: ~v" headers)
690 (log-debug "status-line: ~v" status-line)
691 (define status
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.
695 (let ([result
696 (match status
697 [200
698 `(ok . ,(uri-download-from-port u headers body-input))]
699 [_
700 `(error . (http . ,status))])])
701 (close-input-port body-input)
702 result)]))
703
704 (: timeline-print (-> Out-Format (Listof Msg) Void))
705 (define (timeline-print out-format timeline)
706 (match timeline
707 ['()
708 (void)]
709 [(cons first-msg _)
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)
714 (cons from i))])
715 (cons (Msg-from first-msg) 0)
716 timeline))]))
717
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))
723 ; TODO Expire cache
724 (if msgs-data
725 (str->msgs peer msgs-data)
726 '()))
727
728 (: peer-download
729 (-> Positive-Float Peer
730 (Result (U 'skipped-cached 'downloaded-new)
731 Any)))
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)
740 u
741 result)
742 result)
743
744 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
745 (define (timeline-download num-workers timeout peers)
746 (define results
747 (concurrent-filter-map num-workers
748 (λ (p) (cons p (peer-download timeout p)))
749 peers))
750 (define peers-ok
751 (filter-map (match-lambda
752 [(cons p (cons 'ok _)) p]
753 [(cons _ (cons 'error e)) #f])
754 results))
755 (define peers-err
756 (filter-map (match-lambda
757 [(cons _ (cons 'ok _))
758 #f]
759 [(cons p (cons 'error e))
760 (struct-copy Peer p [comment (format "~s" e)])])
761 results))
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")))
764
765 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
766 (define (peers->timeline peers)
767 (append* (filter-map peer->msgs peers)))
768
769 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
770 (define (timeline-sort msgs order)
771 (define cmp (match order
772 ['old->new <]
773 ['new->old >]))
774 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
775 (Msg-ts-epoch b)))))
776
777 (: paths->peers (-> (Listof String) (Listof Peer)))
778 (define (paths->peers paths)
779 (let* ([paths (match paths
780 ['()
781 (let ([peer-refs-file (build-path tt-home-dir "peers")])
782 (log-debug
783 "No peer ref file paths provided, defaulting to ~v"
784 (path->string peer-refs-file))
785 (list peer-refs-file))]
786 [paths
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))
791 peers))
792
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)
798 [#f #f]
799 [url (Peer nick url url-str #f)]))
800
801 (: peers-cached (-> (Listof Peer)))
802 (define (peers-cached)
803 ; TODO Expire cache?
804 (filter-map cache-filename->peer (directory-list cache-object-dir)))
805
806 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
807 (define (peers-mentioned msgs)
808 (append* (map Msg-mentions msgs)))
809
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))
814
815 (: log-writer-start (-> Log-Level Thread))
816 (define (log-writer-start level)
817 (let* ([logger
818 (make-logger #f #f level #f)]
819 [log-receiver
820 (make-log-receiver logger level)]
821 [log-writer
822 (thread
823 (λ ()
824 (parameterize
825 ([date-display-format 'iso-8601])
826 (let loop ()
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)
830 (loop))))))])
831 (current-logger logger)
832 log-writer))
833
834 (: msgs->nick-hist (-> (Listof Msg) Nick-Hist))
835 (define (msgs->nick-hist msgs)
836 (foldl
837 (λ (msg url->nick->hist)
838 (match-define (Msg curr _ from _ mentions) msg)
839 (foldl
840 (λ (peer url->nick->hist)
841 (match-define (Peer nick url _ _) peer)
842 (if nick
843 (hash-update url->nick->hist
844 url
845 (λ (nick->hist)
846 (hash-update nick->hist
847 nick
848 (match-lambda
849 [(Hist freq prev)
850 (Hist (+ 1 freq) (max prev curr))])
851 (Hist 0 0)))
852 (hash))
853 url->nick->hist))
854 url->nick->hist
855 (cons from mentions)))
856 (hash)
857 msgs))
858
859 (: update-nicks-history (-> (Listof Msg) Void))
860 (define (update-nicks-history msgs)
861 (hash-for-each
862 (msgs->nick-hist msgs)
863 (λ (url nick->hist)
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
867 (map (match-lambda
868 [(cons nick (Hist freq last))
869 (format "~a ~a ~a" nick freq last)])
870 (sort (hash->list nick->hist)
871 (match-lambda**
872 [((cons _ (Hist a _)) (cons _ (Hist b _)))
873 (> a b)])))
874 path
875 #:exists 'replace))))
876
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)
880 [#f #f]
881 [nick->hist
882 (match (sort (hash->list nick->hist)
883 (λ (a b) (> (by (cdr a))
884 (by (cdr b)))))
885 ['() #f]
886 [(cons (cons nick _) _) nick])]))
887
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))
891
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))
895
896 (module+ test
897 (let* ([url-str "http://foo"]
898 [url (string->url url-str)]
899 [nick1 "a"]
900 [nick2 "b"]
901 [nick3 "c"]
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)]
906 [msgs
907 (map (match-lambda
908 [(cons ts-str nick)
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)))]
917 [hist
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)))
924
925 (: crawl (-> Void))
926 (define (crawl)
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")]
932 [peers-parsed-file
933 (build-path tt-home-dir "peers-parsed")]
934 [peers-cached-file
935 (build-path tt-home-dir "peers-cached")]
936 [peers-cached
937 (peers-cached)]
938 [cached-timeline
939 (peers->timeline peers-cached)]
940 [peers-mentioned-curr
941 (peers-mentioned cached-timeline)]
942 [peers-mentioned-prev
943 (file->peers peers-mentioned-file)]
944 [peers-all-prev
945 (file->peers peers-all-file)]
946 [peers-mentioned
947 (begin
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))]
953 [peers-all
954 (peers-merge peers-mentioned
955 peers-all-prev
956 peers-cached)]
957 [peers-discovered
958 (set->list (set-subtract (make-immutable-peers peers-all)
959 (make-immutable-peers peers-all-prev)))]
960 [peers-parsed
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)
969 (pretty-format (map
970 (match-lambda
971 [(Peer n _ u c) (list n u c)])
972 peers-discovered)))
973 (peers->file peers-cached
974 peers-cached-file)
975 (peers->file peers-mentioned
976 peers-mentioned-file)
977 (peers->file peers-parsed
978 peers-parsed-file)
979 (peers->file peers-all
980 peers-all-file)))
981
982 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
983 (define (read file-paths ts-min ts-max order out-format)
984 (let* ([peers
985 (paths->peers file-paths)]
986 [msgs
987 (timeline-sort (peers->timeline peers) order)]
988 [include?
989 (λ (m)
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))))
993
994 (: upload (-> Void))
995 (define (upload)
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")))
998 (exit 0)
999 (exit 1)))
1000
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."
1007 (length peers)
1008 (/ real-ms 1000.0))))
1009
1010 (: dispatch (-> String Void))
1011 (define (dispatch command)
1012 (match 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]
1017 [timeout 10.0])
1018 (command-line
1019 #:program "tt download"
1020 #:once-each
1021 [("-j" "--jobs")
1022 njobs "Number of concurrent jobs."
1023 (set! num-workers (string->number njobs))]
1024 [("-t" "--timeout")
1025 seconds "Timeout seconds per request."
1026 (set! timeout (string->number seconds))]
1027 #:args file-paths
1028 (download file-paths num-workers timeout)))]
1029 [(or "u" "upload")
1030 (command-line
1031 #:program "tt upload" #:args () (upload))]
1032 [(or "r" "read")
1033 (let ([out-format 'multi-line]
1034 [order 'old->new]
1035 [ts-min #f]
1036 [ts-max #f])
1037 (command-line
1038 #:program "tt read"
1039 #:once-each
1040 [("-r" "--rev")
1041 "Reverse displayed timeline order."
1042 (set! order 'new->old)]
1043 [("-m" "--min")
1044 m "Earliest time to display (ignore anything before it)."
1045 (set! ts-min (rfc3339->epoch m))]
1046 [("-x" "--max")
1047 x "Latest time to display (ignore anything after it)."
1048 (set! ts-max (rfc3339->epoch x))]
1049 #:once-any
1050 [("-s" "--short")
1051 "Short output format"
1052 (set! out-format 'single-line)]
1053 [("-l" "--long")
1054 "Long output format"
1055 (set! out-format 'multi-line)]
1056 #:args file-paths
1057 (read file-paths ts-min ts-max order out-format)))]
1058 [(or "c" "crawl")
1059 (command-line
1060 #:program "tt crawl" #:args () (crawl))]
1061 [command
1062 (eprintf "Error: invalid command: ~v\n" command)
1063 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1064 (exit 1)]))
1065
1066 (module+ main
1067 (let ([log-level 'info])
1068 (command-line
1069 #:program
1070 "tt"
1071 #:once-each
1072 [("-d" "--debug")
1073 "Enable debug log level."
1074 (set! log-level 'debug)]
1075 #:help-labels
1076 ""
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)."
1083 ""
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
1089 (dispatch command)
1090 (log-writer-stop log-writer))))
This page took 0.145582 seconds and 4 git commands to generate.