Switch to just calling it urL instead of urI
[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 (define-type Download-Result
31 (Result (U 'skipped-cached 'downloaded-new)
32 (U 'timeout
33 (Pair 'unsupported-url-scheme String)
34 (Pair 'http-not-ok Positive-Integer)
35 (Pair 'net-error Any)
36 (Pair 'other Any))))
37
38 (struct Hist
39 ([freq : Nonnegative-Integer]
40 [last : Nonnegative-Integer])
41 #:transparent)
42
43 (define-type Url-Nick-Hist
44 (Immutable-HashTable Url (Immutable-HashTable (Option String) Hist)))
45
46 (struct User
47 ([url : Url]
48 [nick : (Option String)]))
49
50 (struct User-Agent
51 ([user : User]
52 [prog : Prog]))
53
54 (struct Prog
55 ([name : String]
56 [version : String]))
57
58 (struct Msg
59 ([ts-epoch : Integer]
60 [ts-orig : String]
61 [from : Peer]
62 [text : String]
63 [mentions : (Listof Peer)]))
64
65 (struct Peer
66 ([nick : (Option String)]
67 [url : Url]
68 [url-str : String]
69 [comment : (Option String)])
70 #:transparent)
71
72 (: prog Prog)
73 (define prog
74 (Prog "tt" (info:#%info-lookup 'version)))
75
76 (: user-default User)
77 (define user-default
78 (User (string->url "https://github.com/xandkar/tt") #f))
79
80 (: user->str (-> User String))
81 (define (user->str user)
82 (match-define (User u0 n) user)
83 (define u (url->string u0))
84 (if n
85 (format "+~a; @~a" u n)
86 (format "+~a" u )))
87
88 (: user-agent->str (-> User-Agent String))
89 (define (user-agent->str ua)
90 (match-define (User-Agent u p) ua)
91 (format "~a/~a (~a)" (Prog-name p) (Prog-version p) (user->str u)))
92
93 (: user->user-agent User)
94 (define (user->user-agent user)
95 (User-Agent user prog))
96
97 (: user-agent-str String)
98 (define user-agent-str
99 (user-agent->str (user->user-agent user-default)))
100
101 (: set-user-agent-str (-> Path-String Void))
102 (define (set-user-agent-str filename)
103 (set! user-agent-str (user-agent->str (user->user-agent (file->user filename))))
104 (log-info "User-Agent string is now set to: ~v" user-agent-str))
105
106 (: file->user (-> Path-String User))
107 (define (file->user filename)
108 (if (file-exists? filename)
109 (match (file->peers filename)
110 [(list p)
111 (log-info
112 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
113 filename
114 (peer->str p))
115 (peer->user p)]
116 [(list* p _)
117 (log-warning
118 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
119 filename
120 (peer->str p))
121 (peer->user p)]
122 ['()
123 (log-warning
124 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
125 filename
126 user-default)
127 user-default])
128 (begin
129 (log-warning
130 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
131 filename
132 user-default)
133 user-default)))
134
135 (: peer->user (-> Peer User))
136 (define (peer->user p)
137 (match-define (Peer n u _ _) p)
138 (User u n))
139
140 (: peers-equal? (-> Peer Peer Boolean))
141 (define (peers-equal? p1 p2)
142 (equal? (Peer-url-str p1)
143 (Peer-url-str p2)))
144
145 (: peer-hash (-> Peer Fixnum))
146 (define (peer-hash p)
147 (equal-hash-code (Peer-url-str p)))
148
149 (define-custom-set-types peers
150 #:elem? Peer?
151 peers-equal?
152 peer-hash)
153 ; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
154 ; the following contract violations:
155 ;
156 ; custom-elem-contents: contract violation
157 ; expected: custom-elem?
158 ; given: #f
159 ; context...:
160 ; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
161 ; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
162 ; /usr/share/racket/collects/racket/cmdline.rkt:191:51
163 ; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
164 ;
165 ; TODO Investigate why and make a minimal reproducible test case.
166
167 (: peers-merge (-> (Listof Peer) * (Listof Peer)))
168 (define (peers-merge . peer-sets)
169 (define groups
170 (foldl
171 (λ (p groups)
172 (hash-update groups (Peer-url-str p) (λ (group) (cons p group)) '()))
173 (hash)
174 (append* peer-sets)))
175 (define (merge peers)
176 (match peers
177 ['() (raise 'impossible)]
178 [(list p) p]
179 [(list* p1 p2 ps)
180 (let* ([n1 (Peer-nick p1)]
181 [n2 (Peer-nick p2)]
182 [p (cond
183 ; TODO Try to pick from nicks db: preferred, otherwise seen
184 [(and (not n1) (not n2)) p1] ; TODO update with most-common nick
185 [(and n1 n2 ) p1] ; TODO compare which is more-common
186 [(and n1 (not n2)) p1]
187 [(and (not n1) n2) p2]
188 [else
189 (raise 'impossible)])])
190 (merge (cons p ps)))]))
191 (sort (map merge (hash-values groups))
192 (match-lambda**
193 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
194
195 (module+ test
196 (let* ([u1 "http://foo/bar"]
197 [u2 "http://baz/quux"]
198 [p1 (Peer #f (string->url u1) u1 #f)]
199 [p2 (Peer "a" (string->url u1) u1 #f)]
200 [p3 (Peer "b" (string->url u2) u2 #f)]
201 [s1 (list p1)]
202 [s2 (list p2 p3)])
203 (check-equal? (list p3 p2) (peers-merge s1 s2))
204 (check-equal? (list p3 p2) (peers-merge s2 s1))))
205
206 (: tt-home-dir Path-String)
207 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
208
209 (: pub-peers-dir Path-String)
210 (define pub-peers-dir (build-path tt-home-dir "peers"))
211
212 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
213 (define (concurrent-filter-map num-workers f xs)
214 ; TODO preserve order of elements OR communicate that reorder is expected
215 ; TODO switch from mailboxes to channels
216 (define (make-worker id f)
217 (define parent (current-thread))
218 (λ ()
219 (define self : Thread (current-thread))
220 (: work (∀ (α) (-> α)))
221 (define (work)
222 (thread-send parent (cons 'next self))
223 (match (thread-receive)
224 ['done (thread-send parent (cons 'exit id))]
225 [(cons 'unit x) (begin
226 (define y (f x))
227 (when y (thread-send parent (cons 'result y)))
228 (work))]))
229 (work)))
230 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
231 (define (dispatch ws xs ys)
232 (if (empty? ws)
233 ys
234 (match (thread-receive)
235 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
236 [(cons 'result y) (dispatch ws xs (cons y ys))]
237 [(cons 'next thd) (match xs
238 ['() (begin
239 (thread-send thd 'done)
240 (dispatch ws xs ys))]
241 [(cons x xs) (begin
242 (thread-send thd (cons 'unit x))
243 (dispatch ws xs ys))])])))
244 (define workers (range num-workers))
245 (define threads (map (λ (id) (thread (make-worker id f))) workers))
246 (define results (dispatch workers xs '()))
247 (for-each thread-wait threads)
248 results)
249
250 (module+ test
251 (let* ([f (λ (x) (if (even? x) x #f))]
252 [xs (range 11)]
253 [actual (sort (concurrent-filter-map 10 f xs) <)]
254 [expected (sort ( filter-map f xs) <)])
255 (check-equal? actual expected "concurrent-filter-map")))
256
257 (: msg-print (-> Out-Format Integer Msg Void))
258 (define msg-print
259 (let* ([colors (vector 36 33)]
260 [n (vector-length colors)])
261 (λ (out-format color-i msg)
262 (let ([color (vector-ref colors (modulo color-i n))]
263 [nick (Peer-nick (Msg-from msg))]
264 [url (Peer-url-str (Msg-from msg))]
265 [text (Msg-text msg)])
266 (match out-format
267 ['single-line
268 (let ([nick (if nick nick url)])
269 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
270 (parameterize
271 ([date-display-format 'iso-8601])
272 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
273 nick color text))]
274 ['multi-line
275 (let ([nick (if nick (string-append nick " ") "")])
276 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
277 (parameterize
278 ([date-display-format 'rfc2822])
279 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
280 (Msg-ts-orig msg)
281 nick url color text))])))))
282
283 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
284 (define rfc3339->epoch
285 (let ([re (pregexp "^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(:([0-9]{2}))?(\\.[0-9]+)?(Z|([+-])([0-9]{1,2}):?([0-9]{2}))?$")])
286 (λ (ts)
287 (match (regexp-match re ts)
288 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
289 (let*
290 ([tz-offset
291 (match* (tz-whole tz-sign tz-HH tz-MM)
292 [("Z" #f #f #f)
293 0]
294 [(_ (or "-" "+") (? identity h) (? identity m))
295 (let ([h (string->number h)]
296 [m (string->number m)]
297 ; Reverse to get back to UTC:
298 [op (match tz-sign ["+" -] ["-" +])])
299 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
300 [(a b c d)
301 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
302 0])]
303 [ts-orig ts]
304 [local-time? #f]
305 [ts-epoch (find-seconds (if SS (string->number SS) 0)
306 (string->number MM)
307 (string->number HH)
308 (string->number dd)
309 (string->number mm)
310 (string->number yyyy)
311 local-time?)])
312 (+ ts-epoch tz-offset))]
313 [_
314 (log-debug "Invalid timestamp: ~v" ts)
315 #f]))))
316
317 (: str->msg (-> Peer String (Option Msg)))
318 (define str->msg
319 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
320 (λ (from str)
321 (define from-str (peer->str from))
322 (define str-head (substring str 0 (min 100 (string-length str))))
323 (with-handlers*
324 ([exn:fail?
325 (λ (e)
326 (log-debug
327 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
328 str-head from-str e)
329 #f)])
330 (match (regexp-match re str)
331 [(list _wholething ts-orig text)
332 (let ([ts-epoch (rfc3339->epoch ts-orig)])
333 (if ts-epoch
334 (let ([mentions
335 (filter-map
336 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
337 [(list _wholething nick-url)
338 (str->peer nick-url)]))
339 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
340 (Msg ts-epoch ts-orig from text mentions))
341 (begin
342 (log-debug
343 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
344 from-str str-head)
345 #f)))]
346 [_
347 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
348 #f])))))
349
350 (module+ test
351 ; TODO Test for when missing-nick case
352 (let* ([tzs (for*/list ([d '("-" "+")]
353 [h '("5" "05")]
354 [m '("00" ":00" "57" ":57")])
355 (string-append d h m))]
356 [tzs (list* "" "Z" tzs)])
357 (for* ([n '("fake-nick")]
358 [u '("http://fake-url")]
359 [p (list (Peer n (string->url u) u #f))]
360 [s '("" ":10")]
361 [f '("" ".1337")]
362 [z tzs]
363 [sep (list "\t" " ")]
364 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
365 (let* ([ts (string-append "2020-11-18T22:22"
366 (if (non-empty-string? s) s ":00")
367 z)]
368 [m (str->msg p (string-append ts sep txt))])
369 (check-not-false m)
370 (check-equal? (Msg-from m) p)
371 (check-equal? (Msg-text m) txt)
372 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
373 )))
374
375 (let* ([ts "2020-11-18T22:22:09-0500"]
376 [tab " "]
377 [text "Lorem ipsum"]
378 [nick "foo"]
379 [url "http://bar/"]
380 [peer (Peer nick (string->url url) url #f)]
381 [actual (str->msg peer (string-append ts tab text))]
382 [expected (Msg 1605756129 ts peer text '())])
383 (check-equal?
384 (Msg-ts-epoch actual)
385 (Msg-ts-epoch expected)
386 "str->msg ts-epoch")
387 (check-equal?
388 (Msg-ts-orig actual)
389 (Msg-ts-orig expected)
390 "str->msg ts-orig")
391 (check-equal?
392 (Peer-nick (Msg-from actual))
393 (Peer-nick (Msg-from expected))
394 "str->msg nick")
395 (check-equal?
396 (Peer-url (Msg-from actual))
397 (Peer-url (Msg-from expected))
398 "str->msg url")
399 (check-equal?
400 (Peer-url-str (Msg-from actual))
401 (Peer-url-str (Msg-from expected))
402 "str->msg url-str")
403 (check-equal?
404 (Msg-text actual)
405 (Msg-text expected)
406 "str->msg text")))
407
408 (: str->lines (-> String (Listof String)))
409 (define (str->lines str)
410 (string-split str (regexp "[\r\n]+")))
411
412 (module+ test
413 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
414
415 ; TODO Should return 2 things: 1) msgs; 2) metadata parsed from comments
416 ; TODO Update peer nick based on metadata?
417 (: str->msgs (-> Peer String (Listof Msg)))
418 (define (str->msgs peer str)
419 (filter-map (λ (line) (str->msg peer line))
420 (filter-comments (str->lines str))))
421
422 (: cache-dir Path-String)
423 (define cache-dir (build-path tt-home-dir "cache"))
424
425 (define cache-object-dir (build-path cache-dir "objects"))
426
427 (: url->cache-file-path-v1 (-> Url Path-String))
428 (define (url->cache-file-path-v1 url)
429 (define (hash-sha1 str) : (-> String String)
430 (define in (open-input-string str))
431 (define digest (sha1 in))
432 (close-input-port in)
433 digest)
434 (build-path cache-object-dir (hash-sha1 (url->string url))))
435
436 (: url->cache-file-path-v2 (-> Url Path-String))
437 (define (url->cache-file-path-v2 url)
438 (build-path cache-object-dir (uri-encode (url->string url))))
439
440 (define url->cache-object-path
441 url->cache-file-path-v2)
442
443 (define (url->cache-etag-path url)
444 (build-path cache-dir "etags" (uri-encode (url->string url))))
445
446 (define (url->cache-lmod-path url)
447 (build-path cache-dir "lmods" (uri-encode (url->string url))))
448
449 (: url-read-cached (-> Url (Option String)))
450 (define (url-read-cached url)
451 (define path-v1 (url->cache-file-path-v1 url))
452 (define path-v2 (url->cache-file-path-v2 url))
453 (when (file-exists? path-v1)
454 (rename-file-or-directory path-v1 path-v2 #t))
455 (if (file-exists? path-v2)
456 (file->string path-v2)
457 (begin
458 (log-debug "Cache file not found for URL: ~a" (url->string url))
459 #f)))
460
461 (: str->url (-> String (Option String)))
462 (define (str->url s)
463 (with-handlers*
464 ([exn:fail? (λ (e) #f)])
465 (string->url s)))
466
467 (: peer->str (-> Peer String))
468 (define (peer->str peer)
469 (match-define (Peer n _ u c) peer)
470 (format "~a~a~a"
471 (if n (format "~a " n) "")
472 u
473 (if c (format " # ~a" c) "")))
474
475 (: str->peer (-> String (Option Peer)))
476 (define (str->peer str)
477 (log-debug "Parsing peer string: ~v" str)
478 (match
479 (regexp-match
480 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
481 str)
482 [(list _wholething
483 _nick-with-space
484 nick
485 url
486 _comment-with-hash
487 comment)
488 (match (str->url url)
489 [#f
490 (log-error "Invalid URL in peer string: ~v" str)
491 #f]
492 [url
493 (Peer nick url (url->string url) comment)])]
494 [_
495 (log-debug "Invalid peer string: ~v" str)
496 #f]))
497
498 (module+ test
499 (check-equal?
500 (str->peer "foo http://bar/file.txt # some rando")
501 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
502 (check-equal?
503 (str->peer "http://bar/file.txt # some rando")
504 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
505 (check-equal?
506 (str->peer "http://bar/file.txt #")
507 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
508 (check-equal?
509 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
510 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
511 (check-equal?
512 (str->peer "http://bar/file.txt")
513 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
514 (check-equal?
515 (str->peer "foo http://bar/file.txt")
516 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
517 (check-equal?
518 (str->peer "foo bar # baz")
519 #f)
520 (check-equal?
521 (str->peer "foo bar://baz # quux")
522 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
523 (check-equal?
524 (str->peer "foo bar//baz # quux")
525 #f))
526
527 (: filter-comments (-> (Listof String) (Listof String)))
528 (define (filter-comments lines)
529 (filter-not (λ (line) (string-prefix? line "#")) lines))
530
531 (: str->peers (-> String (Listof Peer)))
532 (define (str->peers str)
533 (filter-map str->peer (filter-comments (str->lines str))))
534
535 (: peers->file (-> (Listof Peers) Path-String Void))
536 (define (peers->file peers path)
537 (make-parent-directory* path)
538 (display-lines-to-file
539 (map peer->str
540 (sort peers
541 (match-lambda**
542 [((Peer n1 _ _ _) (Peer n2 _ _ _))
543 (string<? (if n1 n1 "")
544 (if n2 n2 ""))])))
545 path
546 #:exists 'replace))
547
548 (: file->peers (-> Path-String (Listof Peer)))
549 (define (file->peers file-path)
550 (if (file-exists? file-path)
551 (str->peers (file->string file-path))
552 (begin
553 (log-warning "File does not exist: ~v" (path->string file-path))
554 '())))
555
556 (define re-rfc2822
557 #px"^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-2][0-9]):([0-6][0-9]):([0-6][0-9]) GMT")
558
559 (: b->n (-> Bytes (Option Number)))
560 (define (b->n b)
561 (string->number (bytes->string/utf-8 b)))
562
563 (: mon->num (-> Bytes Natural))
564 (define/match (mon->num mon)
565 [(#"Jan") 1]
566 [(#"Feb") 2]
567 [(#"Mar") 3]
568 [(#"Apr") 4]
569 [(#"May") 5]
570 [(#"Jun") 6]
571 [(#"Jul") 7]
572 [(#"Aug") 8]
573 [(#"Sep") 9]
574 [(#"Oct") 10]
575 [(#"Nov") 11]
576 [(#"Dec") 12])
577
578 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
579 (define (rfc2822->epoch timestamp)
580 (match (regexp-match re-rfc2822 timestamp)
581 [(list _ _ dd mo yyyy HH MM SS)
582 #:when (and dd mo yyyy HH MM SS)
583 (find-seconds (b->n SS)
584 (b->n MM)
585 (b->n HH)
586 (b->n dd)
587 (mon->num mo)
588 (b->n yyyy)
589 #f)]
590 [_
591 #f]))
592
593 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
594 (define (header-get headers name)
595 (match (filter-map (curry extract-field name) headers)
596 [(list val) val]
597 [_ #f]))
598
599 (: url-download-http-from-port
600 (-> Url (Listof (U Bytes String)) Input-Port
601 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
602 (define (url-download-http-from-port u headers body-input)
603 ; TODO Update message db from here? or where?
604 ; - 1st try can just be an in-memory set that gets written-to
605 ; and read-from disk as a whole.
606 (define u-str (url->string u))
607 (log-debug "url-download-http-from-port ~v into ~v" u-str cached-object-path)
608 (define cached-object-path (url->cache-object-path u))
609 (define cached-etag-path (url->cache-etag-path u))
610 (define cached-lmod-path (url->cache-lmod-path u))
611 (define etag (header-get headers #"ETag"))
612 (define lmod (header-get headers #"Last-Modified"))
613 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
614 (define lmod-prev (if (file-exists? cached-lmod-path)
615 (rfc2822->epoch (file->bytes cached-lmod-path))
616 #f))
617 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
618 (define cached?
619 (or (and etag
620 (file-exists? cached-etag-path)
621 (bytes=? etag (file->bytes cached-etag-path))
622 (begin
623 (log-debug "ETags match, skipping the rest of ~v" u-str)
624 #t))
625 (and lmod-curr
626 lmod-prev
627 (<= lmod-curr lmod-prev)
628 (begin
629 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
630 #t))))
631 (if (not cached?)
632 (begin
633 (log-debug
634 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
635 u-str etag lmod)
636 (make-parent-directory* cached-object-path)
637 (make-parent-directory* cached-etag-path)
638 (make-parent-directory* cached-lmod-path)
639 (call-with-output-file cached-object-path
640 (curry copy-port body-input)
641 #:exists 'replace)
642 (when etag
643 (display-to-file etag cached-etag-path #:exists 'replace))
644 (when lmod
645 (display-to-file lmod cached-lmod-path #:exists 'replace))
646 'downloaded-new)
647 'skipped-cached))
648
649 (: url-download-http (-> Positive-Float Url Download-Result))
650 (define (url-download-http timeout u)
651 (define u-str (url->string u))
652 (define timeout-chan (make-channel))
653 (define result-chan (make-channel))
654 (define timeout-thread
655 (thread (λ ()
656 ; Doing this instead of sync/timeout to distinguish error values,
657 ; rather than just have #f to work with.
658 (sleep timeout)
659 (channel-put timeout-chan '(error . timeout)))))
660 (define result-thread
661 (thread (λ ()
662 (define result
663 (with-handlers
664 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
665 ([exn:fail:network?
666 (λ (e) `(error . (net-error . ,e)))]
667 [exn?
668 (λ (e) `(error . (other . ,e)))])
669 (define-values (status-line headers body-input)
670 (http-sendrecv/url
671 u
672 #:headers (list (format "User-Agent: ~a" user-agent-str))))
673 (log-debug "headers: ~v" headers)
674 (log-debug "status-line: ~v" status-line)
675 (define status
676 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
677 (log-debug "status: ~v" status)
678 (let ([result
679 ; TODO Handle redirects.
680 ; TODO Should a redirect update a peer URL?
681 (match status
682 [200
683 `(ok . ,(url-download-http-from-port u headers body-input))]
684 [_
685 `(error . (http-not-ok . ,status))])])
686 (close-input-port body-input)
687 result)))
688 (channel-put result-chan result))))
689 (define result (sync timeout-chan result-chan))
690 (kill-thread result-thread)
691 (kill-thread timeout-thread)
692 result)
693
694 (: url-download (-> Positive-Float Url Download-Result))
695 (define (url-download timeout u)
696 (match (url-scheme u)
697 ; TODO Support Gopher.
698 [(or "http" "https")
699 (url-download-http timeout u)]
700 [scheme
701 `(error . (unsupported-url-scheme . ,scheme))]))
702
703 (: timeline-print (-> Out-Format (Listof Msg) Void))
704 (define (timeline-print out-format timeline)
705 (match timeline
706 ['()
707 (void)]
708 [(cons first-msg _)
709 (void (foldl (match-lambda**
710 [((and m (Msg _ _ from _ _)) (cons prev-from i))
711 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
712 (msg-print out-format i m)
713 (cons from i))])
714 (cons (Msg-from first-msg) 0)
715 timeline))]))
716
717 (: peer->msgs (-> Peer (Listof Msg)))
718 (define (peer->msgs peer)
719 (match-define (Peer nick url url-str _) peer)
720 (log-debug "Reading peer nick:~v url:~v" nick url-str)
721 (define msgs-data (url-read-cached url))
722 ; TODO Expire cache
723 (if msgs-data
724 (str->msgs peer msgs-data)
725 '()))
726
727 (: peer-download
728 (-> Positive-Float Peer
729 (Result (U 'skipped-cached 'downloaded-new)
730 Any)))
731 (define (peer-download timeout peer)
732 (match-define (Peer nick url u _) peer)
733 (log-info "Download BEGIN URL:~a" u)
734 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
735 (time-apply url-download (list timeout url)))
736 (define result (car results))
737 (log-info "Download END in ~a seconds, URL:~a, result:~s"
738 (/ tm-real-ms 1000.0)
739 u
740 result)
741 result)
742
743 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
744 (define (timeline-download num-workers timeout peers)
745 (define results
746 (concurrent-filter-map num-workers
747 (λ (p) (cons p (peer-download timeout p)))
748 peers))
749 (define peers-ok
750 (filter-map (match-lambda
751 [(cons p (cons 'ok _)) p]
752 [(cons _ (cons 'error e)) #f])
753 results))
754 (define peers-err
755 (filter-map (match-lambda
756 [(cons _ (cons 'ok _))
757 #f]
758 [(cons p (cons 'error e))
759 (struct-copy Peer p [comment (format "~s" e)])])
760 results))
761 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok.txt"))
762 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err.txt")))
763
764 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
765 (define (peers->timeline peers)
766 (append* (filter-map peer->msgs peers)))
767
768 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
769 (define (timeline-sort msgs order)
770 (define cmp (match order
771 ['old->new <]
772 ['new->old >]))
773 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
774 (Msg-ts-epoch b)))))
775
776 (: paths->peers (-> (Listof String) (Listof Peer)))
777 (define (paths->peers paths)
778 (let* ([paths (match paths
779 ['()
780 (let ([peer-refs-file (build-path tt-home-dir "following.txt")])
781 (log-debug
782 "No peer ref file paths provided, defaulting to ~v"
783 (path->string peer-refs-file))
784 (list peer-refs-file))]
785 [paths
786 (log-debug "Peer ref file paths provided: ~v" paths)
787 (map string->path paths)])]
788 [peers (apply peers-merge (map file->peers paths))])
789 (log-info "Read-in ~a peers." (length peers))
790 peers))
791
792 (: cache-filename->peer (-> Path-String (Option Peer)))
793 (define (cache-filename->peer filename)
794 (define nick #f) ; TODO Look it up in the nick-db when it exists.
795 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
796 (match (str->url url-str)
797 [#f #f]
798 [url (Peer nick url url-str #f)]))
799
800 (: peers-cached (-> (Listof Peer)))
801 (define (peers-cached)
802 ; TODO Expire cache?
803 (filter-map cache-filename->peer (directory-list cache-object-dir)))
804
805 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
806 (define (peers-mentioned msgs)
807 (append* (map Msg-mentions msgs)))
808
809 (: peers-filter-denied-domains (-> (Listof Peer) (Listof Peer)))
810 (define (peers-filter-denied-domains peers)
811 (define deny-file (build-path tt-home-dir "domains-deny.txt"))
812 (define denied-hosts
813 (list->set (map string-trim (filter-comments (file->lines deny-file)))))
814 (define denied-domain-patterns
815 (set-map denied-hosts (λ (h) (pregexp (string-append "\\." h "$")))))
816 (filter
817 (λ (p)
818 (define host (url-host (Peer-url p)))
819 (not (or (set-member? denied-hosts host)
820 (ormap (λ (d) (regexp-match? d host)) denied-domain-patterns))))
821 peers))
822
823 (: log-writer-stop (-> Thread Void))
824 (define (log-writer-stop log-writer)
825 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
826 (thread-wait log-writer))
827
828 (: log-writer-start (-> Log-Level Thread))
829 (define (log-writer-start level)
830 (let* ([logger
831 (make-logger #f #f level #f)]
832 [log-receiver
833 (make-log-receiver logger level)]
834 [log-writer
835 (thread
836 (λ ()
837 (parameterize
838 ([date-display-format 'iso-8601])
839 (let loop ()
840 (match-define (vector level msg _ topic) (sync log-receiver))
841 (unless (equal? topic 'stop)
842 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
843 (loop))))))])
844 (current-logger logger)
845 log-writer))
846
847 (: msgs->nick-hist (-> (Listof Msg) Url-Nick-Hist))
848 (define (msgs->nick-hist msgs)
849 (foldl
850 (λ (msg url->nick->hist)
851 (match-define (Msg curr _ from _ mentions) msg)
852 (foldl
853 (λ (peer url->nick->hist)
854 (match-define (Peer nick url _ _) peer)
855 (if nick
856 (hash-update url->nick->hist
857 url
858 (λ (nick->hist)
859 (hash-update nick->hist
860 nick
861 (match-lambda
862 [(Hist freq prev)
863 (Hist (+ 1 freq) (max prev curr))])
864 (Hist 0 0)))
865 (hash))
866 url->nick->hist))
867 url->nick->hist
868 (cons from mentions)))
869 (hash)
870 msgs))
871
872 (: url-nick-hist->file (-> Url-Nick-Hist Path-String Void))
873 (define (url-nick-hist->file unh filepath)
874 (define out (open-output-file filepath #:exists 'replace))
875 (for-each
876 (match-lambda
877 [(cons url nick->hist)
878 (displayln (url->string url) out)
879 (for-each (match-lambda
880 [(cons nick (Hist freq last))
881 (displayln (format " ~a ~a ~a" nick freq last) out)])
882 (sort (hash->list nick->hist)
883 (match-lambda**
884 [((cons _ (Hist a _)) (cons _ (Hist b _)))
885 (> a b)])))])
886 (sort
887 (hash->list unh)
888 (λ (a b) (string<? (url-host (car a))
889 (url-host (car b))))))
890 (close-output-port out))
891
892 (: url-nick-hist->dir (-> Url-Nick-Hist Path-String Void))
893 (define (url-nick-hist->dir unh dirpath)
894 (hash-for-each
895 unh
896 (λ (url nick->hist)
897 (define filename (string-append (uri-encode (url->string url)) ".txt"))
898 (define filepath (build-path dirpath filename))
899 (make-parent-directory* filepath)
900 (display-lines-to-file
901 (map (match-lambda
902 [(cons nick (Hist freq last))
903 (format "~a ~a ~a" nick freq last)])
904 (sort (hash->list nick->hist)
905 (match-lambda**
906 [((cons _ (Hist a _)) (cons _ (Hist b _)))
907 (> a b)])))
908 filepath
909 #:exists 'replace))))
910
911 (: update-nicks-history-files (-> Url-Nick-Hist Void))
912 (define (update-nicks-history-files unh)
913 (define nicks-dir (build-path tt-home-dir "nicks"))
914 (url-nick-hist->file unh (build-path nicks-dir "seen.txt"))
915 (url-nick-hist->dir unh (build-path nicks-dir "seen")))
916
917 (: url-nick-hist-most-by (-> Url-Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
918 (define (url-nick-hist-most-by url->nick->hist url by)
919 (match (hash-ref url->nick->hist url #f)
920 [#f #f]
921 [nick->hist
922 (match (sort (hash->list nick->hist)
923 (λ (a b) (> (by (cdr a))
924 (by (cdr b)))))
925 ['() #f]
926 [(cons (cons nick _) _) nick])]))
927
928 (: url-nick-hist-latest (-> Url-Nick-Hist Url (Option String)))
929 (define (url-nick-hist-latest unh url)
930 (url-nick-hist-most-by unh url Hist-last))
931
932 (: url-nick-hist-common (-> Url-Nick-Hist Url (Option String)))
933 (define (url-nick-hist-common unh url)
934 (url-nick-hist-most-by unh url Hist-freq))
935
936 (: peers-update-nick-to-common (-> Url-Nick-Hist (Listof Peer) (Listof Peer)))
937 (define (peers-update-nick-to-common unh peers)
938 (map
939 (λ (p)
940 (match (url-nick-hist-common unh (Peer-url p))
941 [#f p]
942 [n (struct-copy Peer p [nick n])]))
943 peers))
944
945 (module+ test
946 (let* ([url-str "http://foo"]
947 [url (string->url url-str)]
948 [nick1 "a"]
949 [nick2 "b"]
950 [nick3 "c"]
951 [ts-str-1 "2021-11-29T23:29:08-0500"]
952 [ts-str-2 "2021-11-29T23:30:00-0500"]
953 [ts-1 (rfc3339->epoch ts-str-1)]
954 [ts-2 (rfc3339->epoch ts-str-2)]
955 [msgs
956 (map (match-lambda
957 [(cons ts-str nick)
958 (str->msg (str->peer "test http://test")
959 (string-append ts-str " Hi @<" nick " " url-str ">"))])
960 (list (cons ts-str-2 nick1)
961 (cons ts-str-1 nick2)
962 (cons ts-str-1 nick2)
963 (cons ts-str-1 nick3)
964 (cons ts-str-1 nick3)
965 (cons ts-str-1 nick3)))]
966 [hist
967 (msgs->nick-hist msgs)])
968 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
969 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
970 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
971 (check-equal? (url-nick-hist-common hist url) nick3)
972 (check-equal? (url-nick-hist-latest hist url) nick1)))
973
974 (: crawl (-> Void))
975 (define (crawl)
976 ; TODO Test the non-io parts of crawling
977 (let* ([peers-all-file
978 (build-path pub-peers-dir "all.txt")]
979 [peers-mentioned-file
980 (build-path pub-peers-dir "mentioned.txt")]
981 [peers-parsed-file
982 (build-path pub-peers-dir "downloaded-and-parsed.txt")]
983 [peers-cached-file
984 (build-path pub-peers-dir "downloaded.txt")]
985 [peers-cached
986 (peers-cached)]
987 [cached-timeline
988 (peers->timeline peers-cached)]
989 [url-nick-hist
990 (msgs->nick-hist cached-timeline)]
991 [peers-mentioned-curr
992 (peers-mentioned cached-timeline)]
993 [peers-mentioned-prev
994 (file->peers peers-mentioned-file)]
995 [peers-all-prev
996 (file->peers peers-all-file)]
997 [peers-mentioned
998 (peers-merge peers-mentioned-prev
999 peers-mentioned-curr)]
1000 [peers-all
1001 (peers-update-nick-to-common
1002 url-nick-hist
1003 (peers-merge peers-mentioned
1004 peers-all-prev
1005 peers-cached))]
1006 [peers-discovered
1007 (set->list (set-subtract (make-immutable-peers peers-all)
1008 (make-immutable-peers peers-all-prev)))]
1009 [peers-parsed
1010 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
1011 ; TODO Deeper de-duping
1012 (log-info "Known peers cached ~a" (length peers-cached))
1013 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
1014 (log-info "Known peers parsed ~a" (length peers-parsed))
1015 (log-info "Known peers total: ~a" (length peers-all))
1016 (log-info "Discovered ~a new peers:~n~a"
1017 (length peers-discovered)
1018 (pretty-format (map
1019 (match-lambda
1020 [(Peer n _ u c) (list n u c)])
1021 peers-discovered)))
1022 (update-nicks-history-files url-nick-hist)
1023 (peers->file peers-cached
1024 peers-cached-file)
1025 (peers->file peers-mentioned
1026 peers-mentioned-file)
1027 (peers->file peers-parsed
1028 peers-parsed-file)
1029 (peers->file peers-all
1030 peers-all-file)))
1031
1032 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
1033 (define (read file-paths ts-min ts-max order out-format)
1034 (let* ([peers
1035 (paths->peers file-paths)]
1036 [msgs
1037 (timeline-sort (peers->timeline peers) order)]
1038 [include?
1039 (λ (m)
1040 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
1041 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
1042 (timeline-print out-format (filter include? msgs))))
1043
1044 (: upload (-> Void))
1045 (define (upload)
1046 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
1047 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
1048 (exit 0)
1049 (exit 1)))
1050
1051 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
1052 (define (download file-paths num-workers timeout)
1053 (let* ([peers-given (paths->peers file-paths)]
1054 [peers-kept (peers-filter-denied-domains peers-given)]
1055 [peers-denied (set-subtract peers-given peers-kept)])
1056 (log-info "Denied ~a peers" (length peers-denied))
1057 (define-values (_res _cpu real-ms _gc)
1058 (time-apply timeline-download (list num-workers timeout peers-kept)))
1059 (log-info "Downloaded timelines from ~a peers in ~a seconds."
1060 (length peers-kept)
1061 (/ real-ms 1000.0))))
1062
1063 (: dispatch (-> String Void))
1064 (define (dispatch command)
1065 (match command
1066 [(or "d" "download")
1067 (let ([num-workers 20] ; 20 was fastest out of the tried: 1, 5, 10, 20, 25, 30.
1068 [timeout 10.0])
1069 (command-line
1070 #:program "tt download"
1071 #:once-each
1072 [("-j" "--jobs")
1073 njobs "Number of concurrent jobs."
1074 (set! num-workers (string->number njobs))]
1075 [("-t" "--timeout")
1076 seconds "Timeout seconds per request."
1077 (set! timeout (string->number seconds))]
1078 #:args file-paths
1079 (download file-paths num-workers timeout)))]
1080 [(or "u" "upload")
1081 (command-line
1082 #:program "tt upload" #:args () (upload))]
1083 [(or "r" "read")
1084 (let ([out-format 'multi-line]
1085 [order 'old->new]
1086 [ts-min #f]
1087 [ts-max #f])
1088 (command-line
1089 #:program "tt read"
1090 #:once-each
1091 [("-r" "--rev")
1092 "Reverse displayed timeline order."
1093 (set! order 'new->old)]
1094 [("-m" "--min")
1095 m "Earliest time to display (ignore anything before it)."
1096 (set! ts-min (rfc3339->epoch m))]
1097 [("-x" "--max")
1098 x "Latest time to display (ignore anything after it)."
1099 (set! ts-max (rfc3339->epoch x))]
1100 #:once-any
1101 [("-s" "--short")
1102 "Short output format"
1103 (set! out-format 'single-line)]
1104 [("-l" "--long")
1105 "Long output format"
1106 (set! out-format 'multi-line)]
1107 #:args file-paths
1108 (read file-paths ts-min ts-max order out-format)))]
1109 [(or "c" "crawl")
1110 (command-line
1111 #:program "tt crawl" #:args () (crawl))]
1112 [command
1113 (eprintf "Error: invalid command: ~v\n" command)
1114 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1115 (exit 1)]))
1116
1117 (module+ main
1118 (let ([log-level 'info])
1119 (command-line
1120 #:program
1121 "tt"
1122 #:once-each
1123 [("-d" "--debug")
1124 "Enable debug log level."
1125 (set! log-level 'debug)]
1126 #:help-labels
1127 ""
1128 "and <command> is one of"
1129 "r, read : Read the timeline (offline operation)."
1130 "d, download : Download the timeline."
1131 ; TODO Add path dynamically
1132 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
1133 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
1134 ""
1135 #:args (command . args)
1136 (define log-writer (log-writer-start log-level))
1137 (current-command-line-arguments (list->vector args))
1138 (set-user-agent-str (build-path tt-home-dir "user.txt"))
1139 ; TODO dispatch should return status with which we should exit after cleanups
1140 (dispatch command)
1141 (log-writer-stop log-writer))))
This page took 0.162386 seconds and 4 git commands to generate.