Check ETag to prevent redundant downloads
[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/http-client
8 net/uri-codec
9 net/url-string
10 net/url-structs)
11
12 (require (prefix-in info: "info.rkt"))
13
14 (module+ test
15 (require rackunit))
16
17 (define-type Url
18 net/url-structs:url)
19
20 (define-type Out-Format
21 (U 'single-line
22 'multi-line))
23
24 (define-type Timeline-Order
25 (U 'old->new
26 'new->old))
27
28 (struct Msg
29 ([ts-epoch : Integer]
30 [ts-orig : String]
31 [nick : (Option String)]
32 [uri : Url]
33 [text : String]
34 [mentions : (Listof Peer)]))
35
36 (struct Peer
37 ([nick : (Option String)]
38 [uri : Url])
39 #:transparent)
40
41 (: tt-home-dir Path-String)
42 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
43
44 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
45 (define (concurrent-filter-map num-workers f xs)
46 ; TODO preserve order of elements OR communicate that reorder is expected
47 ; TODO switch from mailboxes to channels
48 (define (make-worker id f)
49 (define parent (current-thread))
50 (λ ()
51 (define self : Thread (current-thread))
52 (: work (∀ (α) (-> α)))
53 (define (work)
54 (thread-send parent (cons 'next self))
55 (match (thread-receive)
56 ['done (thread-send parent (cons 'exit id))]
57 [(cons 'unit x) (begin
58 (define y (f x))
59 (when y (thread-send parent (cons 'result y)))
60 (work))]))
61 (work)))
62 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
63 (define (dispatch ws xs ys)
64 (if (empty? ws)
65 ys
66 (match (thread-receive)
67 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
68 [(cons 'result y) (dispatch ws xs (cons y ys))]
69 [(cons 'next thd) (match xs
70 ['() (begin
71 (thread-send thd 'done)
72 (dispatch ws xs ys))]
73 [(cons x xs) (begin
74 (thread-send thd (cons 'unit x))
75 (dispatch ws xs ys))])])))
76 (define workers (range num-workers))
77 (define threads (map (λ (id) (thread (make-worker id f))) workers))
78 (define results (dispatch workers xs '()))
79 (for-each thread-wait threads)
80 results)
81
82 (module+ test
83 (let* ([f (λ (x) (if (even? x) x #f))]
84 [xs (range 11)]
85 [actual (sort (concurrent-filter-map 10 f xs) <)]
86 [expected (sort ( filter-map f xs) <)])
87 (check-equal? actual expected "concurrent-filter-map")))
88
89 (: msg-print (-> Out-Format Integer Msg Void))
90 (define msg-print
91 (let* ([colors (vector 36 33)]
92 [n (vector-length colors)])
93 (λ (out-format color-i msg)
94 (let ([color (vector-ref colors (modulo color-i n))]
95 [nick (Msg-nick msg)]
96 [uri (url->string (Msg-uri msg))]
97 [text (Msg-text msg)]
98 [mentions (Msg-mentions msg)])
99 (match out-format
100 ['single-line
101 (let ([nick (if nick nick uri)])
102 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
103 (parameterize
104 ([date-display-format 'iso-8601])
105 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
106 nick color text))]
107 ['multi-line
108 (let ([nick (if nick (string-append nick " ") "")])
109 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
110 (parameterize
111 ([date-display-format 'rfc2822])
112 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
113 (Msg-ts-orig msg)
114 nick uri color text))])))))
115
116 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
117 (define rfc3339->epoch
118 (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}))?$")])
119 (λ (ts)
120 (match (regexp-match re ts)
121 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
122 (let*
123 ([tz-offset
124 (match* (tz-whole tz-sign tz-HH tz-MM)
125 [("Z" #f #f #f)
126 0]
127 [(_ (or "-" "+") (? identity h) (? identity m))
128 (let ([h (string->number h)]
129 [m (string->number m)]
130 ; Reverse to get back to UTC:
131 [op (match tz-sign ["+" -] ["-" +])])
132 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
133 [(a b c d)
134 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
135 0])]
136 [ts-orig ts]
137 [local-time? #f]
138 [ts-epoch (find-seconds (if SS (string->number SS) 0)
139 (string->number MM)
140 (string->number HH)
141 (string->number dd)
142 (string->number mm)
143 (string->number yyyy)
144 local-time?)])
145 (+ ts-epoch tz-offset))]
146 [_
147 (log-error "Invalid timestamp: ~v" ts)
148 #f]))))
149
150 (: str->msg (-> (Option String) Url String (Option Msg)))
151 (define str->msg
152 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
153 (λ (nick uri str)
154 (with-handlers*
155 ([exn:fail?
156 (λ (e)
157 (log-error
158 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
159 str nick (url->string uri) e)
160 #f)])
161 (match (regexp-match re str)
162 [(list _wholething ts-orig text)
163 (let ([ts-epoch (rfc3339->epoch ts-orig)])
164 (if ts-epoch
165 (let ([mentions
166 (filter-map
167 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
168 [(list _wholething nick-uri)
169 (str->peer nick-uri)]))
170 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
171 (Msg ts-epoch ts-orig nick uri text mentions))
172 (begin
173 (log-error
174 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
175 str nick (url->string uri))
176 #f)))]
177 [_
178 (log-debug "Non-msg line from nick:~v, line:~a" nick str)
179 #f])))))
180
181 (module+ test
182 ; TODO Test for when missing-nick case
183 (let* ([tzs (for*/list ([d '("-" "+")]
184 [h '("5" "05")]
185 [m '("00" ":00" "57" ":57")])
186 (string-append d h m))]
187 [tzs (list* "" "Z" tzs)])
188 (for* ([n '("fake-nick")]
189 [u '("fake-uri")]
190 [s '("" ":10")]
191 [f '("" ".1337")]
192 [z tzs]
193 [sep (list "\t" " ")]
194 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
195 (let* ([ts (string-append "2020-11-18T22:22"
196 (if (non-empty-string? s) s ":00")
197 z)]
198 [m (str->msg n u (string-append ts sep txt))])
199 (check-not-false m)
200 (check-equal? (Msg-nick m) n)
201 (check-equal? (Msg-uri m) u)
202 (check-equal? (Msg-text m) txt)
203 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
204 )))
205
206 (let* ([ts "2020-11-18T22:22:09-0500"]
207 [tab " "]
208 [text "Lorem ipsum"]
209 [nick "foo"]
210 [uri "bar"]
211 [actual (str->msg nick uri (string-append ts tab text))]
212 [expected (Msg 1605756129 ts nick uri text)])
213 (check-equal?
214 (Msg-ts-epoch actual)
215 (Msg-ts-epoch expected)
216 "str->msg ts-epoch")
217 (check-equal?
218 (Msg-ts-orig actual)
219 (Msg-ts-orig expected)
220 "str->msg ts-orig")
221 (check-equal?
222 (Msg-nick actual)
223 (Msg-nick expected)
224 "str->msg nick")
225 (check-equal?
226 (Msg-uri actual)
227 (Msg-uri expected)
228 "str->msg uri")
229 (check-equal?
230 (Msg-text actual)
231 (Msg-text expected)
232 "str->msg text")))
233
234 (: str->lines (-> String (Listof String)))
235 (define (str->lines str)
236 (string-split str (regexp "[\r\n]+")))
237
238 (module+ test
239 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
240
241 (: str->msgs (-> (Option String) Url String (Listof Msg)))
242 (define (str->msgs nick uri str)
243 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
244
245 (: cache-dir Path-String)
246 (define cache-dir (build-path tt-home-dir "cache"))
247
248 (define cache-object-dir (build-path cache-dir "objects"))
249
250 (: url->cache-file-path-v1 (-> Url Path-String))
251 (define (url->cache-file-path-v1 uri)
252 (define (hash-sha1 str) : (-> String String)
253 (define in (open-input-string str))
254 (define digest (sha1 in))
255 (close-input-port in)
256 digest)
257 (build-path cache-object-dir (hash-sha1 (url->string uri))))
258
259 (: url->cache-file-path-v2 (-> Url Path-String))
260 (define (url->cache-file-path-v2 uri)
261 (build-path cache-object-dir (uri-encode (url->string uri))))
262
263 (define url->cache-object-path url->cache-file-path-v2)
264
265 (define (url->cache-etag-path uri)
266 (build-path cache-dir "etags" (uri-encode (url->string uri))))
267
268 (define (url->cache-lmod-path uri)
269 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
270
271 ; TODO Return Option
272 (: uri-read-cached (-> Url String))
273 (define (uri-read-cached uri)
274 (define path-v1 (url->cache-file-path-v1 uri))
275 (define path-v2 (url->cache-file-path-v2 uri))
276 (when (file-exists? path-v1)
277 (rename-file-or-directory path-v1 path-v2 #t))
278 (if (file-exists? path-v2)
279 (file->string path-v2)
280 (begin
281 (log-warning "Cache file not found for URI: ~a" (url->string uri))
282 "")))
283
284 (: str->peer (String (Option Peer)))
285 (define (str->peer str)
286 (log-debug "Parsing peer string: ~v" str)
287 (with-handlers*
288 ([exn:fail?
289 (λ (e)
290 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
291 #f)])
292 (match (string-split str)
293 [(list u) (Peer #f (string->url u))]
294 [(list n u) (Peer n (string->url u))]
295 [_
296 (log-error "Invalid peer string: ~v" str)
297 #f])))
298
299
300 (: filter-comments (-> (Listof String) (Listof String)))
301 (define (filter-comments lines)
302 (filter-not (λ (line) (string-prefix? line "#")) lines))
303
304 (: str->peers (-> String (Listof Peer)))
305 (define (str->peers str)
306 (filter-map str->peer (filter-comments (str->lines str))))
307
308 (: file->peers (-> Path-String (Listof Peer)))
309 (define (file->peers file-path)
310 (if (file-exists? file-path)
311 (str->peers (file->string file-path))
312 (begin
313 (log-error "File does not exist: ~v" (path->string file-path))
314 '())))
315
316 (: user-agent String)
317 (define user-agent
318 (let*
319 ([prog-name "tt"]
320 [prog-version (info:#%info-lookup 'version)]
321 [prog-uri "https://github.com/xandkar/tt"]
322 [user-peer-file (build-path tt-home-dir "me")]
323 [user
324 (if (file-exists? user-peer-file)
325 (match (first (file->peers user-peer-file))
326 [(Peer #f u) (format "+~a" (url->string u) )]
327 [(Peer n u) (format "+~a; @~a" (url->string u) n)])
328 (format "+~a" prog-uri))])
329 (format "~a/~a (~a)" prog-name prog-version user)))
330
331 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
332 (define (header-get headers name)
333 (match (filter-map (curry extract-field name) headers)
334 [(list val) val]
335 [_ #f]))
336
337 (: uri-download (-> Url Void))
338 (define (uri-download u)
339 (define cached-object-path (url->cache-object-path u))
340 (define cached-etag-path (url->cache-etag-path u))
341 (define cached-lmod-path (url->cache-lmod-path u))
342 (log-debug "uri-download ~v into ~v" u cached-object-path)
343 (match* ((url-scheme u) (url-host u) (url-port u))
344 [(s h p)
345 #:when (and s h)
346 (define ssl? (string=? s "https"))
347 (define-values (status-line headers body-input)
348 ; TODO Timeout. Currently hangs on slow connections.
349 (http-sendrecv
350 h
351 (url->string (struct-copy url u [scheme #f] [host #f]))
352 #:ssl? ssl?
353 #:port (cond [p p] [ssl? 443] [else 80])
354 #:headers (list (format "User-Agent: ~a" user-agent))))
355 (log-debug "headers: ~v" headers)
356 (log-debug "status-line: ~v" status-line)
357 (define status
358 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
359 (log-debug "status: ~v" status)
360 ; TODO Handle redirects
361 (match status
362 [200
363 (let ([etag (header-get headers #"ETag")]
364 [lmod (header-get headers #"Last-Modified")])
365 (if (and etag
366 (file-exists? cached-etag-path)
367 (bytes=? etag (file->bytes cached-etag-path)))
368 (log-info "ETags match, skipping the rest of ~v" (url->string u))
369 (begin
370 (log-info
371 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
372 (url->string u) etag lmod)
373 (make-parent-directory* cached-object-path)
374 (make-parent-directory* cached-etag-path)
375 (make-parent-directory* cached-lmod-path)
376 (call-with-output-file cached-object-path
377 (curry copy-port body-input)
378 #:exists 'replace)
379 (when etag
380 (display-to-file etag cached-etag-path #:exists 'replace))
381 (when lmod
382 (display-to-file etag cached-lmod-path #:exists 'replace))))
383 (close-input-port body-input))]
384 [_
385 (raise status)])]
386 [(_ _ _)
387 (log-error "Invalid URI: ~v" u)]))
388
389 (: timeline-print (-> Out-Format (Listof Msg) Void))
390 (define (timeline-print out-format timeline)
391 (void (foldl (match-lambda**
392 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
393 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
394 (msg-print out-format i m)
395 (cons nick i))])
396 (cons "" 0)
397 timeline)))
398
399 (: peer->msgs (-> Peer (Listof Msg)))
400 (define (peer->msgs f)
401 (match-define (Peer nick uri) f)
402 (log-info "Reading peer nick:~v uri:~v" nick (url->string uri))
403 (str->msgs nick uri (uri-read-cached uri)))
404
405 (: peer-download (-> Peer Void))
406 (define (peer-download f)
407 (match-define (Peer nick uri) f)
408 (define u (url->string uri))
409 (log-info "Downloading peer uri:~a" u)
410 (with-handlers
411 ([exn:fail?
412 (λ (e)
413 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
414 #f)]
415 [integer?
416 (λ (status)
417 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
418 #f)])
419 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
420 (time-apply uri-download (list uri)))
421 (log-info "Peer downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
422
423 (: timeline-download (-> Integer (Listof Peer) Void))
424 (define (timeline-download num-workers peers)
425 ; TODO No need for map - can just iter
426 (void (concurrent-filter-map num-workers peer-download peers)))
427
428 ; TODO timeline contract : time-sorted list of messages
429 (: timeline-read (-> Timeline-Order (Listof Peer) (Listof Msg)))
430 (define (timeline-read order peers)
431 (define cmp (match order
432 ['old->new <]
433 ['new->old >]))
434 (sort (append* (filter-map peer->msgs peers))
435 (λ (a b) (cmp (Msg-ts-epoch a) (Msg-ts-epoch b)))))
436
437 (: paths->peers (-> (Listof String) (Listof Peer)))
438 (define (paths->peers paths)
439 (let* ([paths (match paths
440 ['()
441 (let ([peer-refs-file (build-path tt-home-dir "peers")])
442 (log-debug
443 "No peer ref file paths provided, defaulting to ~v"
444 (path->string peer-refs-file))
445 (list peer-refs-file))]
446 [paths
447 (log-debug "Peer ref file paths provided: ~v" paths)
448 (map string->path paths)])]
449 [peers (append* (map file->peers paths))])
450 (log-info "Read-in ~a peers." (length peers))
451 peers))
452
453 (: log-writer-stop (-> Thread Void))
454 (define (log-writer-stop log-writer)
455 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
456 (thread-wait log-writer))
457
458 (: log-writer-start (-> Log-Level Thread))
459 (define (log-writer-start level)
460 (let* ([logger
461 (make-logger #f #f level #f)]
462 [log-receiver
463 (make-log-receiver logger level)]
464 [log-writer
465 (thread
466 (λ ()
467 (parameterize
468 ([date-display-format 'iso-8601])
469 (let loop ()
470 (match-define (vector level msg _ topic) (sync log-receiver))
471 (unless (equal? topic 'stop)
472 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
473 (loop))))))])
474 (current-logger logger)
475 log-writer))
476
477 (module+ main
478 (let ([log-level 'info])
479 (command-line
480 #:program
481 "tt"
482 #:once-each
483 [("-d" "--debug")
484 "Enable debug log level."
485 (set! log-level 'debug)]
486 #:help-labels
487 ""
488 "and <command> is one of"
489 "r, read i : Read the timeline."
490 "d, download : Download the timeline."
491 ; TODO Add path dynamically
492 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
493 ""
494 #:args (command . args)
495 (define log-writer (log-writer-start log-level))
496 (current-command-line-arguments (list->vector args))
497 (match command
498 [(or "d" "download")
499 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
500 ; started noticing significant slowdowns. Reducing to 5 seems to help.
501 (let ([num-workers 5])
502 (command-line
503 #:program
504 "tt download"
505 #:once-each
506 [("-j" "--jobs")
507 njobs "Number of concurrent jobs."
508 (set! num-workers (string->number njobs))]
509 #:args file-paths
510 (define-values (_res _cpu real-ms _gc)
511 (time-apply timeline-download (list num-workers (paths->peers file-paths))))
512 (log-info "Timeline downloaded in ~a seconds." (/ real-ms 1000.0))))]
513 [(or "u" "upload")
514 (command-line
515 #:program
516 "tt upload"
517 #:args ()
518 (if (system (path->string (build-path tt-home-dir "upload")))
519 (exit 0)
520 (exit 1)))]
521 [(or "r" "read")
522 (let ([out-format 'multi-line]
523 [order 'old->new])
524 (command-line
525 #:program
526 "tt read"
527 #:once-each
528 [("-r" "--rev")
529 "Reverse displayed timeline order."
530 (set! order 'new->old)]
531 #:once-any
532 [("-s" "--short")
533 "Short output format"
534 (set! out-format 'single-line)]
535 [("-l" "--long")
536 "Long output format"
537 (set! out-format 'multi-line)]
538 #:args file-paths
539 (timeline-print out-format (timeline-read order (paths->peers file-paths)))))])
540 (log-writer-stop log-writer))))
This page took 0.102095 seconds and 4 git commands to generate.