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