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