Refactor merge
[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 (merge-2 p1 p2)
170 (match* (p1 p2)
171 [((Peer n1 _ _ _) (Peer n2 _ _ _)) #:when (and n1 n2) p1] ; TODO compare which is more-common?
172 [((Peer #f _ _ _) (Peer #f _ _ _)) p1] ; TODO update with most-common nick?
173 [((Peer n1 _ _ _) (Peer #f _ _ _)) p1]
174 [((Peer #f _ _ _) (Peer n2 _ _ _)) p2]))
175 (define (merge-n peers)
176 (match peers
177 ['() (raise 'impossible)]
178 [(list p) p]
179 [(list* p1 p2 ps) (merge-n (cons (merge-2 p1 p2) ps))]))
180 (sort (map merge-n (group-by Peer-url-str (append* peer-sets)))
181 (match-lambda**
182 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
183
184 (module+ test
185 (let* ([u1 "http://foo/bar"]
186 [u2 "http://baz/quux"]
187 [p1 (Peer #f (string->url u1) u1 #f)]
188 [p2 (Peer "a" (string->url u1) u1 #f)]
189 [p3 (Peer "b" (string->url u2) u2 #f)]
190 [s1 (list p1)]
191 [s2 (list p2 p3)])
192 (check-equal? (list p3 p2) (peers-merge s1 s2))
193 (check-equal? (list p3 p2) (peers-merge s2 s1))))
194
195 (: tt-home-dir Path-String)
196 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
197
198 (: pub-peers-dir Path-String)
199 (define pub-peers-dir (build-path tt-home-dir "peers"))
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 [url (Peer-url-str (Msg-from msg))]
254 [text (Msg-text msg)])
255 (match out-format
256 ['single-line
257 (let ([nick (if nick nick url)])
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 url 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-url)
327 (str->peer nick-url)]))
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-url")]
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 [url "http://bar/"]
369 [peer (Peer nick (string->url url) url #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-url (Msg-from actual))
386 (Peer-url (Msg-from expected))
387 "str->msg url")
388 (check-equal?
389 (Peer-url-str (Msg-from actual))
390 (Peer-url-str (Msg-from expected))
391 "str->msg url-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 url)
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 url))))
424
425 (: url->cache-file-path-v2 (-> Url Path-String))
426 (define (url->cache-file-path-v2 url)
427 (build-path cache-object-dir (uri-encode (url->string url))))
428
429 (define url->cache-object-path
430 url->cache-file-path-v2)
431
432 (define (url->cache-etag-path url)
433 (build-path cache-dir "etags" (uri-encode (url->string url))))
434
435 (define (url->cache-lmod-path url)
436 (build-path cache-dir "lmods" (uri-encode (url->string url))))
437
438 (: url-read-cached (-> Url (Option String)))
439 (define (url-read-cached url)
440 (define path-v1 (url->cache-file-path-v1 url))
441 (define path-v2 (url->cache-file-path-v2 url))
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 URL: ~a" (url->string url))
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 URL 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 (make-parent-directory* path)
527 (display-lines-to-file
528 (map peer->str
529 (sort peers
530 (match-lambda**
531 [((Peer n1 _ _ _) (Peer n2 _ _ _))
532 (string<? (if n1 n1 "")
533 (if n2 n2 ""))])))
534 path
535 #:exists 'replace))
536
537 (: file->peers (-> Path-String (Listof Peer)))
538 (define (file->peers file-path)
539 (if (file-exists? file-path)
540 (str->peers (file->string file-path))
541 (begin
542 (log-warning "File does not exist: ~v" (path->string file-path))
543 '())))
544
545 (define re-rfc2822
546 #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")
547
548 (: b->n (-> Bytes (Option Number)))
549 (define (b->n b)
550 (string->number (bytes->string/utf-8 b)))
551
552 (: mon->num (-> Bytes Natural))
553 (define/match (mon->num mon)
554 [(#"Jan") 1]
555 [(#"Feb") 2]
556 [(#"Mar") 3]
557 [(#"Apr") 4]
558 [(#"May") 5]
559 [(#"Jun") 6]
560 [(#"Jul") 7]
561 [(#"Aug") 8]
562 [(#"Sep") 9]
563 [(#"Oct") 10]
564 [(#"Nov") 11]
565 [(#"Dec") 12])
566
567 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
568 (define (rfc2822->epoch timestamp)
569 (match (regexp-match re-rfc2822 timestamp)
570 [(list _ _ dd mo yyyy HH MM SS)
571 #:when (and dd mo yyyy HH MM SS)
572 (find-seconds (b->n SS)
573 (b->n MM)
574 (b->n HH)
575 (b->n dd)
576 (mon->num mo)
577 (b->n yyyy)
578 #f)]
579 [_
580 #f]))
581
582 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
583 (define (header-get headers name)
584 (match (filter-map (curry extract-field name) headers)
585 [(list val) val]
586 [_ #f]))
587
588 (: url-download-http-from-port
589 (-> Url (Listof (U Bytes String)) Input-Port
590 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
591 (define (url-download-http-from-port u headers body-input)
592 ; TODO Update message db from here? or where?
593 ; - 1st try can just be an in-memory set that gets written-to
594 ; and read-from disk as a whole.
595 (define u-str (url->string u))
596 (log-debug "url-download-http-from-port ~v into ~v" u-str cached-object-path)
597 (define cached-object-path (url->cache-object-path u))
598 (define cached-etag-path (url->cache-etag-path u))
599 (define cached-lmod-path (url->cache-lmod-path u))
600 (define etag (header-get headers #"ETag"))
601 (define lmod (header-get headers #"Last-Modified"))
602 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
603 (define lmod-prev (if (file-exists? cached-lmod-path)
604 (rfc2822->epoch (file->bytes cached-lmod-path))
605 #f))
606 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
607 (define cached?
608 (or (and etag
609 (file-exists? cached-etag-path)
610 (bytes=? etag (file->bytes cached-etag-path))
611 (begin
612 (log-debug "ETags match, skipping the rest of ~v" u-str)
613 #t))
614 (and lmod-curr
615 lmod-prev
616 (<= lmod-curr lmod-prev)
617 (begin
618 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
619 #t))))
620 (if (not cached?)
621 (begin
622 (log-debug
623 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
624 u-str etag lmod)
625 (make-parent-directory* cached-object-path)
626 (make-parent-directory* cached-etag-path)
627 (make-parent-directory* cached-lmod-path)
628 (call-with-output-file cached-object-path
629 (curry copy-port body-input)
630 #:exists 'replace)
631 (when etag
632 (display-to-file etag cached-etag-path #:exists 'replace))
633 (when lmod
634 (display-to-file lmod cached-lmod-path #:exists 'replace))
635 'downloaded-new)
636 'skipped-cached))
637
638 (: url-download-http (-> Positive-Float Url Download-Result))
639 (define (url-download-http timeout u)
640 (define u-str (url->string u))
641 (define timeout-chan (make-channel))
642 (define result-chan (make-channel))
643 (define timeout-thread
644 (thread (λ ()
645 ; Doing this instead of sync/timeout to distinguish error values,
646 ; rather than just have #f to work with.
647 (sleep timeout)
648 (channel-put timeout-chan '(error . timeout)))))
649 (define result-thread
650 (thread (λ ()
651 (define result
652 (with-handlers
653 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
654 ([exn:fail:network?
655 (λ (e) `(error . (net-error . ,e)))]
656 [exn?
657 (λ (e) `(error . (other . ,e)))])
658 (define-values (status-line headers body-input)
659 (http-sendrecv/url
660 u
661 #:headers (list (format "User-Agent: ~a" user-agent-str))))
662 (log-debug "headers: ~v" headers)
663 (log-debug "status-line: ~v" status-line)
664 (define status
665 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
666 (log-debug "status: ~v" status)
667 (let ([result
668 ; TODO Handle redirects.
669 ; TODO Should a redirect update a peer URL?
670 (match status
671 [200
672 `(ok . ,(url-download-http-from-port u headers body-input))]
673 [_
674 `(error . (http-not-ok . ,status))])])
675 (close-input-port body-input)
676 result)))
677 (channel-put result-chan result))))
678 (define result (sync timeout-chan result-chan))
679 (kill-thread result-thread)
680 (kill-thread timeout-thread)
681 result)
682
683 (: url-download (-> Positive-Float Url Download-Result))
684 (define (url-download timeout u)
685 (match (url-scheme u)
686 ; TODO Support Gopher.
687 [(or "http" "https")
688 (url-download-http timeout u)]
689 [scheme
690 `(error . (unsupported-url-scheme . ,scheme))]))
691
692 (: timeline-print (-> Out-Format (Listof Msg) Void))
693 (define (timeline-print out-format timeline)
694 (match timeline
695 ['()
696 (void)]
697 [(cons first-msg _)
698 (void (foldl (match-lambda**
699 [((and m (Msg _ _ from _ _)) (cons prev-from i))
700 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
701 (msg-print out-format i m)
702 (cons from i))])
703 (cons (Msg-from first-msg) 0)
704 timeline))]))
705
706 (: peer->msgs (-> Peer (Listof Msg)))
707 (define (peer->msgs peer)
708 (match-define (Peer nick url url-str _) peer)
709 (log-debug "Reading peer nick:~v url:~v" nick url-str)
710 (define msgs-data (url-read-cached url))
711 ; TODO Expire cache
712 (if msgs-data
713 (str->msgs peer msgs-data)
714 '()))
715
716 (: peer-download
717 (-> Positive-Float Peer
718 (Result (U 'skipped-cached 'downloaded-new)
719 Any)))
720 (define (peer-download timeout peer)
721 (match-define (Peer nick url u _) peer)
722 (log-info "Download BEGIN URL:~a" u)
723 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
724 (time-apply url-download (list timeout url)))
725 (define result (car results))
726 (log-info "Download END in ~a seconds, URL:~a, result:~s"
727 (/ tm-real-ms 1000.0)
728 u
729 result)
730 result)
731
732 (: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
733 (define (timeline-download num-workers timeout peers)
734 (define results
735 (concurrent-filter-map num-workers
736 (λ (p) (cons p (peer-download timeout p)))
737 peers))
738 (define peers-ok
739 (filter-map (match-lambda
740 [(cons p (cons 'ok _)) p]
741 [(cons _ (cons 'error e)) #f])
742 results))
743 (define peers-err
744 (filter-map (match-lambda
745 [(cons _ (cons 'ok _))
746 #f]
747 [(cons p (cons 'error e))
748 (struct-copy Peer p [comment (format "~s" e)])])
749 results))
750 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok.txt"))
751 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err.txt")))
752
753 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
754 (define (peers->timeline peers)
755 (append* (filter-map peer->msgs peers)))
756
757 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
758 (define (timeline-sort msgs order)
759 (define cmp (match order
760 ['old->new <]
761 ['new->old >]))
762 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
763 (Msg-ts-epoch b)))))
764
765 (: paths->peers (-> (Listof String) (Listof Peer)))
766 (define (paths->peers paths)
767 (let* ([paths (match paths
768 ['()
769 (let ([peer-refs-file (build-path tt-home-dir "following.txt")])
770 (log-debug
771 "No peer ref file paths provided, defaulting to ~v"
772 (path->string peer-refs-file))
773 (list peer-refs-file))]
774 [paths
775 (log-debug "Peer ref file paths provided: ~v" paths)
776 (map string->path paths)])]
777 [peers (apply peers-merge (map file->peers paths))])
778 (log-info "Read-in ~a peers." (length peers))
779 peers))
780
781 (: cache-filename->peer (-> Path-String (Option Peer)))
782 (define (cache-filename->peer filename)
783 (define nick #f) ; TODO Look it up in the nick-db when it exists.
784 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
785 (match (str->url url-str)
786 [#f #f]
787 [url (Peer nick url url-str #f)]))
788
789 (: peers-cached (-> (Listof Peer)))
790 (define (peers-cached)
791 ; TODO Expire cache?
792 (filter-map cache-filename->peer (directory-list cache-object-dir)))
793
794 (: peers-mentioned (-> (Listof Msg) (Listof Peer)))
795 (define (peers-mentioned msgs)
796 (append* (map Msg-mentions msgs)))
797
798 (: peers-filter-denied-domains (-> (Listof Peer) (Listof Peer)))
799 (define (peers-filter-denied-domains peers)
800 (define deny-file (build-path tt-home-dir "domains-deny.txt"))
801 (define denied-hosts
802 (list->set (map string-trim (filter-comments (file->lines deny-file)))))
803 (define denied-domain-patterns
804 (set-map denied-hosts (λ (h) (pregexp (string-append "\\." h "$")))))
805 (filter
806 (λ (p)
807 (define host (url-host (Peer-url p)))
808 (not (or (set-member? denied-hosts host)
809 (ormap (λ (d) (regexp-match? d host)) denied-domain-patterns))))
810 peers))
811
812 (: log-writer-stop (-> Thread Void))
813 (define (log-writer-stop log-writer)
814 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
815 (thread-wait log-writer))
816
817 (: log-writer-start (-> Log-Level Thread))
818 (define (log-writer-start level)
819 (let* ([logger
820 (make-logger #f #f level #f)]
821 [log-receiver
822 (make-log-receiver logger level)]
823 [log-writer
824 (thread
825 (λ ()
826 (parameterize
827 ([date-display-format 'iso-8601])
828 (let loop ()
829 (match-define (vector level msg _ topic) (sync log-receiver))
830 (unless (equal? topic 'stop)
831 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
832 (loop))))))])
833 (current-logger logger)
834 log-writer))
835
836 (: msgs->nick-hist (-> (Listof Msg) Url-Nick-Hist))
837 (define (msgs->nick-hist msgs)
838 (foldl
839 (λ (msg url->nick->hist)
840 (match-define (Msg curr _ from _ mentions) msg)
841 (foldl
842 (λ (peer url->nick->hist)
843 (match-define (Peer nick url _ _) peer)
844 (if nick
845 (hash-update url->nick->hist
846 url
847 (λ (nick->hist)
848 (hash-update nick->hist
849 nick
850 (match-lambda
851 [(Hist freq prev)
852 (Hist (+ 1 freq) (max prev curr))])
853 (Hist 0 0)))
854 (hash))
855 url->nick->hist))
856 url->nick->hist
857 (cons from mentions)))
858 (hash)
859 msgs))
860
861 (: url-nick-hist->file (-> Url-Nick-Hist Path-String Void))
862 (define (url-nick-hist->file unh filepath)
863 (define out (open-output-file filepath #:exists 'replace))
864 (for-each
865 (match-lambda
866 [(cons url nick->hist)
867 (displayln (url->string url) out)
868 (for-each (match-lambda
869 [(cons nick (Hist freq last))
870 (displayln (format " ~a ~a ~a" nick freq last) out)])
871 (sort (hash->list nick->hist)
872 (match-lambda**
873 [((cons _ (Hist a _)) (cons _ (Hist b _)))
874 (> a b)])))])
875 (sort
876 (hash->list unh)
877 (λ (a b) (string<? (url-host (car a))
878 (url-host (car b))))))
879 (close-output-port out))
880
881 (: url-nick-hist->dir (-> Url-Nick-Hist Path-String Void))
882 (define (url-nick-hist->dir unh dirpath)
883 (hash-for-each
884 unh
885 (λ (url nick->hist)
886 (define filename (string-append (uri-encode (url->string url)) ".txt"))
887 (define filepath (build-path dirpath filename))
888 (make-parent-directory* filepath)
889 (display-lines-to-file
890 (map (match-lambda
891 [(cons nick (Hist freq last))
892 (format "~a ~a ~a" nick freq last)])
893 (sort (hash->list nick->hist)
894 (match-lambda**
895 [((cons _ (Hist a _)) (cons _ (Hist b _)))
896 (> a b)])))
897 filepath
898 #:exists 'replace))))
899
900 (: update-nicks-history-files (-> Url-Nick-Hist Void))
901 (define (update-nicks-history-files unh)
902 (define nicks-dir (build-path tt-home-dir "nicks"))
903 (url-nick-hist->file unh (build-path nicks-dir "seen.txt"))
904 (url-nick-hist->dir unh (build-path nicks-dir "seen")))
905
906 (: url-nick-hist-most-by (-> Url-Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
907 (define (url-nick-hist-most-by url->nick->hist url by)
908 (match (hash-ref url->nick->hist url #f)
909 [#f #f]
910 [nick->hist
911 (match (sort (hash->list nick->hist)
912 (λ (a b) (> (by (cdr a))
913 (by (cdr b)))))
914 ['() #f]
915 [(cons (cons nick _) _) nick])]))
916
917 (: url-nick-hist-latest (-> Url-Nick-Hist Url (Option String)))
918 (define (url-nick-hist-latest unh url)
919 (url-nick-hist-most-by unh url Hist-last))
920
921 (: url-nick-hist-common (-> Url-Nick-Hist Url (Option String)))
922 (define (url-nick-hist-common unh url)
923 (url-nick-hist-most-by unh url Hist-freq))
924
925 (: peers-update-nick-to-common (-> Url-Nick-Hist (Listof Peer) (Listof Peer)))
926 (define (peers-update-nick-to-common unh peers)
927 (map
928 (λ (p)
929 (match (url-nick-hist-common unh (Peer-url p))
930 [#f p]
931 [n (struct-copy Peer p [nick n])]))
932 peers))
933
934 (module+ test
935 (let* ([url-str "http://foo"]
936 [url (string->url url-str)]
937 [nick1 "a"]
938 [nick2 "b"]
939 [nick3 "c"]
940 [ts-str-1 "2021-11-29T23:29:08-0500"]
941 [ts-str-2 "2021-11-29T23:30:00-0500"]
942 [ts-1 (rfc3339->epoch ts-str-1)]
943 [ts-2 (rfc3339->epoch ts-str-2)]
944 [msgs
945 (map (match-lambda
946 [(cons ts-str nick)
947 (str->msg (str->peer "test http://test")
948 (string-append ts-str " Hi @<" nick " " url-str ">"))])
949 (list (cons ts-str-2 nick1)
950 (cons ts-str-1 nick2)
951 (cons ts-str-1 nick2)
952 (cons ts-str-1 nick3)
953 (cons ts-str-1 nick3)
954 (cons ts-str-1 nick3)))]
955 [hist
956 (msgs->nick-hist msgs)])
957 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
958 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
959 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
960 (check-equal? (url-nick-hist-common hist url) nick3)
961 (check-equal? (url-nick-hist-latest hist url) nick1)))
962
963 (: crawl (-> Void))
964 (define (crawl)
965 ; TODO Test the non-io parts of crawling
966 (let* ([peers-all-file
967 (build-path pub-peers-dir "all.txt")]
968 [peers-mentioned-file
969 (build-path pub-peers-dir "mentioned.txt")]
970 [peers-parsed-file
971 (build-path pub-peers-dir "downloaded-and-parsed.txt")]
972 [peers-cached-file
973 (build-path pub-peers-dir "downloaded.txt")]
974 [peers-cached
975 (peers-cached)]
976 [cached-timeline
977 (peers->timeline peers-cached)]
978 [url-nick-hist
979 (msgs->nick-hist cached-timeline)]
980 [peers-mentioned-curr
981 (peers-mentioned cached-timeline)]
982 [peers-mentioned-prev
983 (file->peers peers-mentioned-file)]
984 [peers-all-prev
985 (file->peers peers-all-file)]
986 [peers-mentioned
987 (peers-merge peers-mentioned-prev
988 peers-mentioned-curr)]
989 [peers-all
990 (peers-update-nick-to-common
991 url-nick-hist
992 (peers-merge peers-mentioned
993 peers-all-prev
994 peers-cached))]
995 [peers-discovered
996 (set->list (set-subtract (make-immutable-peers peers-all)
997 (make-immutable-peers peers-all-prev)))]
998 [peers-parsed
999 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
1000 ; TODO Deeper de-duping
1001 (log-info "Known peers cached ~a" (length peers-cached))
1002 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
1003 (log-info "Known peers parsed ~a" (length peers-parsed))
1004 (log-info "Known peers total: ~a" (length peers-all))
1005 (log-info "Discovered ~a new peers:~n~a"
1006 (length peers-discovered)
1007 (pretty-format (map
1008 (match-lambda
1009 [(Peer n _ u c) (list n u c)])
1010 peers-discovered)))
1011 (update-nicks-history-files url-nick-hist)
1012 (peers->file peers-cached
1013 peers-cached-file)
1014 (peers->file peers-mentioned
1015 peers-mentioned-file)
1016 (peers->file peers-parsed
1017 peers-parsed-file)
1018 (peers->file peers-all
1019 peers-all-file)))
1020
1021 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
1022 (define (read file-paths ts-min ts-max order out-format)
1023 (let* ([peers
1024 (paths->peers file-paths)]
1025 [msgs
1026 (timeline-sort (peers->timeline peers) order)]
1027 [include?
1028 (λ (m)
1029 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
1030 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
1031 (timeline-print out-format (filter include? msgs))))
1032
1033 (: upload (-> Void))
1034 (define (upload)
1035 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
1036 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
1037 (exit 0)
1038 (exit 1)))
1039
1040 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
1041 (define (download file-paths num-workers timeout)
1042 (let* ([peers-given (paths->peers file-paths)]
1043 [peers-kept (peers-filter-denied-domains peers-given)]
1044 [peers-denied (set-subtract peers-given peers-kept)])
1045 (log-info "Denied ~a peers" (length peers-denied))
1046 (define-values (_res _cpu real-ms _gc)
1047 (time-apply timeline-download (list num-workers timeout peers-kept)))
1048 (log-info "Downloaded timelines from ~a peers in ~a seconds."
1049 (length peers-kept)
1050 (/ real-ms 1000.0))))
1051
1052 (: dispatch (-> String Void))
1053 (define (dispatch command)
1054 (match command
1055 [(or "d" "download")
1056 (let ([num-workers 20] ; 20 was fastest out of the tried: 1, 5, 10, 20, 25, 30.
1057 [timeout 10.0])
1058 (command-line
1059 #:program "tt download"
1060 #:once-each
1061 [("-j" "--jobs")
1062 njobs "Number of concurrent jobs."
1063 (set! num-workers (string->number njobs))]
1064 [("-t" "--timeout")
1065 seconds "Timeout seconds per request."
1066 (set! timeout (string->number seconds))]
1067 #:args file-paths
1068 (download file-paths num-workers timeout)))]
1069 [(or "u" "upload")
1070 (command-line
1071 #:program "tt upload" #:args () (upload))]
1072 [(or "r" "read")
1073 (let ([out-format 'multi-line]
1074 [order 'old->new]
1075 [ts-min #f]
1076 [ts-max #f])
1077 (command-line
1078 #:program "tt read"
1079 #:once-each
1080 [("-r" "--rev")
1081 "Reverse displayed timeline order."
1082 (set! order 'new->old)]
1083 [("-m" "--min")
1084 m "Earliest time to display (ignore anything before it)."
1085 (set! ts-min (rfc3339->epoch m))]
1086 [("-x" "--max")
1087 x "Latest time to display (ignore anything after it)."
1088 (set! ts-max (rfc3339->epoch x))]
1089 #:once-any
1090 [("-s" "--short")
1091 "Short output format"
1092 (set! out-format 'single-line)]
1093 [("-l" "--long")
1094 "Long output format"
1095 (set! out-format 'multi-line)]
1096 #:args file-paths
1097 (read file-paths ts-min ts-max order out-format)))]
1098 [(or "c" "crawl")
1099 (command-line
1100 #:program "tt crawl" #:args () (crawl))]
1101 [command
1102 (eprintf "Error: invalid command: ~v\n" command)
1103 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1104 (exit 1)]))
1105
1106 (module+ main
1107 (let ([log-level 'info])
1108 (command-line
1109 #:program
1110 "tt"
1111 #:once-each
1112 [("-d" "--debug")
1113 "Enable debug log level."
1114 (set! log-level 'debug)]
1115 #:help-labels
1116 ""
1117 "and <command> is one of"
1118 "r, read : Read the timeline (offline operation)."
1119 "d, download : Download the timeline."
1120 ; TODO Add path dynamically
1121 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
1122 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
1123 ""
1124 #:args (command . args)
1125 (define log-writer (log-writer-start log-level))
1126 (current-command-line-arguments (list->vector args))
1127 (set-user-agent-str (build-path tt-home-dir "user.txt"))
1128 ; TODO dispatch should return status with which we should exit after cleanups
1129 (dispatch command)
1130 (log-writer-stop log-writer))))
This page took 0.123236 seconds and 4 git commands to generate.