Re-org peer set file names and locations
[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 (: log-writer-stop (-> Thread Void))
796 (define (log-writer-stop log-writer)
797 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
798 (thread-wait log-writer))
799
800 (: log-writer-start (-> Log-Level Thread))
801 (define (log-writer-start level)
802 (let* ([logger
803 (make-logger #f #f level #f)]
804 [log-receiver
805 (make-log-receiver logger level)]
806 [log-writer
807 (thread
808 (λ ()
809 (parameterize
810 ([date-display-format 'iso-8601])
811 (let loop ()
812 (match-define (vector level msg _ topic) (sync log-receiver))
813 (unless (equal? topic 'stop)
814 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
815 (loop))))))])
816 (current-logger logger)
817 log-writer))
818
819 (: msgs->nick-hist (-> (Listof Msg) Nick-Hist))
820 (define (msgs->nick-hist msgs)
821 (foldl
822 (λ (msg url->nick->hist)
823 (match-define (Msg curr _ from _ mentions) msg)
824 (foldl
825 (λ (peer url->nick->hist)
826 (match-define (Peer nick url _ _) peer)
827 (if nick
828 (hash-update url->nick->hist
829 url
830 (λ (nick->hist)
831 (hash-update nick->hist
832 nick
833 (match-lambda
834 [(Hist freq prev)
835 (Hist (+ 1 freq) (max prev curr))])
836 (Hist 0 0)))
837 (hash))
838 url->nick->hist))
839 url->nick->hist
840 (cons from mentions)))
841 (hash)
842 msgs))
843
844 (: update-nicks-history-files (-> Nick-Hist Void))
845 (define (update-nicks-history-files nick-hist)
846 (hash-for-each
847 nick-hist
848 (λ (url nick->hist)
849 (define filename (string-append (uri-encode (url->string url)) ".txt"))
850 (define filepath (build-path tt-home-dir "nicks" "seen" filename))
851 (make-parent-directory* filepath)
852 (display-lines-to-file
853 (map (match-lambda
854 [(cons nick (Hist freq last))
855 (format "~a ~a ~a" nick freq last)])
856 (sort (hash->list nick->hist)
857 (match-lambda**
858 [((cons _ (Hist a _)) (cons _ (Hist b _)))
859 (> a b)])))
860 filepath
861 #:exists 'replace))))
862
863 (: nick-hist-most-by (-> Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
864 (define (nick-hist-most-by url->nick->hist url by)
865 (match (hash-ref url->nick->hist url #f)
866 [#f #f]
867 [nick->hist
868 (match (sort (hash->list nick->hist)
869 (λ (a b) (> (by (cdr a))
870 (by (cdr b)))))
871 ['() #f]
872 [(cons (cons nick _) _) nick])]))
873
874 (: nick-hist-latest (-> Nick-Hist Url (Option String)))
875 (define (nick-hist-latest nick-hist url)
876 (nick-hist-most-by nick-hist url Hist-last))
877
878 (: nick-hist-common (-> Nick-Hist Url (Option String)))
879 (define (nick-hist-common nick-hist url)
880 (nick-hist-most-by nick-hist url Hist-freq))
881
882 (: peers-update-nick-to-common (-> Nick-Hist (Listof Peer) (Listof Peer)))
883 (define (peers-update-nick-to-common nick-hist peers)
884 (map
885 (λ (p)
886 (match (nick-hist-common nick-hist (Peer-uri p))
887 [#f p]
888 [n (struct-copy Peer p [nick n])]))
889 peers))
890
891 (module+ test
892 (let* ([url-str "http://foo"]
893 [url (string->url url-str)]
894 [nick1 "a"]
895 [nick2 "b"]
896 [nick3 "c"]
897 [ts-str-1 "2021-11-29T23:29:08-0500"]
898 [ts-str-2 "2021-11-29T23:30:00-0500"]
899 [ts-1 (rfc3339->epoch ts-str-1)]
900 [ts-2 (rfc3339->epoch ts-str-2)]
901 [msgs
902 (map (match-lambda
903 [(cons ts-str nick)
904 (str->msg (str->peer "test http://test")
905 (string-append ts-str " Hi @<" nick " " url-str ">"))])
906 (list (cons ts-str-2 nick1)
907 (cons ts-str-1 nick2)
908 (cons ts-str-1 nick2)
909 (cons ts-str-1 nick3)
910 (cons ts-str-1 nick3)
911 (cons ts-str-1 nick3)))]
912 [hist
913 (msgs->nick-hist msgs)])
914 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
915 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
916 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
917 (check-equal? (nick-hist-common hist url) nick3)
918 (check-equal? (nick-hist-latest hist url) nick1)))
919
920 (: crawl (-> Void))
921 (define (crawl)
922 ; TODO Test the non-io parts of crawling
923 (let* ([peers-all-file
924 (build-path pub-peers-dir "all.txt")]
925 [peers-mentioned-file
926 (build-path pub-peers-dir "mentioned.txt")]
927 [peers-parsed-file
928 (build-path pub-peers-dir "downloaded-and-parsed.txt")]
929 [peers-cached-file
930 (build-path pub-peers-dir "downloaded.txt")]
931 [peers-cached
932 (peers-cached)]
933 [cached-timeline
934 (peers->timeline peers-cached)]
935 [nick-hist
936 (msgs->nick-hist cached-timeline)]
937 [peers-mentioned-curr
938 (peers-mentioned cached-timeline)]
939 [peers-mentioned-prev
940 (file->peers peers-mentioned-file)]
941 [peers-all-prev
942 (file->peers peers-all-file)]
943 [peers-mentioned
944 (peers-merge peers-mentioned-prev
945 peers-mentioned-curr)]
946 [peers-all
947 (peers-update-nick-to-common
948 nick-hist
949 (peers-merge peers-mentioned
950 peers-all-prev
951 peers-cached))]
952 [peers-discovered
953 (set->list (set-subtract (make-immutable-peers peers-all)
954 (make-immutable-peers peers-all-prev)))]
955 [peers-parsed
956 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
957 ; TODO Deeper de-duping
958 (log-info "Known peers cached ~a" (length peers-cached))
959 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
960 (log-info "Known peers parsed ~a" (length peers-parsed))
961 (log-info "Known peers total: ~a" (length peers-all))
962 (log-info "Discovered ~a new peers:~n~a"
963 (length peers-discovered)
964 (pretty-format (map
965 (match-lambda
966 [(Peer n _ u c) (list n u c)])
967 peers-discovered)))
968 (update-nicks-history-files nick-hist)
969 (peers->file peers-cached
970 peers-cached-file)
971 (peers->file peers-mentioned
972 peers-mentioned-file)
973 (peers->file peers-parsed
974 peers-parsed-file)
975 (peers->file peers-all
976 peers-all-file)))
977
978 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
979 (define (read file-paths ts-min ts-max order out-format)
980 (let* ([peers
981 (paths->peers file-paths)]
982 [msgs
983 (timeline-sort (peers->timeline peers) order)]
984 [include?
985 (λ (m)
986 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
987 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
988 (timeline-print out-format (filter include? msgs))))
989
990 (: upload (-> Void))
991 (define (upload)
992 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
993 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
994 (exit 0)
995 (exit 1)))
996
997 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
998 (define (download file-paths num-workers timeout)
999 (let ([peers (paths->peers file-paths)])
1000 (define-values (_res _cpu real-ms _gc)
1001 (time-apply timeline-download (list num-workers timeout peers)))
1002 (log-info "Downloaded timelines from ~a peers in ~a seconds."
1003 (length peers)
1004 (/ real-ms 1000.0))))
1005
1006 (: dispatch (-> String Void))
1007 (define (dispatch command)
1008 (match command
1009 [(or "d" "download")
1010 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
1011 ; started noticing significant slowdowns. Reducing to 5 seems to help.
1012 (let ([num-workers 5]
1013 [timeout 10.0])
1014 (command-line
1015 #:program "tt download"
1016 #:once-each
1017 [("-j" "--jobs")
1018 njobs "Number of concurrent jobs."
1019 (set! num-workers (string->number njobs))]
1020 [("-t" "--timeout")
1021 seconds "Timeout seconds per request."
1022 (set! timeout (string->number seconds))]
1023 #:args file-paths
1024 (download file-paths num-workers timeout)))]
1025 [(or "u" "upload")
1026 (command-line
1027 #:program "tt upload" #:args () (upload))]
1028 [(or "r" "read")
1029 (let ([out-format 'multi-line]
1030 [order 'old->new]
1031 [ts-min #f]
1032 [ts-max #f])
1033 (command-line
1034 #:program "tt read"
1035 #:once-each
1036 [("-r" "--rev")
1037 "Reverse displayed timeline order."
1038 (set! order 'new->old)]
1039 [("-m" "--min")
1040 m "Earliest time to display (ignore anything before it)."
1041 (set! ts-min (rfc3339->epoch m))]
1042 [("-x" "--max")
1043 x "Latest time to display (ignore anything after it)."
1044 (set! ts-max (rfc3339->epoch x))]
1045 #:once-any
1046 [("-s" "--short")
1047 "Short output format"
1048 (set! out-format 'single-line)]
1049 [("-l" "--long")
1050 "Long output format"
1051 (set! out-format 'multi-line)]
1052 #:args file-paths
1053 (read file-paths ts-min ts-max order out-format)))]
1054 [(or "c" "crawl")
1055 (command-line
1056 #:program "tt crawl" #:args () (crawl))]
1057 [command
1058 (eprintf "Error: invalid command: ~v\n" command)
1059 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1060 (exit 1)]))
1061
1062 (module+ main
1063 (let ([log-level 'info])
1064 (command-line
1065 #:program
1066 "tt"
1067 #:once-each
1068 [("-d" "--debug")
1069 "Enable debug log level."
1070 (set! log-level 'debug)]
1071 #:help-labels
1072 ""
1073 "and <command> is one of"
1074 "r, read : Read the timeline (offline operation)."
1075 "d, download : Download the timeline."
1076 ; TODO Add path dynamically
1077 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
1078 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
1079 ""
1080 #:args (command . args)
1081 (define log-writer (log-writer-start log-level))
1082 (current-command-line-arguments (list->vector args))
1083 (set-user-agent-str (build-path tt-home-dir "user.txt"))
1084 ; TODO dispatch should return status with which we should exit after cleanups
1085 (dispatch command)
1086 (log-writer-stop log-writer))))
This page took 0.156099 seconds and 4 git commands to generate.