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