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