b99a45ef314b113eef308e1fcce31ef445d2bdd0
[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 : (Option String)]
31 [uri : Url]
32 [text : String]
33 [mentions : (Listof Feed)])
34 #:type-name Msg)
35
36 (struct feed
37 ([nick : (Option String)]
38 [uri : Url])
39 #:type-name Feed)
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 α))))
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->feed 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 (: url->cache-file-path-v1 (-> Url Path-String))
249 (define (url->cache-file-path-v1 uri)
250 (define (hash-sha1 str) : (-> String String)
251 (define in (open-input-string str))
252 (define digest (sha1 in))
253 (close-input-port in)
254 digest)
255 (build-path cache-dir (hash-sha1 (url->string uri))))
256
257 (: url->cache-file-path-v2 (-> Url Path-String))
258 (define (url->cache-file-path-v2 uri)
259 (build-path cache-dir (uri-encode (url->string uri))))
260
261 (define url->cache-file-path url->cache-file-path-v2)
262
263 ; TODO Return Option
264 (: uri-read-cached (-> Url String))
265 (define (uri-read-cached uri)
266 (define path-v1 (url->cache-file-path-v1 uri))
267 (define path-v2 (url->cache-file-path-v2 uri))
268 (when (file-exists? path-v1)
269 (rename-file-or-directory path-v1 path-v2 #t))
270 (if (file-exists? path-v2)
271 (file->string path-v2)
272 (begin
273 (log-warning "Cache file not found for URI: ~a" (url->string uri))
274 "")))
275
276 (: str->feed (String (Option Feed)))
277 (define (str->feed str)
278 (log-debug "Parsing feed string: ~v" str)
279 (with-handlers*
280 ([exn:fail?
281 (λ (e)
282 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
283 #f)])
284 (match (string-split str)
285 [(list u) (feed #f (string->url u))]
286 [(list n u) (feed n (string->url u))]
287 [_
288 (log-error "Invalid feed string: ~v" str)
289 #f])))
290
291
292 (: filter-comments (-> (Listof String) (Listof String)))
293 (define (filter-comments lines)
294 (filter-not (λ (line) (string-prefix? line "#")) lines))
295
296 (: str->feeds (-> String (Listof Feed)))
297 (define (str->feeds str)
298 (filter-map str->feed (filter-comments (str->lines str))))
299
300 (: file->feeds (-> Path-String (Listof Feed)))
301 (define (file->feeds filename)
302 (str->feeds (file->string filename)))
303
304 (: user-agent String)
305 (define user-agent
306 (let*
307 ([prog-name "tt"]
308 [prog-version (info:#%info-lookup 'version)]
309 [prog-uri "https://github.com/xandkar/tt"]
310 [user-feed-file (build-path tt-home-dir "me")]
311 [user
312 (if (file-exists? user-feed-file)
313 (match (first (file->feeds user-feed-file))
314 [(feed #f u) (format "+~a" (url->string u) )]
315 [(feed n u) (format "+~a; @~a" (url->string u) n)])
316 (format "+~a" prog-uri))])
317 (format "~a/~a (~a)" prog-name prog-version user)))
318
319 (: uri-download (-> Url Void))
320 (define (uri-download u)
321 (define cache-file-path (url->cache-file-path u))
322 (log-debug "uri-download ~v into ~v" u cache-file-path)
323 (match* ((url-scheme u) (url-host u) (url-port u))
324 [(s h p)
325 #:when (and s h)
326 (define ssl? (string=? s "https"))
327 (define-values (status-line headers body-input)
328 ; TODO Timeout. Currently hangs on slow connections.
329 (http-sendrecv
330 h
331 (url->string (struct-copy url u [scheme #f] [host #f]))
332 #:ssl? ssl?
333 #:port (cond [p p] [ssl? 443] [else 80])
334 #:headers (list (format "User-Agent: ~a" user-agent))
335 ))
336 (log-debug "headers: ~v" headers)
337 (log-debug "status-line: ~v" status-line)
338 (define status
339 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
340 (log-debug "status: ~v" status)
341 ; TODO Handle redirects
342 (if (= 200 status)
343 (begin
344 (make-parent-directory* cache-file-path)
345 (call-with-output-file cache-file-path
346 (curry copy-port body-input)
347 #:exists 'replace))
348 (raise status))]
349 [(_ _ _)
350 (log-error "Invalid URI: ~v" u)]))
351
352 (: timeline-print (-> Out-Format (Listof Msg) Void))
353 (define (timeline-print out-format timeline)
354 (void (foldl (match-lambda**
355 [((and m (msg _ _ nick _ _ _)) (cons prev-nick i))
356 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
357 (msg-print out-format i m)
358 (cons nick i))])
359 (cons "" 0)
360 timeline)))
361
362 (: feed->msgs (-> Feed (Listof Msg)))
363 (define (feed->msgs f)
364 (match-define (feed nick uri) f)
365 (log-info "Reading feed nick:~v uri:~v" nick (url->string uri))
366 (str->msgs nick uri (uri-read-cached uri)))
367
368 (: feed-download (-> Feed Void))
369 (define (feed-download f)
370 (match-define (feed nick uri) f)
371 (define u (url->string uri))
372 (log-info "Downloading feed uri:~a" u)
373 (with-handlers
374 ([exn:fail?
375 (λ (e)
376 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
377 #f)]
378 [integer?
379 (λ (status)
380 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
381 #f)])
382 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
383 (time-apply uri-download (list uri)))
384 (log-info "Feed downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
385
386 (: timeline-download (-> Integer (Listof Feed) Void))
387 (define (timeline-download num-workers feeds)
388 ; TODO No need for map - can just iter
389 (void (concurrent-filter-map num-workers feed-download feeds)))
390
391 ; TODO timeline contract : time-sorted list of messages
392 (: timeline-read (-> Timeline-Order (Listof Feed) (Listof Msg)))
393 (define (timeline-read order feeds)
394 (define cmp (match order
395 ['old->new <]
396 ['new->old >]))
397 (sort (append* (filter-map feed->msgs feeds))
398 (λ (a b) (cmp (msg-ts-epoch a) (msg-ts-epoch b)))))
399
400 (: log-writer-stop (-> Thread Void))
401 (define (log-writer-stop log-writer)
402 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
403 (thread-wait log-writer))
404
405 (: logger-start (-> Log-Level Thread))
406 (define (logger-start level)
407 (let* ([logger
408 (make-logger #f #f level #f)]
409 [log-receiver
410 (make-log-receiver logger level)]
411 [log-writer
412 (thread
413 (λ ()
414 (parameterize
415 ([date-display-format 'iso-8601])
416 (let loop ()
417 (match-define (vector level msg _ topic) (sync log-receiver))
418 (unless (equal? topic 'stop)
419 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
420 (loop))))))])
421 (current-logger logger)
422 log-writer))
423
424 (module+ main
425 (let ([log-level 'info])
426 (command-line
427 #:program
428 "tt"
429 #:once-each
430 [("-d" "--debug")
431 "Enable debug log level."
432 (set! log-level 'debug)]
433 #:help-labels
434 ""
435 "and <command> is one of"
436 "r, read i : Read the timeline."
437 "d, download : Download the timeline."
438 ; TODO Add path dynamically
439 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
440 ""
441 #:args (command . args)
442 (define log-writer (logger-start log-level))
443 (current-command-line-arguments (list->vector args))
444 (match command
445 [(or "d" "download")
446 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
447 ; started noticing significant slowdowns. Reducing to 5 seems to help.
448 (let ([num-workers 5])
449 (command-line
450 #:program
451 "tt download"
452 #:once-each
453 [("-j" "--jobs")
454 njobs "Number of concurrent jobs."
455 (set! num-workers (string->number njobs))]
456 #:args (filename)
457 (define-values (_res _cpu real-ms _gc)
458 (time-apply timeline-download (list num-workers (file->feeds filename))))
459 (log-info "Timeline downloaded in ~a seconds." (/ real-ms 1000.0))
460 (log-writer-stop log-writer)))]
461 [(or "u" "upload")
462 (command-line
463 #:program
464 "tt upload"
465 #:args ()
466 (if (system (path->string (build-path tt-home-dir "upload")))
467 (exit 0)
468 (exit 1)))]
469 [(or "r" "read")
470 (let ([out-format 'multi-line]
471 [order 'old->new])
472 (command-line
473 #:program
474 "tt read"
475 #:once-each
476 [("-r" "--rev")
477 "Reverse displayed timeline order."
478 (set! order 'new->old)]
479 #:once-any
480 [("-s" "--short")
481 "Short output format"
482 (set! out-format 'single-line)]
483 [("-l" "--long")
484 "Long output format"
485 (set! out-format 'multi-line)]
486 #:args (filename)
487 (timeline-print out-format (timeline-read order (file->feeds filename)))))]
488 ))))
This page took 0.068182 seconds and 3 git commands to generate.