16dffac459fab5c49da8b25b355ccf55cb1d9adb
[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 (: pub-peers-dir Path-String)
202 (define pub-peers-dir (build-path tt-home-dir "peers"))
203
204 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
205 (define (concurrent-filter-map num-workers f xs)
206 ; TODO preserve order of elements OR communicate that reorder is expected
207 ; TODO switch from mailboxes to channels
208 (define (make-worker id f)
209 (define parent (current-thread))
210 (λ ()
211 (define self : Thread (current-thread))
212 (: work (∀ (α) (-> α)))
213 (define (work)
214 (thread-send parent (cons 'next self))
215 (match (thread-receive)
216 ['done (thread-send parent (cons 'exit id))]
217 [(cons 'unit x) (begin
218 (define y (f x))
219 (when y (thread-send parent (cons 'result y)))
220 (work))]))
221 (work)))
222 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
223 (define (dispatch ws xs ys)
224 (if (empty? ws)
225 ys
226 (match (thread-receive)
227 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
228 [(cons 'result y) (dispatch ws xs (cons y ys))]
229 [(cons 'next thd) (match xs
230 ['() (begin
231 (thread-send thd 'done)
232 (dispatch ws xs ys))]
233 [(cons x xs) (begin
234 (thread-send thd (cons 'unit x))
235 (dispatch ws xs ys))])])))
236 (define workers (range num-workers))
237 (define threads (map (λ (id) (thread (make-worker id f))) workers))
238 (define results (dispatch workers xs '()))
239 (for-each thread-wait threads)
240 results)
241
242 (module+ test
243 (let* ([f (λ (x) (if (even? x) x #f))]
244 [xs (range 11)]
245 [actual (sort (concurrent-filter-map 10 f xs) <)]
246 [expected (sort ( filter-map f xs) <)])
247 (check-equal? actual expected "concurrent-filter-map")))
248
249 (: msg-print (-> Out-Format Integer Msg Void))
250 (define msg-print
251 (let* ([colors (vector 36 33)]
252 [n (vector-length colors)])
253 (λ (out-format color-i msg)
254 (let ([color (vector-ref colors (modulo color-i n))]
255 [nick (Peer-nick (Msg-from msg))]
256 [uri (Peer-uri-str (Msg-from msg))]
257 [text (Msg-text msg)])
258 (match out-format
259 ['single-line
260 (let ([nick (if nick nick uri)])
261 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
262 (parameterize
263 ([date-display-format 'iso-8601])
264 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
265 nick color text))]
266 ['multi-line
267 (let ([nick (if nick (string-append nick " ") "")])
268 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
269 (parameterize
270 ([date-display-format 'rfc2822])
271 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
272 (Msg-ts-orig msg)
273 nick uri color text))])))))
274
275 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
276 (define rfc3339->epoch
277 (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}))?$")])
278 (λ (ts)
279 (match (regexp-match re ts)
280 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
281 (let*
282 ([tz-offset
283 (match* (tz-whole tz-sign tz-HH tz-MM)
284 [("Z" #f #f #f)
285 0]
286 [(_ (or "-" "+") (? identity h) (? identity m))
287 (let ([h (string->number h)]
288 [m (string->number m)]
289 ; Reverse to get back to UTC:
290 [op (match tz-sign ["+" -] ["-" +])])
291 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
292 [(a b c d)
293 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
294 0])]
295 [ts-orig ts]
296 [local-time? #f]
297 [ts-epoch (find-seconds (if SS (string->number SS) 0)
298 (string->number MM)
299 (string->number HH)
300 (string->number dd)
301 (string->number mm)
302 (string->number yyyy)
303 local-time?)])
304 (+ ts-epoch tz-offset))]
305 [_
306 (log-debug "Invalid timestamp: ~v" ts)
307 #f]))))
308
309 (: str->msg (-> Peer String (Option Msg)))
310 (define str->msg
311 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
312 (λ (from str)
313 (define from-str (peer->str from))
314 (define str-head (substring str 0 (min 100 (string-length str))))
315 (with-handlers*
316 ([exn:fail?
317 (λ (e)
318 (log-debug
319 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
320 str-head from-str e)
321 #f)])
322 (match (regexp-match re str)
323 [(list _wholething ts-orig text)
324 (let ([ts-epoch (rfc3339->epoch ts-orig)])
325 (if ts-epoch
326 (let ([mentions
327 (filter-map
328 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
329 [(list _wholething nick-uri)
330 (str->peer nick-uri)]))
331 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
332 (Msg ts-epoch ts-orig from text mentions))
333 (begin
334 (log-debug
335 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
336 from-str str-head)
337 #f)))]
338 [_
339 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
340 #f])))))
341
342 (module+ test
343 ; TODO Test for when missing-nick case
344 (let* ([tzs (for*/list ([d '("-" "+")]
345 [h '("5" "05")]
346 [m '("00" ":00" "57" ":57")])
347 (string-append d h m))]
348 [tzs (list* "" "Z" tzs)])
349 (for* ([n '("fake-nick")]
350 [u '("http://fake-uri")]
351 [p (list (Peer n (string->url u) u #f))]
352 [s '("" ":10")]
353 [f '("" ".1337")]
354 [z tzs]
355 [sep (list "\t" " ")]
356 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
357 (let* ([ts (string-append "2020-11-18T22:22"
358 (if (non-empty-string? s) s ":00")
359 z)]
360 [m (str->msg p (string-append ts sep txt))])
361 (check-not-false m)
362 (check-equal? (Msg-from m) p)
363 (check-equal? (Msg-text m) txt)
364 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
365 )))
366
367 (let* ([ts "2020-11-18T22:22:09-0500"]
368 [tab " "]
369 [text "Lorem ipsum"]
370 [nick "foo"]
371 [uri "http://bar/"]
372 [peer (Peer nick (string->url uri) uri #f)]
373 [actual (str->msg peer (string-append ts tab text))]
374 [expected (Msg 1605756129 ts peer text '())])
375 (check-equal?
376 (Msg-ts-epoch actual)
377 (Msg-ts-epoch expected)
378 "str->msg ts-epoch")
379 (check-equal?
380 (Msg-ts-orig actual)
381 (Msg-ts-orig expected)
382 "str->msg ts-orig")
383 (check-equal?
384 (Peer-nick (Msg-from actual))
385 (Peer-nick (Msg-from expected))
386 "str->msg nick")
387 (check-equal?
388 (Peer-uri (Msg-from actual))
389 (Peer-uri (Msg-from expected))
390 "str->msg uri")
391 (check-equal?
392 (Peer-uri-str (Msg-from actual))
393 (Peer-uri-str (Msg-from expected))
394 "str->msg uri-str")
395 (check-equal?
396 (Msg-text actual)
397 (Msg-text expected)
398 "str->msg text")))
399
400 (: str->lines (-> String (Listof String)))
401 (define (str->lines str)
402 (string-split str (regexp "[\r\n]+")))
403
404 (module+ test
405 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
406
407 ; TODO Should return 2 things: 1) msgs; 2) metadata parsed from comments
408 ; TODO Update peer nick based on metadata?
409 (: str->msgs (-> Peer String (Listof Msg)))
410 (define (str->msgs peer str)
411 (filter-map (λ (line) (str->msg peer line))
412 (filter-comments (str->lines str))))
413
414 (: cache-dir Path-String)
415 (define cache-dir (build-path tt-home-dir "cache"))
416
417 (define cache-object-dir (build-path cache-dir "objects"))
418
419 (: url->cache-file-path-v1 (-> Url Path-String))
420 (define (url->cache-file-path-v1 uri)
421 (define (hash-sha1 str) : (-> String String)
422 (define in (open-input-string str))
423 (define digest (sha1 in))
424 (close-input-port in)
425 digest)
426 (build-path cache-object-dir (hash-sha1 (url->string uri))))
427
428 (: url->cache-file-path-v2 (-> Url Path-String))
429 (define (url->cache-file-path-v2 uri)
430 (build-path cache-object-dir (uri-encode (url->string uri))))
431
432 (define url->cache-object-path
433 url->cache-file-path-v2)
434
435 (define (url->cache-etag-path uri)
436 (build-path cache-dir "etags" (uri-encode (url->string uri))))
437
438 (define (url->cache-lmod-path uri)
439 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
440
441 (: uri-read-cached (-> Url (Option String)))
442 (define (uri-read-cached uri)
443 (define path-v1 (url->cache-file-path-v1 uri))
444 (define path-v2 (url->cache-file-path-v2 uri))
445 (when (file-exists? path-v1)
446 (rename-file-or-directory path-v1 path-v2 #t))
447 (if (file-exists? path-v2)
448 (file->string path-v2)
449 (begin
450 (log-debug "Cache file not found for URI: ~a" (url->string uri))
451 #f)))
452
453 (: str->url (-> String (Option String)))
454 (define (str->url s)
455 (with-handlers*
456 ([exn:fail? (λ (e) #f)])
457 (string->url s)))
458
459 (: peer->str (-> Peer String))
460 (define (peer->str peer)
461 (match-define (Peer n _ u c) peer)
462 (format "~a~a~a"
463 (if n (format "~a " n) "")
464 u
465 (if c (format " # ~a" c) "")))
466
467 (: str->peer (-> String (Option Peer)))
468 (define (str->peer str)
469 (log-debug "Parsing peer string: ~v" str)
470 (match
471 (regexp-match
472 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
473 str)
474 [(list _wholething
475 _nick-with-space
476 nick
477 url
478 _comment-with-hash
479 comment)
480 (match (str->url url)
481 [#f
482 (log-error "Invalid URI in peer string: ~v" str)
483 #f]
484 [url
485 (Peer nick url (url->string url) comment)])]
486 [_
487 (log-debug "Invalid peer string: ~v" str)
488 #f]))
489
490 (module+ test
491 (check-equal?
492 (str->peer "foo http://bar/file.txt # some rando")
493 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
494 (check-equal?
495 (str->peer "http://bar/file.txt # some rando")
496 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
497 (check-equal?
498 (str->peer "http://bar/file.txt #")
499 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
500 (check-equal?
501 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
502 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
503 (check-equal?
504 (str->peer "http://bar/file.txt")
505 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
506 (check-equal?
507 (str->peer "foo http://bar/file.txt")
508 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
509 (check-equal?
510 (str->peer "foo bar # baz")
511 #f)
512 (check-equal?
513 (str->peer "foo bar://baz # quux")
514 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
515 (check-equal?
516 (str->peer "foo bar//baz # quux")
517 #f))
518
519 (: filter-comments (-> (Listof String) (Listof String)))
520 (define (filter-comments lines)
521 (filter-not (λ (line) (string-prefix? line "#")) lines))
522
523 (: str->peers (-> String (Listof Peer)))
524 (define (str->peers str)
525 (filter-map str->peer (filter-comments (str->lines str))))
526
527 (: peers->file (-> (Listof Peers) Path-String Void))
528 (define (peers->file peers path)
529 (make-parent-directory* 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 ; TODO Update message db from here? or where?
596 ; - 1st try can just be an in-memory set that gets written-to
597 ; and read-from disk as a whole.
598 (define u-str (url->string u))
599 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
600 (define cached-object-path (url->cache-object-path u))
601 (define cached-etag-path (url->cache-etag-path u))
602 (define cached-lmod-path (url->cache-lmod-path u))
603 (define etag (header-get headers #"ETag"))
604 (define lmod (header-get headers #"Last-Modified"))
605 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
606 (define lmod-prev (if (file-exists? cached-lmod-path)
607 (rfc2822->epoch (file->bytes cached-lmod-path))
608 #f))
609 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
610 (define cached?
611 (or (and etag
612 (file-exists? cached-etag-path)
613 (bytes=? etag (file->bytes cached-etag-path))
614 (begin
615 (log-debug "ETags match, skipping the rest of ~v" u-str)
616 #t))
617 (and lmod-curr
618 lmod-prev
619 (<= lmod-curr lmod-prev)
620 (begin
621 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
622 #t))))
623 (if (not cached?)
624 (begin
625 (log-debug
626 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
627 u-str etag lmod)
628 (make-parent-directory* cached-object-path)
629 (make-parent-directory* cached-etag-path)
630 (make-parent-directory* cached-lmod-path)
631 (call-with-output-file cached-object-path
632 (curry copy-port body-input)
633 #:exists 'replace)
634 (when etag
635 (display-to-file etag cached-etag-path #:exists 'replace))
636 (when lmod
637 (display-to-file lmod cached-lmod-path #:exists 'replace))
638 'downloaded-new)
639 'skipped-cached))
640
641 (: uri-download
642 (-> Positive-Float Url
643 (Result (U 'skipped-cached 'downloaded-new)
644 Any))) ; TODO Maybe more-precise error type?
645 (define (uri-download timeout u)
646 (define u-str (url->string u))
647 (define timeout-chan (make-channel))
648 (define result-chan (make-channel))
649 (define timeout-thread
650 (thread (λ ()
651 ; Doing this instead of sync/timeout to distinguish error values,
652 ; rather than just have #f to work with.
653 (sleep timeout)
654 (channel-put timeout-chan '(error . timeout)))))
655 (define result-thread
656 (thread (λ ()
657 (define result
658 (with-handlers
659 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
660 ([exn:fail:network?
661 (λ (e) `(error . (net-error . ,e)))]
662 [exn?
663 (λ (e) `(error . (other . ,e)))])
664 (define-values (status-line headers body-input)
665 (http-sendrecv/url
666 u
667 #:headers (list (format "User-Agent: ~a" user-agent-str))))
668 (log-debug "headers: ~v" headers)
669 (log-debug "status-line: ~v" status-line)
670 (define status
671 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
672 (log-debug "status: ~v" status)
673 (let ([result
674 ; TODO Handle redirects.
675 ; TODO Should a redirect update a peer URL?
676 (match status
677 [200
678 `(ok . ,(uri-download-from-port u headers body-input))]
679 [_
680 `(error . (http-not-ok . ,status))])])
681 (close-input-port body-input)
682 result)))
683 (channel-put result-chan result))))
684 (define result (sync timeout-chan result-chan))
685 (kill-thread result-thread)
686 (kill-thread timeout-thread)
687 result)
688
689 (: timeline-print (-> Out-Format (Listof Msg) Void))
690 (define (timeline-print out-format timeline)
691 (match timeline
692 ['()
693 (void)]
694 [(cons first-msg _)
695 (void (foldl (match-lambda**
696 [((and m (Msg _ _ from _ _)) (cons prev-from i))
697 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
698 (msg-print out-format i m)
699 (cons from i))])
700 (cons (Msg-from first-msg) 0)
701 timeline))]))
702
703 (: peer->msgs (-> Peer (Listof Msg)))
704 (define (peer->msgs peer)
705 (match-define (Peer nick uri uri-str _) peer)
706 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
707 (define msgs-data (uri-read-cached uri))
708 ; TODO Expire cache
709 (if msgs-data
710 (str->msgs peer msgs-data)
711 '()))
712
713 (: peer-download
714 (-> Positive-Float Peer
715 (Result (U 'skipped-cached 'downloaded-new)
716 Any)))
717 (define (peer-download timeout peer)
718 (match-define (Peer nick uri u _) peer)
719 (log-info "Download BEGIN URL:~a" u)
720 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
721 (time-apply uri-download (list timeout uri)))
722 (define result (car results))
723 (log-info "Download END in ~a seconds, URL:~a, result:~s"
724 (/ tm-real-ms 1000.0)
725 u
726 result)
727 result)
728
729 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
730 (define (timeline-download num-workers timeout peers)
731 (define results
732 (concurrent-filter-map num-workers
733 (λ (p) (cons p (peer-download timeout p)))
734 peers))
735 (define peers-ok
736 (filter-map (match-lambda
737 [(cons p (cons 'ok _)) p]
738 [(cons _ (cons 'error e)) #f])
739 results))
740 (define peers-err
741 (filter-map (match-lambda
742 [(cons _ (cons 'ok _))
743 #f]
744 [(cons p (cons 'error e))
745 (struct-copy Peer p [comment (format "~s" e)])])
746 results))
747 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok.txt"))
748 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err.txt")))
749
750 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
751 (define (peers->timeline peers)
752 (append* (filter-map peer->msgs peers)))
753
754 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
755 (define (timeline-sort msgs order)
756 (define cmp (match order
757 ['old->new <]
758 ['new->old >]))
759 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
760 (Msg-ts-epoch b)))))
761
762 (: paths->peers (-> (Listof String) (Listof Peer)))
763 (define (paths->peers paths)
764 (let* ([paths (match paths
765 ['()
766 (let ([peer-refs-file (build-path tt-home-dir "following.txt")])
767 (log-debug
768 "No peer ref file paths provided, defaulting to ~v"
769 (path->string peer-refs-file))
770 (list peer-refs-file))]
771 [paths
772 (log-debug "Peer ref file paths provided: ~v" paths)
773 (map string->path paths)])]
774 [peers (apply peers-merge (map file->peers paths))])
775 (log-info "Read-in ~a peers." (length peers))
776 peers))
777
778 (: cache-filename->peer (-> Path-String (Option Peer)))
779 (define (cache-filename->peer filename)
780 (define nick #f) ; TODO Look it up in the nick-db when it exists.
781 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
782 (match (str->url url-str)
783 [#f #f]
784 [url (Peer nick url url-str #f)]))
785
786 (: peers-cached (-> (Listof Peer)))
787 (define (peers-cached)
788 ; TODO Expire cache?
789 (filter-map cache-filename->peer (directory-list cache-object-dir)))
790
791 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
792 (define (peers-mentioned msgs)
793 (append* (map Msg-mentions msgs)))
794
795 (: peers-filter-denied-domains (-> (Listof Peer) (Listof Peer)))
796 (define (peers-filter-denied-domains peers)
797 (define deny-file (build-path tt-home-dir "domains-deny.txt"))
798 (define denied-hosts
799 (list->set (map string-trim (filter-comments (file->lines deny-file)))))
800 (define denied-domain-patterns
801 (set-map denied-hosts (λ (h) (pregexp (string-append "\\." h "$")))))
802 (filter
803 (λ (p)
804 (define host (url-host (Peer-uri p)))
805 (not (or (set-member? denied-hosts host)
806 (ormap (λ (d) (regexp-match? d host)) denied-domain-patterns))))
807 peers))
808
809 (: log-writer-stop (-> Thread Void))
810 (define (log-writer-stop log-writer)
811 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
812 (thread-wait log-writer))
813
814 (: log-writer-start (-> Log-Level Thread))
815 (define (log-writer-start level)
816 (let* ([logger
817 (make-logger #f #f level #f)]
818 [log-receiver
819 (make-log-receiver logger level)]
820 [log-writer
821 (thread
822 (λ ()
823 (parameterize
824 ([date-display-format 'iso-8601])
825 (let loop ()
826 (match-define (vector level msg _ topic) (sync log-receiver))
827 (unless (equal? topic 'stop)
828 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
829 (loop))))))])
830 (current-logger logger)
831 log-writer))
832
833 (: msgs->nick-hist (-> (Listof Msg) Nick-Hist))
834 (define (msgs->nick-hist msgs)
835 (foldl
836 (λ (msg url->nick->hist)
837 (match-define (Msg curr _ from _ mentions) msg)
838 (foldl
839 (λ (peer url->nick->hist)
840 (match-define (Peer nick url _ _) peer)
841 (if nick
842 (hash-update url->nick->hist
843 url
844 (λ (nick->hist)
845 (hash-update nick->hist
846 nick
847 (match-lambda
848 [(Hist freq prev)
849 (Hist (+ 1 freq) (max prev curr))])
850 (Hist 0 0)))
851 (hash))
852 url->nick->hist))
853 url->nick->hist
854 (cons from mentions)))
855 (hash)
856 msgs))
857
858 (: update-nicks-history-files (-> Nick-Hist Void))
859 (define (update-nicks-history-files nick-hist)
860 (hash-for-each
861 nick-hist
862 (λ (url nick->hist)
863 (define filename (string-append (uri-encode (url->string url)) ".txt"))
864 (define filepath (build-path tt-home-dir "nicks" "seen" filename))
865 (make-parent-directory* filepath)
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 filepath
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 (: peers-update-nick-to-common (-> Nick-Hist (Listof Peer) (Listof Peer)))
897 (define (peers-update-nick-to-common nick-hist peers)
898 (map
899 (λ (p)
900 (match (nick-hist-common nick-hist (Peer-uri p))
901 [#f p]
902 [n (struct-copy Peer p [nick n])]))
903 peers))
904
905 (module+ test
906 (let* ([url-str "http://foo"]
907 [url (string->url url-str)]
908 [nick1 "a"]
909 [nick2 "b"]
910 [nick3 "c"]
911 [ts-str-1 "2021-11-29T23:29:08-0500"]
912 [ts-str-2 "2021-11-29T23:30:00-0500"]
913 [ts-1 (rfc3339->epoch ts-str-1)]
914 [ts-2 (rfc3339->epoch ts-str-2)]
915 [msgs
916 (map (match-lambda
917 [(cons ts-str nick)
918 (str->msg (str->peer "test http://test")
919 (string-append ts-str " Hi @<" nick " " url-str ">"))])
920 (list (cons ts-str-2 nick1)
921 (cons ts-str-1 nick2)
922 (cons ts-str-1 nick2)
923 (cons ts-str-1 nick3)
924 (cons ts-str-1 nick3)
925 (cons ts-str-1 nick3)))]
926 [hist
927 (msgs->nick-hist msgs)])
928 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
929 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
930 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
931 (check-equal? (nick-hist-common hist url) nick3)
932 (check-equal? (nick-hist-latest hist url) nick1)))
933
934 (: crawl (-> Void))
935 (define (crawl)
936 ; TODO Test the non-io parts of crawling
937 (let* ([peers-all-file
938 (build-path pub-peers-dir "all.txt")]
939 [peers-mentioned-file
940 (build-path pub-peers-dir "mentioned.txt")]
941 [peers-parsed-file
942 (build-path pub-peers-dir "downloaded-and-parsed.txt")]
943 [peers-cached-file
944 (build-path pub-peers-dir "downloaded.txt")]
945 [peers-cached
946 (peers-cached)]
947 [cached-timeline
948 (peers->timeline peers-cached)]
949 [nick-hist
950 (msgs->nick-hist cached-timeline)]
951 [peers-mentioned-curr
952 (peers-mentioned cached-timeline)]
953 [peers-mentioned-prev
954 (file->peers peers-mentioned-file)]
955 [peers-all-prev
956 (file->peers peers-all-file)]
957 [peers-mentioned
958 (peers-merge peers-mentioned-prev
959 peers-mentioned-curr)]
960 [peers-all
961 (peers-update-nick-to-common
962 nick-hist
963 (peers-merge peers-mentioned
964 peers-all-prev
965 peers-cached))]
966 [peers-discovered
967 (set->list (set-subtract (make-immutable-peers peers-all)
968 (make-immutable-peers peers-all-prev)))]
969 [peers-parsed
970 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
971 ; TODO Deeper de-duping
972 (log-info "Known peers cached ~a" (length peers-cached))
973 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
974 (log-info "Known peers parsed ~a" (length peers-parsed))
975 (log-info "Known peers total: ~a" (length peers-all))
976 (log-info "Discovered ~a new peers:~n~a"
977 (length peers-discovered)
978 (pretty-format (map
979 (match-lambda
980 [(Peer n _ u c) (list n u c)])
981 peers-discovered)))
982 (update-nicks-history-files nick-hist)
983 (peers->file peers-cached
984 peers-cached-file)
985 (peers->file peers-mentioned
986 peers-mentioned-file)
987 (peers->file peers-parsed
988 peers-parsed-file)
989 (peers->file peers-all
990 peers-all-file)))
991
992 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
993 (define (read file-paths ts-min ts-max order out-format)
994 (let* ([peers
995 (paths->peers file-paths)]
996 [msgs
997 (timeline-sort (peers->timeline peers) order)]
998 [include?
999 (λ (m)
1000 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
1001 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
1002 (timeline-print out-format (filter include? msgs))))
1003
1004 (: upload (-> Void))
1005 (define (upload)
1006 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
1007 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
1008 (exit 0)
1009 (exit 1)))
1010
1011 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
1012 (define (download file-paths num-workers timeout)
1013 (let* ([peers-given (paths->peers file-paths)]
1014 [peers-kept (peers-filter-denied-domains peers-given)]
1015 [peers-denied (set-subtract peers-given peers-kept)])
1016 (log-info "Denied ~a peers" (length peers-denied))
1017 (define-values (_res _cpu real-ms _gc)
1018 (time-apply timeline-download (list num-workers timeout peers-kept)))
1019 (log-info "Downloaded timelines from ~a peers in ~a seconds."
1020 (length peers-kept)
1021 (/ real-ms 1000.0))))
1022
1023 (: dispatch (-> String Void))
1024 (define (dispatch command)
1025 (match command
1026 [(or "d" "download")
1027 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
1028 ; started noticing significant slowdowns. Reducing to 5 seems to help.
1029 (let ([num-workers 5]
1030 [timeout 10.0])
1031 (command-line
1032 #:program "tt download"
1033 #:once-each
1034 [("-j" "--jobs")
1035 njobs "Number of concurrent jobs."
1036 (set! num-workers (string->number njobs))]
1037 [("-t" "--timeout")
1038 seconds "Timeout seconds per request."
1039 (set! timeout (string->number seconds))]
1040 #:args file-paths
1041 (download file-paths num-workers timeout)))]
1042 [(or "u" "upload")
1043 (command-line
1044 #:program "tt upload" #:args () (upload))]
1045 [(or "r" "read")
1046 (let ([out-format 'multi-line]
1047 [order 'old->new]
1048 [ts-min #f]
1049 [ts-max #f])
1050 (command-line
1051 #:program "tt read"
1052 #:once-each
1053 [("-r" "--rev")
1054 "Reverse displayed timeline order."
1055 (set! order 'new->old)]
1056 [("-m" "--min")
1057 m "Earliest time to display (ignore anything before it)."
1058 (set! ts-min (rfc3339->epoch m))]
1059 [("-x" "--max")
1060 x "Latest time to display (ignore anything after it)."
1061 (set! ts-max (rfc3339->epoch x))]
1062 #:once-any
1063 [("-s" "--short")
1064 "Short output format"
1065 (set! out-format 'single-line)]
1066 [("-l" "--long")
1067 "Long output format"
1068 (set! out-format 'multi-line)]
1069 #:args file-paths
1070 (read file-paths ts-min ts-max order out-format)))]
1071 [(or "c" "crawl")
1072 (command-line
1073 #:program "tt crawl" #:args () (crawl))]
1074 [command
1075 (eprintf "Error: invalid command: ~v\n" command)
1076 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1077 (exit 1)]))
1078
1079 (module+ main
1080 (let ([log-level 'info])
1081 (command-line
1082 #:program
1083 "tt"
1084 #:once-each
1085 [("-d" "--debug")
1086 "Enable debug log level."
1087 (set! log-level 'debug)]
1088 #:help-labels
1089 ""
1090 "and <command> is one of"
1091 "r, read : Read the timeline (offline operation)."
1092 "d, download : Download the timeline."
1093 ; TODO Add path dynamically
1094 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
1095 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
1096 ""
1097 #:args (command . args)
1098 (define log-writer (log-writer-start log-level))
1099 (current-command-line-arguments (list->vector args))
1100 (set-user-agent-str (build-path tt-home-dir "user.txt"))
1101 ; TODO dispatch should return status with which we should exit after cleanups
1102 (dispatch command)
1103 (log-writer-stop log-writer))))
This page took 0.11664 seconds and 3 git commands to generate.