Normalize msg provenance field(s) to just [from : Peer]
[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 Msg
31 ([ts-epoch : Integer]
32 [ts-orig : String]
33 [from : Peer]
34 [text : String]
35 [mentions : (Listof Peer)]))
36
37 (struct Peer
38 ([nick : (Option String)]
39 [uri : Url]
40 [uri-str : String]
41 [comment : (Option String)])
42 #:transparent)
43
44 (struct Resp
45 ([status-line : String]
46 [headers : (Listof Bytes)]
47 [body-input : Input-Port])
48 #:transparent)
49
50 (: peers-equal? (-> Peer Peer Boolean))
51 (define (peers-equal? p1 p2)
52 (equal? (Peer-uri-str p1)
53 (Peer-uri-str p2)))
54
55 (: peer-hash (-> Peer Fixnum))
56 (define (peer-hash p)
57 (equal-hash-code (Peer-uri-str p)))
58
59 (define-custom-set-types peers
60 #:elem? Peer?
61 peers-equal?
62 peer-hash)
63 ; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
64 ; the following contract violations:
65 ;
66 ; custom-elem-contents: contract violation
67 ; expected: custom-elem?
68 ; given: #f
69 ; context...:
70 ; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
71 ; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
72 ; /usr/share/racket/collects/racket/cmdline.rkt:191:51
73 ; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
74 ;
75 ; TODO Investigate why and make a minimal reproducible test case.
76
77 (: tt-home-dir Path-String)
78 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
79
80 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
81 (define (concurrent-filter-map num-workers f xs)
82 ; TODO preserve order of elements OR communicate that reorder is expected
83 ; TODO switch from mailboxes to channels
84 (define (make-worker id f)
85 (define parent (current-thread))
86 (λ ()
87 (define self : Thread (current-thread))
88 (: work (∀ (α) (-> α)))
89 (define (work)
90 (thread-send parent (cons 'next self))
91 (match (thread-receive)
92 ['done (thread-send parent (cons 'exit id))]
93 [(cons 'unit x) (begin
94 (define y (f x))
95 (when y (thread-send parent (cons 'result y)))
96 (work))]))
97 (work)))
98 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
99 (define (dispatch ws xs ys)
100 (if (empty? ws)
101 ys
102 (match (thread-receive)
103 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
104 [(cons 'result y) (dispatch ws xs (cons y ys))]
105 [(cons 'next thd) (match xs
106 ['() (begin
107 (thread-send thd 'done)
108 (dispatch ws xs ys))]
109 [(cons x xs) (begin
110 (thread-send thd (cons 'unit x))
111 (dispatch ws xs ys))])])))
112 (define workers (range num-workers))
113 (define threads (map (λ (id) (thread (make-worker id f))) workers))
114 (define results (dispatch workers xs '()))
115 (for-each thread-wait threads)
116 results)
117
118 (module+ test
119 (let* ([f (λ (x) (if (even? x) x #f))]
120 [xs (range 11)]
121 [actual (sort (concurrent-filter-map 10 f xs) <)]
122 [expected (sort ( filter-map f xs) <)])
123 (check-equal? actual expected "concurrent-filter-map")))
124
125 (: msg-print (-> Out-Format Integer Msg Void))
126 (define msg-print
127 (let* ([colors (vector 36 33)]
128 [n (vector-length colors)])
129 (λ (out-format color-i msg)
130 (let ([color (vector-ref colors (modulo color-i n))]
131 [nick (Peer-nick (Msg-from msg))]
132 [uri (Peer-uri-str (Msg-from msg))]
133 [text (Msg-text msg)])
134 (match out-format
135 ['single-line
136 (let ([nick (if nick nick uri)])
137 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
138 (parameterize
139 ([date-display-format 'iso-8601])
140 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
141 nick color text))]
142 ['multi-line
143 (let ([nick (if nick (string-append nick " ") "")])
144 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
145 (parameterize
146 ([date-display-format 'rfc2822])
147 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
148 (Msg-ts-orig msg)
149 nick uri color text))])))))
150
151 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
152 (define rfc3339->epoch
153 (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}))?$")])
154 (λ (ts)
155 (match (regexp-match re ts)
156 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
157 (let*
158 ([tz-offset
159 (match* (tz-whole tz-sign tz-HH tz-MM)
160 [("Z" #f #f #f)
161 0]
162 [(_ (or "-" "+") (? identity h) (? identity m))
163 (let ([h (string->number h)]
164 [m (string->number m)]
165 ; Reverse to get back to UTC:
166 [op (match tz-sign ["+" -] ["-" +])])
167 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
168 [(a b c d)
169 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
170 0])]
171 [ts-orig ts]
172 [local-time? #f]
173 [ts-epoch (find-seconds (if SS (string->number SS) 0)
174 (string->number MM)
175 (string->number HH)
176 (string->number dd)
177 (string->number mm)
178 (string->number yyyy)
179 local-time?)])
180 (+ ts-epoch tz-offset))]
181 [_
182 (log-debug "Invalid timestamp: ~v" ts)
183 #f]))))
184
185 (: str->msg (-> Peer String (Option Msg)))
186 (define str->msg
187 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
188 (λ (from str)
189 (define from-str (peer->str from))
190 (define str-head (substring str 0 (min 100 (string-length str))))
191 (with-handlers*
192 ([exn:fail?
193 (λ (e)
194 (log-debug
195 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
196 str-head from-str e)
197 #f)])
198 (match (regexp-match re str)
199 [(list _wholething ts-orig text)
200 (let ([ts-epoch (rfc3339->epoch ts-orig)])
201 (if ts-epoch
202 (let ([mentions
203 (filter-map
204 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
205 [(list _wholething nick-uri)
206 (str->peer nick-uri)]))
207 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
208 (Msg ts-epoch ts-orig from text mentions))
209 (begin
210 (log-debug
211 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
212 from-str str-head)
213 #f)))]
214 [_
215 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
216 #f])))))
217
218 (module+ test
219 ; TODO Test for when missing-nick case
220 (let* ([tzs (for*/list ([d '("-" "+")]
221 [h '("5" "05")]
222 [m '("00" ":00" "57" ":57")])
223 (string-append d h m))]
224 [tzs (list* "" "Z" tzs)])
225 (for* ([n '("fake-nick")]
226 [u '("http://fake-uri")]
227 [p (list (Peer n (string->url u) u ""))]
228 [s '("" ":10")]
229 [f '("" ".1337")]
230 [z tzs]
231 [sep (list "\t" " ")]
232 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
233 (let* ([ts (string-append "2020-11-18T22:22"
234 (if (non-empty-string? s) s ":00")
235 z)]
236 [m (str->msg p (string-append ts sep txt))])
237 (check-not-false m)
238 (check-equal? (Msg-from m) p)
239 (check-equal? (Msg-text m) txt)
240 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
241 )))
242
243 (let* ([ts "2020-11-18T22:22:09-0500"]
244 [tab " "]
245 [text "Lorem ipsum"]
246 [nick "foo"]
247 [uri "http://bar/"]
248 [peer (Peer nick (string->url uri) uri "")]
249 [actual (str->msg peer (string-append ts tab text))]
250 [expected (Msg 1605756129 ts peer text '())])
251 (check-equal?
252 (Msg-ts-epoch actual)
253 (Msg-ts-epoch expected)
254 "str->msg ts-epoch")
255 (check-equal?
256 (Msg-ts-orig actual)
257 (Msg-ts-orig expected)
258 "str->msg ts-orig")
259 (check-equal?
260 (Peer-nick (Msg-from actual))
261 (Peer-nick (Msg-from expected))
262 "str->msg nick")
263 (check-equal?
264 (Peer-uri (Msg-from actual))
265 (Peer-uri (Msg-from expected))
266 "str->msg uri")
267 (check-equal?
268 (Peer-uri-str (Msg-from actual))
269 (Peer-uri-str (Msg-from expected))
270 "str->msg uri-str")
271 (check-equal?
272 (Msg-text actual)
273 (Msg-text expected)
274 "str->msg text")))
275
276 (: str->lines (-> String (Listof String)))
277 (define (str->lines str)
278 (string-split str (regexp "[\r\n]+")))
279
280 (module+ test
281 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
282
283 (: str->msgs (-> Peer String (Listof Msg)))
284 (define (str->msgs peer str)
285 (filter-map (λ (line) (str->msg peer line))
286 (filter-comments (str->lines str))))
287
288 (: cache-dir Path-String)
289 (define cache-dir (build-path tt-home-dir "cache"))
290
291 (define cache-object-dir (build-path cache-dir "objects"))
292
293 (: url->cache-file-path-v1 (-> Url Path-String))
294 (define (url->cache-file-path-v1 uri)
295 (define (hash-sha1 str) : (-> String String)
296 (define in (open-input-string str))
297 (define digest (sha1 in))
298 (close-input-port in)
299 digest)
300 (build-path cache-object-dir (hash-sha1 (url->string uri))))
301
302 (: url->cache-file-path-v2 (-> Url Path-String))
303 (define (url->cache-file-path-v2 uri)
304 (build-path cache-object-dir (uri-encode (url->string uri))))
305
306 (define url->cache-object-path
307 url->cache-file-path-v2)
308
309 (define (url->cache-etag-path uri)
310 (build-path cache-dir "etags" (uri-encode (url->string uri))))
311
312 (define (url->cache-lmod-path uri)
313 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
314
315 (: uri-read-cached (-> Url (Option String)))
316 (define (uri-read-cached uri)
317 (define path-v1 (url->cache-file-path-v1 uri))
318 (define path-v2 (url->cache-file-path-v2 uri))
319 (when (file-exists? path-v1)
320 (rename-file-or-directory path-v1 path-v2 #t))
321 (if (file-exists? path-v2)
322 (file->string path-v2)
323 (begin
324 (log-debug "Cache file not found for URI: ~a" (url->string uri))
325 #f)))
326
327 (: str->url (-> String (Option String)))
328 (define (str->url s)
329 (with-handlers*
330 ([exn:fail? (λ (e) #f)])
331 (string->url s)))
332
333 (: peer->str (-> Peer String))
334 (define (peer->str peer)
335 (match-define (Peer n _ u c) peer)
336 (format "~a~a~a"
337 (if n (format "~a " n) "")
338 u
339 (if c (format " # ~a" c) "")))
340
341 (: str->peer (-> String (Option Peer)))
342 (define (str->peer str)
343 (log-debug "Parsing peer string: ~v" str)
344 (match
345 (regexp-match
346 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
347 str)
348 [(list _wholething
349 _nick-with-space
350 nick
351 url
352 _comment-with-hash
353 comment)
354 (match (str->url url)
355 [#f
356 (log-error "Invalid URI in peer string: ~v" str)
357 #f]
358 [url
359 (Peer nick url (url->string url) comment)])]
360 [_
361 (log-debug "Invalid peer string: ~v" str)
362 #f]))
363
364 (module+ test
365 (check-equal?
366 (str->peer "foo http://bar/file.txt # some rando")
367 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
368 (check-equal?
369 (str->peer "http://bar/file.txt # some rando")
370 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
371 (check-equal?
372 (str->peer "http://bar/file.txt #")
373 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
374 (check-equal?
375 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
376 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
377 (check-equal?
378 (str->peer "http://bar/file.txt")
379 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
380 (check-equal?
381 (str->peer "foo http://bar/file.txt")
382 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
383 (check-equal?
384 (str->peer "foo bar # baz")
385 #f)
386 (check-equal?
387 (str->peer "foo bar://baz # quux")
388 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
389 (check-equal?
390 (str->peer "foo bar//baz # quux")
391 #f))
392
393 (: filter-comments (-> (Listof String) (Listof String)))
394 (define (filter-comments lines)
395 (filter-not (λ (line) (string-prefix? line "#")) lines))
396
397 (: str->peers (-> String (Setof Peer)))
398 (define (str->peers str)
399 (make-immutable-peers (filter-map str->peer (filter-comments (str->lines str)))))
400
401 (: peers->file (-> (Setof Peers) Path-String Void))
402 (define (peers->file peers path)
403 (display-lines-to-file
404 (map peer->str
405 (sort (set->list peers)
406 (match-lambda**
407 [((Peer n1 _ _ _) (Peer n2 _ _ _))
408 (string<? (if n1 n1 "")
409 (if n2 n2 ""))])))
410 path
411 #:exists 'replace))
412
413 (: file->peers (-> Path-String (Setof Peer)))
414 (define (file->peers file-path)
415 (if (file-exists? file-path)
416 (str->peers (file->string file-path))
417 (begin
418 (log-warning "File does not exist: ~v" (path->string file-path))
419 (make-immutable-peers))))
420
421 (define re-rfc2822
422 #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")
423
424 (: b->n (-> Bytes (Option Number)))
425 (define (b->n b)
426 (string->number (bytes->string/utf-8 b)))
427
428 (: mon->num (-> Bytes Natural))
429 (define/match (mon->num mon)
430 [(#"Jan") 1]
431 [(#"Feb") 2]
432 [(#"Mar") 3]
433 [(#"Apr") 4]
434 [(#"May") 5]
435 [(#"Jun") 6]
436 [(#"Jul") 7]
437 [(#"Aug") 8]
438 [(#"Sep") 9]
439 [(#"Oct") 10]
440 [(#"Nov") 11]
441 [(#"Dec") 12])
442
443 (: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
444 (define (rfc2822->epoch timestamp)
445 (match (regexp-match re-rfc2822 timestamp)
446 [(list _ _ dd mo yyyy HH MM SS)
447 #:when (and dd mo yyyy HH MM SS)
448 (find-seconds (b->n SS)
449 (b->n MM)
450 (b->n HH)
451 (b->n dd)
452 (mon->num mo)
453 (b->n yyyy)
454 #f)]
455 [_
456 #f]))
457
458 (: user-agent String)
459 (define user-agent
460 (let*
461 ([prog-name "tt"]
462 [prog-version (info:#%info-lookup 'version)]
463 [prog-uri "https://github.com/xandkar/tt"]
464 [user-peer-file (build-path tt-home-dir "me")]
465 [user
466 (if (file-exists? user-peer-file)
467 (match (set-first (file->peers user-peer-file))
468 [(Peer #f _ u _) (format "+~a" u )]
469 [(Peer n _ u _) (format "+~a; @~a" u n)])
470 (format "+~a" prog-uri))])
471 (format "~a/~a (~a)" prog-name prog-version user)))
472
473 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
474 (define (header-get headers name)
475 (match (filter-map (curry extract-field name) headers)
476 [(list val) val]
477 [_ #f]))
478
479 (: uri-download-from-port
480 (-> Url (Listof (U Bytes String)) Input-Port
481 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
482 (define (uri-download-from-port u headers body-input)
483 (define u-str (url->string u))
484 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
485 (define cached-object-path (url->cache-object-path u))
486 (define cached-etag-path (url->cache-etag-path u))
487 (define cached-lmod-path (url->cache-lmod-path u))
488 (define etag (header-get headers #"ETag"))
489 (define lmod (header-get headers #"Last-Modified"))
490 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
491 (define lmod-prev (if (file-exists? cached-lmod-path)
492 (rfc2822->epoch (file->bytes cached-lmod-path))
493 #f))
494 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
495 (define cached?
496 (or (and etag
497 (file-exists? cached-etag-path)
498 (bytes=? etag (file->bytes cached-etag-path))
499 (begin
500 (log-debug "ETags match, skipping the rest of ~v" u-str)
501 #t))
502 (and lmod-curr
503 lmod-prev
504 (<= lmod-curr lmod-prev)
505 (begin
506 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
507 #t))))
508 (if (not cached?)
509 (begin
510 (log-debug
511 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
512 u-str etag lmod)
513 (make-parent-directory* cached-object-path)
514 (make-parent-directory* cached-etag-path)
515 (make-parent-directory* cached-lmod-path)
516 (call-with-output-file cached-object-path
517 (curry copy-port body-input)
518 #:exists 'replace)
519 (when etag
520 (display-to-file etag cached-etag-path #:exists 'replace))
521 (when lmod
522 (display-to-file lmod cached-lmod-path #:exists 'replace))
523 'downloaded-new)
524 'skipped-cached))
525
526 (: uri-download
527 (-> Positive-Float Url
528 (Result (U 'skipped-cached 'downloaded-new)
529 Any))) ; TODO Maybe more-precise error type?
530 (define (uri-download timeout u)
531 (define u-str (url->string u))
532 (define timeout-chan (make-channel))
533 (define result-chan (make-channel))
534 (define timeout-thread
535 (thread (λ ()
536 ; Doing this instead of sync/timeout to distinguish error values,
537 ; rather than just have #f to work with.
538 (sleep timeout)
539 (channel-put timeout-chan '(error . timeout)))))
540 (define result-thread
541 (thread (λ ()
542 ; XXX We timeout getting a response, but body download could
543 ; also take a long time and we might want to time that out as
544 ; well, but then we may end-up with partially downloaded
545 ; objects. But that could happen anyway if the server drops the
546 ; connection for whatever reason.
547 ;
548 ; Maybe that is OK once we start treating the
549 ; downloaded object as an addition to the stored set of
550 ; messages, rather than the final set of messages.
551
552 ; TODO message db
553 ; - 1st try can just be an in-memory set that gets written-to
554 ; and read-from disk as a whole.
555 (define result
556 (with-handlers
557 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
558 ([exn:fail:network?
559 (λ (e) `(error . (net-error . ,e)))]
560 [exn?
561 (λ (e) `(error . (other . ,e)))])
562 (define-values (status-line headers body-input)
563 (http-sendrecv/url
564 u
565 #:headers (list (format "User-Agent: ~a" user-agent))))
566 `(ok . ,(Resp status-line headers body-input))))
567 (channel-put result-chan result))))
568 (define result
569 (sync timeout-chan
570 result-chan))
571 (kill-thread result-thread)
572 (kill-thread timeout-thread)
573 (match result
574 [(cons 'error _)
575 result]
576 [(cons 'ok (Resp status-line headers body-input))
577 (log-debug "headers: ~v" headers)
578 (log-debug "status-line: ~v" status-line)
579 (define status
580 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
581 (log-debug "status: ~v" status)
582 ; TODO Handle redirects. Should be within same timeout as req and body.
583 (let ([result
584 (match status
585 [200
586 `(ok . ,(uri-download-from-port u headers body-input))]
587 [_
588 `(error . (http . ,status))])])
589 (close-input-port body-input)
590 result)]))
591
592 (: timeline-print (-> Out-Format (Listof Msg) Void))
593 (define (timeline-print out-format timeline)
594 (match timeline
595 ['()
596 (void)]
597 [(cons first-msg _)
598 (void (foldl (match-lambda**
599 [((and m (Msg _ _ from _ _)) (cons prev-from i))
600 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
601 (msg-print out-format i m)
602 (cons from i))])
603 (cons (Msg-from first-msg) 0)
604 timeline))]))
605
606 (: peer->msgs (-> Peer (Listof Msg)))
607 (define (peer->msgs peer)
608 (match-define (Peer nick uri uri-str _) peer)
609 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
610 (define msgs-data (uri-read-cached uri))
611 ; TODO Expire cache
612 (if msgs-data
613 (str->msgs peer msgs-data)
614 '()))
615
616 (: peer-download
617 (-> Positive-Float Peer
618 (Result (U 'skipped-cached 'downloaded-new)
619 Any)))
620 (define (peer-download timeout peer)
621 (match-define (Peer nick uri u _) peer)
622 (log-info "Download BEGIN URL:~a" u)
623 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
624 (time-apply uri-download (list timeout uri)))
625 (define result (car results))
626 (log-info "Download END in ~a seconds, URL:~a, result:~s"
627 (/ tm-real-ms 1000.0)
628 u
629 result)
630 result)
631
632 (: timeline-download (-> Integer Positive-Float (Setof Peer) Void))
633 (define (timeline-download num-workers timeout peers)
634 (define results
635 (concurrent-filter-map num-workers
636 (λ (p) (cons p (peer-download timeout p)))
637 (set->list peers)))
638 (define peers-ok
639 (filter-map (match-lambda
640 [(cons p (cons 'ok _)) p]
641 [(cons _ (cons 'error e)) #f])
642 results))
643 (define peers-err
644 (filter-map (match-lambda
645 [(cons _ (cons 'ok _))
646 #f]
647 [(cons p (cons 'error e))
648 (struct-copy Peer p [comment (format "~s" e)])])
649 results))
650 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
651 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
652
653 (: peers->timeline (-> (Listof Peer) (Listof Msg)))
654 (define (peers->timeline peers)
655 (append* (filter-map peer->msgs (set->list peers))))
656
657 (: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
658 (define (timeline-sort msgs order)
659 (define cmp (match order
660 ['old->new <]
661 ['new->old >]))
662 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
663 (Msg-ts-epoch b)))))
664
665 (: paths->peers (-> (Listof String) (Setof Peer)))
666 (define (paths->peers paths)
667 (let* ([paths (match paths
668 ['()
669 (let ([peer-refs-file (build-path tt-home-dir "peers")])
670 (log-debug
671 "No peer ref file paths provided, defaulting to ~v"
672 (path->string peer-refs-file))
673 (list peer-refs-file))]
674 [paths
675 (log-debug "Peer ref file paths provided: ~v" paths)
676 (map string->path paths)])]
677 [peers (apply set-union (map file->peers paths))])
678 (log-info "Read-in ~a peers." (set-count peers))
679 peers))
680
681 (: mentioned-peers-in-cache (-> (Setof Peer)))
682 (define (mentioned-peers-in-cache)
683 ; TODO Expire cache
684 (define msgs
685 (append* (map (λ (filename)
686 (define path (build-path cache-object-dir filename))
687 (define size (/ (file-size path) 1000000.0))
688 (log-debug "BEGIN parsing ~a MB from file: ~v"
689 size
690 (path->string path))
691 (define t0 (current-inexact-milliseconds))
692 (define m (filter-map
693 (λ (line)
694 (define url-str (uri-decode (path->string filename)))
695 (define url (string->url url-str))
696 (define from (Peer #f url url-str ""))
697 (str->msg from line))
698 (filter-comments
699 (file->lines path))))
700 (define t1 (current-inexact-milliseconds))
701 (log-debug "END parsing ~a MB in ~a seconds from file: ~v."
702 size
703 (* 0.001 (- t1 t0))
704 (path->string path))
705 (when (empty? m)
706 (log-debug "No messages found in ~a" (path->string path)))
707 m)
708 (directory-list cache-object-dir))))
709 (make-immutable-peers (append* (map Msg-mentions msgs))))
710
711 (: log-writer-stop (-> Thread Void))
712 (define (log-writer-stop log-writer)
713 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
714 (thread-wait log-writer))
715
716 (: log-writer-start (-> Log-Level Thread))
717 (define (log-writer-start level)
718 (let* ([logger
719 (make-logger #f #f level #f)]
720 [log-receiver
721 (make-log-receiver logger level)]
722 [log-writer
723 (thread
724 (λ ()
725 (parameterize
726 ([date-display-format 'iso-8601])
727 (let loop ()
728 (match-define (vector level msg _ topic) (sync log-receiver))
729 (unless (equal? topic 'stop)
730 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
731 (loop))))))])
732 (current-logger logger)
733 log-writer))
734
735 (: crawl (-> Void))
736 (define (crawl)
737 (let* ([peers-all-file
738 (build-path tt-home-dir "peers-all")]
739 [peers-mentioned-file
740 (build-path tt-home-dir "peers-mentioned")]
741 [peers-parsed-file
742 (build-path tt-home-dir "peers-parsed")]
743 [peers-mentioned-curr
744 (mentioned-peers-in-cache)]
745 [peers-mentioned-prev
746 (file->peers peers-mentioned-file)]
747 [peers-mentioned
748 (set-union peers-mentioned-prev
749 peers-mentioned-curr)]
750 [peers-all-prev
751 (file->peers peers-all-file)]
752 [peers-all
753 (set-union peers-mentioned
754 peers-all-prev)]
755 [peers-discovered
756 (set-subtract peers-all
757 peers-all-prev)]
758 [peers-parsed
759 (for/set ([p peers-all] #:when (> (length (peer->msgs p)) 0)) p)])
760 ; TODO Deeper de-duping
761 (log-info "Known peers mentioned: ~a" (set-count peers-mentioned))
762 (log-info "Known peers parsed ~a" (set-count peers-parsed))
763 (log-info "Known peers total: ~a" (set-count peers-all))
764 (log-info "Discovered ~a new peers:~n~a"
765 (set-count peers-discovered)
766 (pretty-format (map
767 (match-lambda
768 [(Peer n _ u c) (list n u c)])
769 (set->list peers-discovered))))
770 (peers->file peers-mentioned
771 peers-mentioned-file)
772 (peers->file peers-parsed
773 peers-parsed-file)
774 (peers->file peers-all
775 peers-all-file)))
776
777 (: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
778 (define (read file-paths ts-min ts-max order out-format)
779 (let* ([peers
780 (paths->peers file-paths)]
781 [msgs
782 (timeline-sort (peers->timeline peers) order)]
783 [include?
784 (λ (m)
785 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
786 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
787 (timeline-print out-format (filter include? msgs))))
788
789 (: upload (-> Void))
790 (define (upload)
791 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
792 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
793 (exit 0)
794 (exit 1)))
795
796 (: download (-> (Listof String) Positive-Integer Positive-Float Void))
797 (define (download file-paths num-workers timeout)
798 (let ([peers (paths->peers file-paths)])
799 (define-values (_res _cpu real-ms _gc)
800 (time-apply timeline-download (list num-workers timeout peers)))
801 (log-info "Downloaded timelines from ~a peers in ~a seconds."
802 (set-count peers)
803 (/ real-ms 1000.0))))
804
805 (: dispatch (-> String Void))
806 (define (dispatch command)
807 (match command
808 [(or "d" "download")
809 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
810 ; started noticing significant slowdowns. Reducing to 5 seems to help.
811 (let ([num-workers 5]
812 [timeout 10.0])
813 (command-line
814 #:program "tt download"
815 #:once-each
816 [("-j" "--jobs")
817 njobs "Number of concurrent jobs."
818 (set! num-workers (string->number njobs))]
819 [("-t" "--timeout")
820 seconds "Timeout seconds per request."
821 (set! timeout (string->number seconds))]
822 #:args file-paths
823 (download file-paths num-workers timeout)))]
824 [(or "u" "upload")
825 (command-line
826 #:program "tt upload" #:args () (upload))]
827 [(or "r" "read")
828 (let ([out-format 'multi-line]
829 [order 'old->new]
830 [ts-min #f]
831 [ts-max #f])
832 (command-line
833 #:program "tt read"
834 #:once-each
835 [("-r" "--rev")
836 "Reverse displayed timeline order."
837 (set! order 'new->old)]
838 [("-m" "--min")
839 m "Earliest time to display (ignore anything before it)."
840 (set! ts-min (rfc3339->epoch m))]
841 [("-x" "--max")
842 x "Latest time to display (ignore anything after it)."
843 (set! ts-max (rfc3339->epoch x))]
844 #:once-any
845 [("-s" "--short")
846 "Short output format"
847 (set! out-format 'single-line)]
848 [("-l" "--long")
849 "Long output format"
850 (set! out-format 'multi-line)]
851 #:args file-paths
852 (read file-paths ts-min ts-max order out-format)))]
853 [(or "c" "crawl")
854 (command-line
855 #:program "tt crawl" #:args () (crawl))]
856 [command
857 (eprintf "Error: invalid command: ~v\n" command)
858 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
859 (exit 1)]))
860
861 (module+ main
862 (let ([log-level 'info])
863 (command-line
864 #:program
865 "tt"
866 #:once-each
867 [("-d" "--debug")
868 "Enable debug log level."
869 (set! log-level 'debug)]
870 #:help-labels
871 ""
872 "and <command> is one of"
873 "r, read : Read the timeline (offline operation)."
874 "d, download : Download the timeline."
875 ; TODO Add path dynamically
876 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
877 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
878 ""
879 #:args (command . args)
880 (define log-writer (log-writer-start log-level))
881 (current-command-line-arguments (list->vector args))
882 ; TODO dispatch should return status with which we should exit after cleanups
883 (dispatch command)
884 (log-writer-stop log-writer))))
This page took 0.142641 seconds and 4 git commands to generate.