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