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