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