e002e71da561eb8b175244894e753b469f19cc30
[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 (: prog Prog)
65 (define prog
66 (Prog "tt" (info:#%info-lookup 'version)))
67
68 (: user-default User)
69 (define user-default
70 (User (string->url "https://github.com/xandkar/tt") #f))
71
72 (: user->str (-> User String))
73 (define (user->str user)
74 (match-define (User u0 n) user)
75 (define u (url->string u0))
76 (if n
77 (format "+~a; @~a" u n)
78 (format "+~a" u )))
79
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)))
84
85 (: user->user-agent User)
86 (define (user->user-agent user)
87 (User-Agent user prog))
88
89 (: user-agent-str String)
90 (define user-agent-str
91 (user-agent->str (user->user-agent user-default)))
92
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))
97
98 (: file->user (-> Path-String User))
99 (define (file->user filename)
100 (if (file-exists? filename)
101 (match (file->peers filename)
102 [(list p)
103 (log-info
104 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
105 filename
106 (peer->str p))
107 (peer->user p)]
108 [(list* p _)
109 (log-warning
110 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
111 filename
112 (peer->str p))
113 (peer->user p)]
114 ['()
115 (log-warning
116 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
117 filename
118 user-default)
119 user-default])
120 (begin
121 (log-warning
122 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
123 filename
124 user-default)
125 user-default)))
126
127 (: peer->user (-> Peer User))
128 (define (peer->user p)
129 (match-define (Peer n u _ _) p)
130 (User u n))
131
132 (: peers-equal? (-> Peer Peer Boolean))
133 (define (peers-equal? p1 p2)
134 (equal? (Peer-uri-str p1)
135 (Peer-uri-str p2)))
136
137 (: peer-hash (-> Peer Fixnum))
138 (define (peer-hash p)
139 (equal-hash-code (Peer-uri-str p)))
140
141 (define-custom-set-types peers
142 #:elem? Peer?
143 peers-equal?
144 peer-hash)
145 ; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
146 ; the following contract violations:
147 ;
148 ; custom-elem-contents: contract violation
149 ; expected: custom-elem?
150 ; given: #f
151 ; context...:
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)
156 ;
157 ; TODO Investigate why and make a minimal reproducible test case.
158
159 (: peers-merge (-> (Listof Peer) * (Listof Peer)))
160 (define (peers-merge . peer-sets)
161 (define groups
162 (foldl
163 (λ (p groups)
164 (hash-update groups (Peer-uri-str p) (λ (group) (cons p group)) '()))
165 (hash)
166 (append* peer-sets)))
167 (define (merge peers)
168 (match peers
169 ['() (raise 'impossible)]
170 [(list p) p]
171 [(list* p1 p2 ps)
172 (let* ([n1 (Peer-nick p1)]
173 [n2 (Peer-nick p2)]
174 [p (cond
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]
180 [else
181 (raise 'impossible)])])
182 (merge (cons p ps)))]))
183 (sort (map merge (hash-values groups))
184 (match-lambda**
185 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
186
187 (module+ test
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)]
193 [s1 (list p1)]
194 [s2 (list p2 p3)])
195 (check-equal? (list p3 p2) (peers-merge s1 s2))
196 (check-equal? (list p3 p2) (peers-merge s2 s1))))
197
198 (: tt-home-dir Path-String)
199 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
200
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))
207 (λ ()
208 (define self : Thread (current-thread))
209 (: work (∀ (α) (-> α)))
210 (define (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
215 (define y (f x))
216 (when y (thread-send parent (cons 'result y)))
217 (work))]))
218 (work)))
219 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
220 (define (dispatch ws xs ys)
221 (if (empty? ws)
222 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
227 ['() (begin
228 (thread-send thd 'done)
229 (dispatch ws xs ys))]
230 [(cons x xs) (begin
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)
237 results)
238
239 (module+ test
240 (let* ([f (λ (x) (if (even? x) x #f))]
241 [xs (range 11)]
242 [actual (sort (concurrent-filter-map 10 f xs) <)]
243 [expected (sort ( filter-map f xs) <)])
244 (check-equal? actual expected "concurrent-filter-map")))
245
246 (: msg-print (-> Out-Format Integer Msg Void))
247 (define msg-print
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)])
255 (match out-format
256 ['single-line
257 (let ([nick (if nick nick uri)])
258 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
259 (parameterize
260 ([date-display-format 'iso-8601])
261 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
262 nick color text))]
263 ['multi-line
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"
266 (parameterize
267 ([date-display-format 'rfc2822])
268 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
269 (Msg-ts-orig msg)
270 nick uri color text))])))))
271
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}))?$")])
275 (λ (ts)
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)
278 (let*
279 ([tz-offset
280 (match* (tz-whole tz-sign tz-HH tz-MM)
281 [("Z" #f #f #f)
282 0]
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)))))]
289 [(a b c d)
290 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
291 0])]
292 [ts-orig ts]
293 [local-time? #f]
294 [ts-epoch (find-seconds (if SS (string->number SS) 0)
295 (string->number MM)
296 (string->number HH)
297 (string->number dd)
298 (string->number mm)
299 (string->number yyyy)
300 local-time?)])
301 (+ ts-epoch tz-offset))]
302 [_
303 (log-debug "Invalid timestamp: ~v" ts)
304 #f]))))
305
306 (: str->msg (-> Peer String (Option Msg)))
307 (define str->msg
308 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
309 (λ (from str)
310 (define from-str (peer->str from))
311 (define str-head (substring str 0 (min 100 (string-length str))))
312 (with-handlers*
313 ([exn:fail?
314 (λ (e)
315 (log-debug
316 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
317 str-head from-str e)
318 #f)])
319 (match (regexp-match re str)
320 [(list _wholething ts-orig text)
321 (let ([ts-epoch (rfc3339->epoch ts-orig)])
322 (if ts-epoch
323 (let ([mentions
324 (filter-map
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))
330 (begin
331 (log-debug
332 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
333 from-str str-head)
334 #f)))]
335 [_
336 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
337 #f])))))
338
339 (module+ test
340 ; TODO Test for when missing-nick case
341 (let* ([tzs (for*/list ([d '("-" "+")]
342 [h '("5" "05")]
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))]
349 [s '("" ":10")]
350 [f '("" ".1337")]
351 [z tzs]
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")
356 z)]
357 [m (str->msg p (string-append ts sep txt))])
358 (check-not-false m)
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))
362 )))
363
364 (let* ([ts "2020-11-18T22:22:09-0500"]
365 [tab " "]
366 [text "Lorem ipsum"]
367 [nick "foo"]
368 [uri "http://bar/"]
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 '())])
372 (check-equal?
373 (Msg-ts-epoch actual)
374 (Msg-ts-epoch expected)
375 "str->msg ts-epoch")
376 (check-equal?
377 (Msg-ts-orig actual)
378 (Msg-ts-orig expected)
379 "str->msg ts-orig")
380 (check-equal?
381 (Peer-nick (Msg-from actual))
382 (Peer-nick (Msg-from expected))
383 "str->msg nick")
384 (check-equal?
385 (Peer-uri (Msg-from actual))
386 (Peer-uri (Msg-from expected))
387 "str->msg uri")
388 (check-equal?
389 (Peer-uri-str (Msg-from actual))
390 (Peer-uri-str (Msg-from expected))
391 "str->msg uri-str")
392 (check-equal?
393 (Msg-text actual)
394 (Msg-text expected)
395 "str->msg text")))
396
397 (: str->lines (-> String (Listof String)))
398 (define (str->lines str)
399 (string-split str (regexp "[\r\n]+")))
400
401 (module+ test
402 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
403
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))))
410
411 (: cache-dir Path-String)
412 (define cache-dir (build-path tt-home-dir "cache"))
413
414 (define cache-object-dir (build-path cache-dir "objects"))
415
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)
422 digest)
423 (build-path cache-object-dir (hash-sha1 (url->string uri))))
424
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))))
428
429 (define url->cache-object-path
430 url->cache-file-path-v2)
431
432 (define (url->cache-etag-path uri)
433 (build-path cache-dir "etags" (uri-encode (url->string uri))))
434
435 (define (url->cache-lmod-path uri)
436 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
437
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)
446 (begin
447 (log-debug "Cache file not found for URI: ~a" (url->string uri))
448 #f)))
449
450 (: str->url (-> String (Option String)))
451 (define (str->url s)
452 (with-handlers*
453 ([exn:fail? (λ (e) #f)])
454 (string->url s)))
455
456 (: peer->str (-> Peer String))
457 (define (peer->str peer)
458 (match-define (Peer n _ u c) peer)
459 (format "~a~a~a"
460 (if n (format "~a " n) "")
461 u
462 (if c (format " # ~a" c) "")))
463
464 (: str->peer (-> String (Option Peer)))
465 (define (str->peer str)
466 (log-debug "Parsing peer string: ~v" str)
467 (match
468 (regexp-match
469 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
470 str)
471 [(list _wholething
472 _nick-with-space
473 nick
474 url
475 _comment-with-hash
476 comment)
477 (match (str->url url)
478 [#f
479 (log-error "Invalid URI in peer string: ~v" str)
480 #f]
481 [url
482 (Peer nick url (url->string url) comment)])]
483 [_
484 (log-debug "Invalid peer string: ~v" str)
485 #f]))
486
487 (module+ test
488 (check-equal?
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"))
491 (check-equal?
492 (str->peer "http://bar/file.txt # some rando")
493 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
494 (check-equal?
495 (str->peer "http://bar/file.txt #")
496 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
497 (check-equal?
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))
500 (check-equal?
501 (str->peer "http://bar/file.txt")
502 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
503 (check-equal?
504 (str->peer "foo http://bar/file.txt")
505 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
506 (check-equal?
507 (str->peer "foo bar # baz")
508 #f)
509 (check-equal?
510 (str->peer "foo bar://baz # quux")
511 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
512 (check-equal?
513 (str->peer "foo bar//baz # quux")
514 #f))
515
516 (: filter-comments (-> (Listof String) (Listof String)))
517 (define (filter-comments lines)
518 (filter-not (λ (line) (string-prefix? line "#")) lines))
519
520 (: str->peers (-> String (Listof Peer)))
521 (define (str->peers str)
522 (filter-map str->peer (filter-comments (str->lines str))))
523
524 (: peers->file (-> (Listof Peers) Path-String Void))
525 (define (peers->file peers path)
526 (display-lines-to-file
527 (map peer->str
528 (sort peers
529 (match-lambda**
530 [((Peer n1 _ _ _) (Peer n2 _ _ _))
531 (string<? (if n1 n1 "")
532 (if n2 n2 ""))])))
533 path
534 #:exists 'replace))
535
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))
540 (begin
541 (log-warning "File does not exist: ~v" (path->string file-path))
542 '())))
543
544 (define re-rfc2822
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")
546
547 (: b->n (-> Bytes (Option Number)))
548 (define (b->n b)
549 (string->number (bytes->string/utf-8 b)))
550
551 (: mon->num (-> Bytes Natural))
552 (define/match (mon->num mon)
553 [(#"Jan") 1]
554 [(#"Feb") 2]
555 [(#"Mar") 3]
556 [(#"Apr") 4]
557 [(#"May") 5]
558 [(#"Jun") 6]
559 [(#"Jul") 7]
560 [(#"Aug") 8]
561 [(#"Sep") 9]
562 [(#"Oct") 10]
563 [(#"Nov") 11]
564 [(#"Dec") 12])
565
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)
572 (b->n MM)
573 (b->n HH)
574 (b->n dd)
575 (mon->num mo)
576 (b->n yyyy)
577 #f)]
578 [_
579 #f]))
580
581 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
582 (define (header-get headers name)
583 (match (filter-map (curry extract-field name) headers)
584 [(list val) val]
585 [_ #f]))
586
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))
604 #f))
605 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
606 (define cached?
607 (or (and etag
608 (file-exists? cached-etag-path)
609 (bytes=? etag (file->bytes cached-etag-path))
610 (begin
611 (log-debug "ETags match, skipping the rest of ~v" u-str)
612 #t))
613 (and lmod-curr
614 lmod-prev
615 (<= lmod-curr lmod-prev)
616 (begin
617 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
618 #t))))
619 (if (not cached?)
620 (begin
621 (log-debug
622 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
623 u-str etag lmod)
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)
629 #:exists 'replace)
630 (when etag
631 (display-to-file etag cached-etag-path #:exists 'replace))
632 (when lmod
633 (display-to-file lmod cached-lmod-path #:exists 'replace))
634 'downloaded-new)
635 'skipped-cached))
636
637 (: uri-download
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
646 (thread (λ ()
647 ; Doing this instead of sync/timeout to distinguish error values,
648 ; rather than just have #f to work with.
649 (sleep timeout)
650 (channel-put timeout-chan '(error . timeout)))))
651 (define result-thread
652 (thread (λ ()
653 (define result
654 (with-handlers
655 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
656 ([exn:fail:network?
657 (λ (e) `(error . (net-error . ,e)))]
658 [exn?
659 (λ (e) `(error . (other . ,e)))])
660 (define-values (status-line headers body-input)
661 (http-sendrecv/url
662 u
663 #:headers (list (format "User-Agent: ~a" user-agent-str))))
664 (log-debug "headers: ~v" headers)
665 (log-debug "status-line: ~v" status-line)
666 (define status
667 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
668 (log-debug "status: ~v" status)
669 (let ([result
670 ; TODO Handle redirects.
671 ; TODO Should a redirect update a peer URL?
672 (match status
673 [200
674 `(ok . ,(uri-download-from-port u headers body-input))]
675 [_
676 `(error . (http-not-ok . ,status))])])
677 (close-input-port body-input)
678 result)))
679 (channel-put result-chan result))))
680 (define result (sync timeout-chan result-chan))
681 (kill-thread result-thread)
682 (kill-thread timeout-thread)
683 result)
684
685 (: timeline-print (-> Out-Format (Listof Msg) Void))
686 (define (timeline-print out-format timeline)
687 (match timeline
688 ['()
689 (void)]
690 [(cons first-msg _)
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)
695 (cons from i))])
696 (cons (Msg-from first-msg) 0)
697 timeline))]))
698
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))
704 ; TODO Expire cache
705 (if msgs-data
706 (str->msgs peer msgs-data)
707 '()))
708
709 (: peer-download
710 (-> Positive-Float Peer
711 (Result (U 'skipped-cached 'downloaded-new)
712 Any)))
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)
721 u
722 result)
723 result)
724
725 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
726 (define (timeline-download num-workers timeout peers)
727 (define results
728 (concurrent-filter-map num-workers
729 (λ (p) (cons p (peer-download timeout p)))
730 peers))
731 (define peers-ok
732 (filter-map (match-lambda
733 [(cons p (cons 'ok _)) p]
734 [(cons _ (cons 'error e)) #f])
735 results))
736 (define peers-err
737 (filter-map (match-lambda
738 [(cons _ (cons 'ok _))
739 #f]
740 [(cons p (cons 'error e))
741 (struct-copy Peer p [comment (format "~s" e)])])
742 results))
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")))
745
746 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
747 (define (peers->timeline peers)
748 (append* (filter-map peer->msgs peers)))
749
750 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
751 (define (timeline-sort msgs order)
752 (define cmp (match order
753 ['old->new <]
754 ['new->old >]))
755 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
756 (Msg-ts-epoch b)))))
757
758 (: paths->peers (-> (Listof String) (Listof Peer)))
759 (define (paths->peers paths)
760 (let* ([paths (match paths
761 ['()
762 (let ([peer-refs-file (build-path tt-home-dir "peers")])
763 (log-debug
764 "No peer ref file paths provided, defaulting to ~v"
765 (path->string peer-refs-file))
766 (list peer-refs-file))]
767 [paths
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))
772 peers))
773
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)
779 [#f #f]
780 [url (Peer nick url url-str #f)]))
781
782 (: peers-cached (-> (Listof Peer)))
783 (define (peers-cached)
784 ; TODO Expire cache?
785 (filter-map cache-filename->peer (directory-list cache-object-dir)))
786
787 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
788 (define (peers-mentioned msgs)
789 (append* (map Msg-mentions msgs)))
790
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))
795
796 (: log-writer-start (-> Log-Level Thread))
797 (define (log-writer-start level)
798 (let* ([logger
799 (make-logger #f #f level #f)]
800 [log-receiver
801 (make-log-receiver logger level)]
802 [log-writer
803 (thread
804 (λ ()
805 (parameterize
806 ([date-display-format 'iso-8601])
807 (let loop ()
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)
811 (loop))))))])
812 (current-logger logger)
813 log-writer))
814
815 (: msgs->nick-hist (-> (Listof Msg) Nick-Hist))
816 (define (msgs->nick-hist msgs)
817 (foldl
818 (λ (msg url->nick->hist)
819 (match-define (Msg curr _ from _ mentions) msg)
820 (foldl
821 (λ (peer url->nick->hist)
822 (match-define (Peer nick url _ _) peer)
823 (if nick
824 (hash-update url->nick->hist
825 url
826 (λ (nick->hist)
827 (hash-update nick->hist
828 nick
829 (match-lambda
830 [(Hist freq prev)
831 (Hist (+ 1 freq) (max prev curr))])
832 (Hist 0 0)))
833 (hash))
834 url->nick->hist))
835 url->nick->hist
836 (cons from mentions)))
837 (hash)
838 msgs))
839
840 (: update-nicks-history-files (-> Nick-Hist Void))
841 (define (update-nicks-history-files nick-hist)
842 (hash-for-each
843 nick-hist
844 (λ (url 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
848 (map (match-lambda
849 [(cons nick (Hist freq last))
850 (format "~a ~a ~a" nick freq last)])
851 (sort (hash->list nick->hist)
852 (match-lambda**
853 [((cons _ (Hist a _)) (cons _ (Hist b _)))
854 (> a b)])))
855 path
856 #:exists 'replace))))
857
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)
861 [#f #f]
862 [nick->hist
863 (match (sort (hash->list nick->hist)
864 (λ (a b) (> (by (cdr a))
865 (by (cdr b)))))
866 ['() #f]
867 [(cons (cons nick _) _) nick])]))
868
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))
872
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))
876
877 (: peers-update-nick-to-common (-> Nick-Hist (Listof Peer) (Listof Peer)))
878 (define (peers-update-nick-to-common nick-hist peers)
879 (map
880 (λ (p)
881 (match (nick-hist-common nick-hist (Peer-uri p))
882 [#f p]
883 [n (struct-copy Peer p [nick n])]))
884 peers))
885
886 (module+ test
887 (let* ([url-str "http://foo"]
888 [url (string->url url-str)]
889 [nick1 "a"]
890 [nick2 "b"]
891 [nick3 "c"]
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)]
896 [msgs
897 (map (match-lambda
898 [(cons ts-str nick)
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)))]
907 [hist
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)))
914
915 (: crawl (-> Void))
916 (define (crawl)
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")]
922 [peers-parsed-file
923 (build-path tt-home-dir "peers-parsed")]
924 [peers-cached-file
925 (build-path tt-home-dir "peers-cached")]
926 [peers-cached
927 (peers-cached)]
928 [cached-timeline
929 (peers->timeline peers-cached)]
930 [nick-hist
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)]
936 [peers-all-prev
937 (file->peers peers-all-file)]
938 [peers-mentioned
939 (peers-merge peers-mentioned-prev
940 peers-mentioned-curr)]
941 [peers-all
942 (peers-update-nick-to-common
943 nick-hist
944 (peers-merge peers-mentioned
945 peers-all-prev
946 peers-cached))]
947 [peers-discovered
948 (set->list (set-subtract (make-immutable-peers peers-all)
949 (make-immutable-peers peers-all-prev)))]
950 [peers-parsed
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)
959 (pretty-format (map
960 (match-lambda
961 [(Peer n _ u c) (list n u c)])
962 peers-discovered)))
963 (update-nicks-history-files nick-hist)
964 (peers->file peers-cached
965 peers-cached-file)
966 (peers->file peers-mentioned
967 peers-mentioned-file)
968 (peers->file peers-parsed
969 peers-parsed-file)
970 (peers->file peers-all
971 peers-all-file)))
972
973 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
974 (define (read file-paths ts-min ts-max order out-format)
975 (let* ([peers
976 (paths->peers file-paths)]
977 [msgs
978 (timeline-sort (peers->timeline peers) order)]
979 [include?
980 (λ (m)
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))))
984
985 (: upload (-> Void))
986 (define (upload)
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")))
989 (exit 0)
990 (exit 1)))
991
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."
998 (length peers)
999 (/ real-ms 1000.0))))
1000
1001 (: dispatch (-> String Void))
1002 (define (dispatch command)
1003 (match 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]
1008 [timeout 10.0])
1009 (command-line
1010 #:program "tt download"
1011 #:once-each
1012 [("-j" "--jobs")
1013 njobs "Number of concurrent jobs."
1014 (set! num-workers (string->number njobs))]
1015 [("-t" "--timeout")
1016 seconds "Timeout seconds per request."
1017 (set! timeout (string->number seconds))]
1018 #:args file-paths
1019 (download file-paths num-workers timeout)))]
1020 [(or "u" "upload")
1021 (command-line
1022 #:program "tt upload" #:args () (upload))]
1023 [(or "r" "read")
1024 (let ([out-format 'multi-line]
1025 [order 'old->new]
1026 [ts-min #f]
1027 [ts-max #f])
1028 (command-line
1029 #:program "tt read"
1030 #:once-each
1031 [("-r" "--rev")
1032 "Reverse displayed timeline order."
1033 (set! order 'new->old)]
1034 [("-m" "--min")
1035 m "Earliest time to display (ignore anything before it)."
1036 (set! ts-min (rfc3339->epoch m))]
1037 [("-x" "--max")
1038 x "Latest time to display (ignore anything after it)."
1039 (set! ts-max (rfc3339->epoch x))]
1040 #:once-any
1041 [("-s" "--short")
1042 "Short output format"
1043 (set! out-format 'single-line)]
1044 [("-l" "--long")
1045 "Long output format"
1046 (set! out-format 'multi-line)]
1047 #:args file-paths
1048 (read file-paths ts-min ts-max order out-format)))]
1049 [(or "c" "crawl")
1050 (command-line
1051 #:program "tt crawl" #:args () (crawl))]
1052 [command
1053 (eprintf "Error: invalid command: ~v\n" command)
1054 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1055 (exit 1)]))
1056
1057 (module+ main
1058 (let ([log-level 'info])
1059 (command-line
1060 #:program
1061 "tt"
1062 #:once-each
1063 [("-d" "--debug")
1064 "Enable debug log level."
1065 (set! log-level 'debug)]
1066 #:help-labels
1067 ""
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)."
1074 ""
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
1080 (dispatch command)
1081 (log-writer-stop log-writer))))
This page took 0.156626 seconds and 3 git commands to generate.