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