Check ETag to prevent redundant downloads
[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
9c464d95 7 net/http-client
edadb804 8 net/uri-codec
9c464d95
SK
9 net/url-string
10 net/url-structs)
4764ff89 11
3c9c8266
SK
12(require (prefix-in info: "info.rkt"))
13
78398948 14(module+ test
de3ff448 15 (require rackunit))
78398948 16
98529d3d
SK
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
b0ff061a 28(struct Msg
78142acb 29 ([ts-epoch : Integer]
3877a0c4 30 [ts-orig : String]
13c11724 31 [nick : (Option String)]
98529d3d 32 [uri : Url]
13c11724 33 [text : String]
b0ff061a 34 [mentions : (Listof Peer)]))
9c464d95 35
dbc26280 36(struct Peer
13c11724 37 ([nick : (Option String)]
d0a0e073
SK
38 [uri : Url])
39 #:transparent)
4764ff89 40
edadb804
SK
41(: tt-home-dir Path-String)
42(define tt-home-dir (build-path (expand-user-path "~") ".tt"))
43
9a346534 44(: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
78142acb 45(define (concurrent-filter-map num-workers f xs)
dad4504d 46 ; TODO preserve order of elements OR communicate that reorder is expected
a239a233 47 ; TODO switch from mailboxes to channels
895a32cf
SK
48 (define (make-worker id f)
49 (define parent (current-thread))
50 (λ ()
a9511f7c
SK
51 (define self : Thread (current-thread))
52 (: work (∀ (α) (-> α)))
895a32cf
SK
53 (define (work)
54 (thread-send parent (cons 'next self))
55 (match (thread-receive)
c562bea3
SK
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))]))
895a32cf 61 (work)))
a9511f7c 62 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
895a32cf
SK
63 (define (dispatch ws xs ys)
64 (if (empty? ws)
f1493e49
SK
65 ys
66 (match (thread-receive)
c562bea3
SK
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))])])))
78142acb 76 (define workers (range num-workers))
9926c9a9
SK
77 (define threads (map (λ (id) (thread (make-worker id f))) workers))
78 (define results (dispatch workers xs '()))
895a32cf
SK
79 (for-each thread-wait threads)
80 results)
81
dad4504d 82(module+ test
de3ff448
SK
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) <)])
c562bea3 87 (check-equal? actual expected "concurrent-filter-map")))
dad4504d 88
98529d3d 89(: msg-print (-> Out-Format Integer Msg Void))
3d042e75
SK
90(define msg-print
91 (let* ([colors (vector 36 33)]
92 [n (vector-length colors)])
93 (λ (out-format color-i msg)
01e4c499 94 (let ([color (vector-ref colors (modulo color-i n))]
b0ff061a
SK
95 [nick (Msg-nick msg)]
96 [uri (url->string (Msg-uri msg))]
97 [text (Msg-text msg)]
98 [mentions (Msg-mentions msg)])
3d042e75 99 (match out-format
01e4c499 100 ['single-line
13c11724
SK
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])
b0ff061a 105 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
13c11724 106 nick color text))]
01e4c499 107 ['multi-line
13c11724
SK
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])
b0ff061a
SK
112 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
113 (Msg-ts-orig msg)
13c11724 114 nick uri color text))])))))
e96264cc 115
3877a0c4
SK
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
13c11724 150(: str->msg (-> (Option String) Url String (Option Msg)))
b4689464 151(define str->msg
3877a0c4 152 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
b4689464
SK
153 (λ (nick uri str)
154 (with-handlers*
155 ([exn:fail?
156 (λ (e)
9c464d95
SK
157 (log-error
158 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
159 str nick (url->string uri) e)
b4689464
SK
160 #f)])
161 (match (regexp-match re str)
3877a0c4
SK
162 [(list _wholething ts-orig text)
163 (let ([ts-epoch (rfc3339->epoch ts-orig)])
164 (if ts-epoch
13c11724
SK
165 (let ([mentions
166 (filter-map
167 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
168 [(list _wholething nick-uri)
dbc26280 169 (str->peer nick-uri)]))
13c11724 170 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
b0ff061a 171 (Msg ts-epoch ts-orig nick uri text mentions))
3877a0c4
SK
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)))]
b4689464 177 [_
13c11724 178 (log-debug "Non-msg line from nick:~v, line:~a" nick str)
b4689464 179 #f])))))
88d50b3e 180
63afa259 181(module+ test
13c11724 182 ; TODO Test for when missing-nick case
b4689464
SK
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)
b0ff061a
SK
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))
b4689464
SK
204 )))
205
de3ff448
SK
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))]
b0ff061a 212 [expected (Msg 1605756129 ts nick uri text)])
c562bea3 213 (check-equal?
b0ff061a
SK
214 (Msg-ts-epoch actual)
215 (Msg-ts-epoch expected)
78142acb 216 "str->msg ts-epoch")
3877a0c4 217 (check-equal?
b0ff061a
SK
218 (Msg-ts-orig actual)
219 (Msg-ts-orig expected)
3877a0c4 220 "str->msg ts-orig")
c562bea3 221 (check-equal?
b0ff061a
SK
222 (Msg-nick actual)
223 (Msg-nick expected)
c562bea3
SK
224 "str->msg nick")
225 (check-equal?
b0ff061a
SK
226 (Msg-uri actual)
227 (Msg-uri expected)
c562bea3
SK
228 "str->msg uri")
229 (check-equal?
b0ff061a
SK
230 (Msg-text actual)
231 (Msg-text expected)
c562bea3 232 "str->msg text")))
63afa259 233
98529d3d 234(: str->lines (-> String (Listof String)))
e96264cc
SK
235(define (str->lines str)
236 (string-split str (regexp "[\r\n]+")))
237
63afa259 238(module+ test
de3ff448 239 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
63afa259 240
13c11724 241(: str->msgs (-> (Option String) Url String (Listof Msg)))
b201e854 242(define (str->msgs nick uri str)
3877a0c4 243 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
4764ff89 244
edadb804
SK
245(: cache-dir Path-String)
246(define cache-dir (build-path tt-home-dir "cache"))
247
d718efc4
SK
248(define cache-object-dir (build-path cache-dir "objects"))
249
edadb804
SK
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)
d718efc4 257 (build-path cache-object-dir (hash-sha1 (url->string uri))))
edadb804
SK
258
259(: url->cache-file-path-v2 (-> Url Path-String))
260(define (url->cache-file-path-v2 uri)
d718efc4
SK
261 (build-path cache-object-dir (uri-encode (url->string uri))))
262
263(define url->cache-object-path url->cache-file-path-v2)
1d753430 264
d718efc4
SK
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))))
9c464d95 270
98529d3d
SK
271; TODO Return Option
272(: uri-read-cached (-> Url String))
4214c0f3 273(define (uri-read-cached uri)
edadb804
SK
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)
0e16a46c 280 (begin
9c464d95 281 (log-warning "Cache file not found for URI: ~a" (url->string uri))
4214c0f3
SK
282 "")))
283
dbc26280
SK
284(: str->peer (String (Option Peer)))
285(define (str->peer str)
286 (log-debug "Parsing peer string: ~v" str)
13c11724
SK
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)
dbc26280
SK
293 [(list u) (Peer #f (string->url u))]
294 [(list n u) (Peer n (string->url u))]
13c11724 295 [_
dbc26280 296 (log-error "Invalid peer string: ~v" str)
13c11724
SK
297 #f])))
298
9c464d95 299
98529d3d 300(: filter-comments (-> (Listof String) (Listof String)))
9c464d95
SK
301(define (filter-comments lines)
302 (filter-not (λ (line) (string-prefix? line "#")) lines))
303
dbc26280
SK
304(: str->peers (-> String (Listof Peer)))
305(define (str->peers str)
306 (filter-map str->peer (filter-comments (str->lines str))))
9c464d95 307
dbc26280 308(: file->peers (-> Path-String (Listof Peer)))
d0a0e073
SK
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 '())))
9c464d95 315
98529d3d 316(: user-agent String)
9c464d95
SK
317(define user-agent
318 (let*
319 ([prog-name "tt"]
3c9c8266 320 [prog-version (info:#%info-lookup 'version)]
9c464d95 321 [prog-uri "https://github.com/xandkar/tt"]
dbc26280 322 [user-peer-file (build-path tt-home-dir "me")]
9c464d95 323 [user
dbc26280
SK
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)])
9c464d95
SK
328 (format "+~a" prog-uri))])
329 (format "~a/~a (~a)" prog-name prog-version user)))
330
d718efc4
SK
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
98529d3d 337(: uri-download (-> Url Void))
9c464d95 338(define (uri-download u)
d718efc4
SK
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)
9c464d95
SK
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])
d718efc4 354 #:headers (list (format "User-Agent: ~a" user-agent))))
9c464d95
SK
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
d718efc4
SK
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)])]
9c464d95
SK
386 [(_ _ _)
387 (log-error "Invalid URI: ~v" u)]))
4764ff89 388
98529d3d 389(: timeline-print (-> Out-Format (Listof Msg) Void))
b201e854 390(define (timeline-print out-format timeline)
3d042e75 391 (void (foldl (match-lambda**
b0ff061a 392 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
13c11724 393 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
3d042e75
SK
394 (msg-print out-format i m)
395 (cons nick i))])
396 (cons "" 0)
397 timeline)))
4764ff89 398
dbc26280
SK
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))
9c464d95 403 (str->msgs nick uri (uri-read-cached uri)))
4214c0f3 404
dbc26280
SK
405(: peer-download (-> Peer Void))
406(define (peer-download f)
407 (match-define (Peer nick uri) f)
2db1b40f 408 (define u (url->string uri))
dbc26280 409 (log-info "Downloading peer uri:~a" u)
9a6a9f9a 410 (with-handlers
9c464d95 411 ([exn:fail?
9a6a9f9a 412 (λ (e)
13c11724 413 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
9a6a9f9a
SK
414 #f)]
415 [integer?
416 (λ (status)
13c11724 417 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
9a6a9f9a 418 #f)])
2db1b40f
SK
419 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
420 (time-apply uri-download (list uri)))
dbc26280 421 (log-info "Peer downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
4214c0f3 422
dbc26280
SK
423(: timeline-download (-> Integer (Listof Peer) Void))
424(define (timeline-download num-workers peers)
4214c0f3 425 ; TODO No need for map - can just iter
dbc26280 426 (void (concurrent-filter-map num-workers peer-download peers)))
9a6a9f9a
SK
427
428; TODO timeline contract : time-sorted list of messages
dbc26280
SK
429(: timeline-read (-> Timeline-Order (Listof Peer) (Listof Msg)))
430(define (timeline-read order peers)
a4899240
SK
431 (define cmp (match order
432 ['old->new <]
433 ['new->old >]))
dbc26280 434 (sort (append* (filter-map peer->msgs peers))
b0ff061a 435 (λ (a b) (cmp (Msg-ts-epoch a) (Msg-ts-epoch b)))))
4764ff89 436
d0a0e073
SK
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
56de6228
SK
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
0d3f753c
SK
458(: log-writer-start (-> Log-Level Thread))
459(define (log-writer-start level)
56de6228
SK
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))
01e4c499 476
24c6a76b 477(module+ main
24f1f64b 478 (let ([log-level 'info])
c562bea3 479 (command-line
24f1f64b
SK
480 #:program
481 "tt"
c562bea3 482 #:once-each
01e4c499
SK
483 [("-d" "--debug")
484 "Enable debug log level."
485 (set! log-level 'debug)]
24f1f64b
SK
486 #:help-labels
487 ""
488 "and <command> is one of"
4214c0f3
SK
489 "r, read i : Read the timeline."
490 "d, download : Download the timeline."
edadb804 491 ; TODO Add path dynamically
3a4b2233 492 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
24f1f64b
SK
493 ""
494 #:args (command . args)
0d3f753c 495 (define log-writer (log-writer-start log-level))
4214c0f3 496 (current-command-line-arguments (list->vector args))
24f1f64b 497 (match command
4214c0f3 498 [(or "d" "download")
2db1b40f 499 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
edadb804 500 ; started noticing significant slowdowns. Reducing to 5 seems to help.
2db1b40f 501 (let ([num-workers 5])
24f1f64b
SK
502 (command-line
503 #:program
4214c0f3 504 "tt download"
24f1f64b
SK
505 #:once-each
506 [("-j" "--jobs")
507 njobs "Number of concurrent jobs."
78142acb 508 (set! num-workers (string->number njobs))]
d0a0e073 509 #:args file-paths
32dcc0b0 510 (define-values (_res _cpu real-ms _gc)
d0a0e073 511 (time-apply timeline-download (list num-workers (paths->peers file-paths))))
0d3f753c 512 (log-info "Timeline downloaded in ~a seconds." (/ real-ms 1000.0))))]
3a4b2233
SK
513 [(or "u" "upload")
514 (command-line
3877a0c4
SK
515 #:program
516 "tt upload"
517 #:args ()
edadb804 518 (if (system (path->string (build-path tt-home-dir "upload")))
3a4b2233
SK
519 (exit 0)
520 (exit 1)))]
4214c0f3 521 [(or "r" "read")
a4899240
SK
522 (let ([out-format 'multi-line]
523 [order 'old->new])
4214c0f3
SK
524 (command-line
525 #:program
526 "tt read"
a4899240
SK
527 #:once-each
528 [("-r" "--rev")
529 "Reverse displayed timeline order."
530 (set! order 'new->old)]
24f1f64b
SK
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)]
d0a0e073
SK
538 #:args file-paths
539 (timeline-print out-format (timeline-read order (paths->peers file-paths)))))])
0d3f753c 540 (log-writer-stop log-writer))))
This page took 0.103264 seconds and 4 git commands to generate.