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