Define custom peers-union and simplify crawling
[tt.git] / tt.rkt
CommitLineData
cd541405 1#lang typed/racket/no-check
4764ff89 2
1d753430 3(require openssl/sha1)
4764ff89 4(require racket/date)
9c464d95 5(require
d718efc4 6 net/head
edadb804 7 net/uri-codec
8da029e4 8 net/url)
4764ff89 9
3c9c8266
SK
10(require (prefix-in info: "info.rkt"))
11
78398948 12(module+ test
de3ff448 13 (require rackunit))
78398948 14
98529d3d
SK
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
7fd20778
SK
26(define-type Result
27 (∀ (α β) (U (cons 'ok α)
28 (cons 'error β))))
29
b0ff061a 30(struct Msg
78142acb 31 ([ts-epoch : Integer]
3877a0c4 32 [ts-orig : String]
0cb1ae9c 33 [from : Peer]
13c11724 34 [text : String]
b0ff061a 35 [mentions : (Listof Peer)]))
9c464d95 36
dbc26280 37(struct Peer
b056019b
SK
38 ([nick : (Option String)]
39 [uri : Url]
e2840743 40 [uri-str : String]
b056019b 41 [comment : (Option String)])
d0a0e073 42 #:transparent)
4764ff89 43
f65d6338
SK
44(struct Resp
45 ([status-line : String]
46 [headers : (Listof Bytes)]
7fd20778
SK
47 [body-input : Input-Port])
48 #:transparent)
f65d6338 49
0cb1ae9c
SK
50(: peers-equal? (-> Peer Peer Boolean))
51(define (peers-equal? p1 p2)
52 (equal? (Peer-uri-str p1)
53 (Peer-uri-str p2)))
54
55(: peer-hash (-> Peer Fixnum))
56(define (peer-hash p)
57 (equal-hash-code (Peer-uri-str p)))
58
e2840743
SK
59(define-custom-set-types peers
60 #:elem? Peer?
0cb1ae9c
SK
61 peers-equal?
62 peer-hash)
e2840743
SK
63; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
64; the following contract violations:
65;
66; custom-elem-contents: contract violation
67; expected: custom-elem?
68; given: #f
69; context...:
70; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
71; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
72; /usr/share/racket/collects/racket/cmdline.rkt:191:51
73; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
74;
75; TODO Investigate why and make a minimal reproducible test case.
76
50f0609d
SK
77(define (peers-union . peer-sets)
78 (define groups
79 (foldl
80 (λ (p groups)
81 (hash-update groups (Peer-uri-str p) (λ (group) (cons p group)) '()))
82 (hash)
83 (append* (map set->list peer-sets))))
84 (define (merge peers)
85 (match peers
86 ['() (raise 'impossible)]
87 [(list p) p]
88 [(list* p1 p2 ps)
89 (let* ([n1 (Peer-nick p1)]
90 [n2 (Peer-nick p2)]
91 [p (cond
92 [(and (not n1) (not n2)) p1]
93 [(and n1 n2 ) p1]
94 [(and n1 (not n2)) p1]
95 [(and (not n1) n2) p2]
96 [else
97 (raise 'impossible)])])
98 (merge (cons p ps)))]))
99 (make-immutable-peers (map merge (hash-values groups))))
100
101(module+ test
102 (let* ([u1 "http://foo/bar"]
103 [u2 "http://baz/quux"]
104 [p1 (Peer #f (string->url u1) u1 #f)]
105 [p2 (Peer "a" (string->url u1) u1 #f)]
106 [p3 (Peer "b" (string->url u2) u2 #f)]
107 [s1 (make-immutable-peers (list p1))]
108 [s2 (make-immutable-peers (list p2 p3))])
109 (check-true (peers? (peers-union s1 s2)))
110 (check-true (peers? (peers-union s2 s1)))
111 (check-equal? (list p3 p2) (set->list (peers-union s1 s2)))
112 (check-equal? (list p3 p2) (set->list (peers-union s2 s1)))))
113
edadb804
SK
114(: tt-home-dir Path-String)
115(define tt-home-dir (build-path (expand-user-path "~") ".tt"))
116
9a346534 117(: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
78142acb 118(define (concurrent-filter-map num-workers f xs)
dad4504d 119 ; TODO preserve order of elements OR communicate that reorder is expected
a239a233 120 ; TODO switch from mailboxes to channels
895a32cf
SK
121 (define (make-worker id f)
122 (define parent (current-thread))
123 (λ ()
a9511f7c
SK
124 (define self : Thread (current-thread))
125 (: work (∀ (α) (-> α)))
895a32cf
SK
126 (define (work)
127 (thread-send parent (cons 'next self))
128 (match (thread-receive)
c562bea3
SK
129 ['done (thread-send parent (cons 'exit id))]
130 [(cons 'unit x) (begin
131 (define y (f x))
132 (when y (thread-send parent (cons 'result y)))
133 (work))]))
895a32cf 134 (work)))
a9511f7c 135 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
895a32cf
SK
136 (define (dispatch ws xs ys)
137 (if (empty? ws)
f1493e49
SK
138 ys
139 (match (thread-receive)
c562bea3
SK
140 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
141 [(cons 'result y) (dispatch ws xs (cons y ys))]
142 [(cons 'next thd) (match xs
143 ['() (begin
144 (thread-send thd 'done)
145 (dispatch ws xs ys))]
146 [(cons x xs) (begin
147 (thread-send thd (cons 'unit x))
148 (dispatch ws xs ys))])])))
78142acb 149 (define workers (range num-workers))
9926c9a9
SK
150 (define threads (map (λ (id) (thread (make-worker id f))) workers))
151 (define results (dispatch workers xs '()))
895a32cf
SK
152 (for-each thread-wait threads)
153 results)
154
dad4504d 155(module+ test
de3ff448
SK
156 (let* ([f (λ (x) (if (even? x) x #f))]
157 [xs (range 11)]
158 [actual (sort (concurrent-filter-map 10 f xs) <)]
159 [expected (sort ( filter-map f xs) <)])
c562bea3 160 (check-equal? actual expected "concurrent-filter-map")))
dad4504d 161
98529d3d 162(: msg-print (-> Out-Format Integer Msg Void))
3d042e75
SK
163(define msg-print
164 (let* ([colors (vector 36 33)]
165 [n (vector-length colors)])
166 (λ (out-format color-i msg)
01e4c499 167 (let ([color (vector-ref colors (modulo color-i n))]
0cb1ae9c
SK
168 [nick (Peer-nick (Msg-from msg))]
169 [uri (Peer-uri-str (Msg-from msg))]
170 [text (Msg-text msg)])
3d042e75 171 (match out-format
01e4c499 172 ['single-line
13c11724
SK
173 (let ([nick (if nick nick uri)])
174 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
175 (parameterize
176 ([date-display-format 'iso-8601])
b0ff061a 177 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
13c11724 178 nick color text))]
01e4c499 179 ['multi-line
13c11724
SK
180 (let ([nick (if nick (string-append nick " ") "")])
181 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
182 (parameterize
183 ([date-display-format 'rfc2822])
b0ff061a
SK
184 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
185 (Msg-ts-orig msg)
13c11724 186 nick uri color text))])))))
e96264cc 187
3877a0c4
SK
188(: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
189(define rfc3339->epoch
190 (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}))?$")])
191 (λ (ts)
192 (match (regexp-match re ts)
193 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
194 (let*
195 ([tz-offset
196 (match* (tz-whole tz-sign tz-HH tz-MM)
197 [("Z" #f #f #f)
198 0]
199 [(_ (or "-" "+") (? identity h) (? identity m))
200 (let ([h (string->number h)]
201 [m (string->number m)]
202 ; Reverse to get back to UTC:
203 [op (match tz-sign ["+" -] ["-" +])])
204 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
205 [(a b c d)
206 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
207 0])]
208 [ts-orig ts]
209 [local-time? #f]
210 [ts-epoch (find-seconds (if SS (string->number SS) 0)
211 (string->number MM)
212 (string->number HH)
213 (string->number dd)
214 (string->number mm)
215 (string->number yyyy)
216 local-time?)])
217 (+ ts-epoch tz-offset))]
218 [_
b8b29fbb 219 (log-debug "Invalid timestamp: ~v" ts)
3877a0c4
SK
220 #f]))))
221
0cb1ae9c 222(: str->msg (-> Peer String (Option Msg)))
b4689464 223(define str->msg
3877a0c4 224 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
0cb1ae9c
SK
225 (λ (from str)
226 (define from-str (peer->str from))
d3ac9e11 227 (define str-head (substring str 0 (min 100 (string-length str))))
b4689464
SK
228 (with-handlers*
229 ([exn:fail?
230 (λ (e)
b8b29fbb 231 (log-debug
9c464d95 232 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
0cb1ae9c 233 str-head from-str e)
b4689464
SK
234 #f)])
235 (match (regexp-match re str)
3877a0c4
SK
236 [(list _wholething ts-orig text)
237 (let ([ts-epoch (rfc3339->epoch ts-orig)])
238 (if ts-epoch
13c11724
SK
239 (let ([mentions
240 (filter-map
241 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
242 [(list _wholething nick-uri)
dbc26280 243 (str->peer nick-uri)]))
13c11724 244 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
0cb1ae9c 245 (Msg ts-epoch ts-orig from text mentions))
3877a0c4 246 (begin
b8b29fbb 247 (log-debug
0cb1ae9c
SK
248 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
249 from-str str-head)
3877a0c4 250 #f)))]
b4689464 251 [_
0cb1ae9c 252 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
b4689464 253 #f])))))
88d50b3e 254
63afa259 255(module+ test
13c11724 256 ; TODO Test for when missing-nick case
b4689464
SK
257 (let* ([tzs (for*/list ([d '("-" "+")]
258 [h '("5" "05")]
259 [m '("00" ":00" "57" ":57")])
260 (string-append d h m))]
261 [tzs (list* "" "Z" tzs)])
262 (for* ([n '("fake-nick")]
0cb1ae9c 263 [u '("http://fake-uri")]
50f0609d 264 [p (list (Peer n (string->url u) u #f))]
b4689464
SK
265 [s '("" ":10")]
266 [f '("" ".1337")]
267 [z tzs]
268 [sep (list "\t" " ")]
269 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
270 (let* ([ts (string-append "2020-11-18T22:22"
271 (if (non-empty-string? s) s ":00")
272 z)]
0cb1ae9c 273 [m (str->msg p (string-append ts sep txt))])
b4689464 274 (check-not-false m)
0cb1ae9c 275 (check-equal? (Msg-from m) p)
b0ff061a
SK
276 (check-equal? (Msg-text m) txt)
277 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
b4689464
SK
278 )))
279
de3ff448
SK
280 (let* ([ts "2020-11-18T22:22:09-0500"]
281 [tab " "]
282 [text "Lorem ipsum"]
283 [nick "foo"]
0cb1ae9c 284 [uri "http://bar/"]
50f0609d 285 [peer (Peer nick (string->url uri) uri #f)]
0cb1ae9c
SK
286 [actual (str->msg peer (string-append ts tab text))]
287 [expected (Msg 1605756129 ts peer text '())])
c562bea3 288 (check-equal?
b0ff061a
SK
289 (Msg-ts-epoch actual)
290 (Msg-ts-epoch expected)
78142acb 291 "str->msg ts-epoch")
3877a0c4 292 (check-equal?
b0ff061a
SK
293 (Msg-ts-orig actual)
294 (Msg-ts-orig expected)
3877a0c4 295 "str->msg ts-orig")
c562bea3 296 (check-equal?
0cb1ae9c
SK
297 (Peer-nick (Msg-from actual))
298 (Peer-nick (Msg-from expected))
c562bea3
SK
299 "str->msg nick")
300 (check-equal?
0cb1ae9c
SK
301 (Peer-uri (Msg-from actual))
302 (Peer-uri (Msg-from expected))
c562bea3 303 "str->msg uri")
0cb1ae9c
SK
304 (check-equal?
305 (Peer-uri-str (Msg-from actual))
306 (Peer-uri-str (Msg-from expected))
307 "str->msg uri-str")
c562bea3 308 (check-equal?
b0ff061a
SK
309 (Msg-text actual)
310 (Msg-text expected)
c562bea3 311 "str->msg text")))
63afa259 312
98529d3d 313(: str->lines (-> String (Listof String)))
e96264cc
SK
314(define (str->lines str)
315 (string-split str (regexp "[\r\n]+")))
316
63afa259 317(module+ test
de3ff448 318 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
63afa259 319
0cb1ae9c
SK
320(: str->msgs (-> Peer String (Listof Msg)))
321(define (str->msgs peer str)
322 (filter-map (λ (line) (str->msg peer line))
323 (filter-comments (str->lines str))))
4764ff89 324
edadb804
SK
325(: cache-dir Path-String)
326(define cache-dir (build-path tt-home-dir "cache"))
327
d718efc4
SK
328(define cache-object-dir (build-path cache-dir "objects"))
329
edadb804
SK
330(: url->cache-file-path-v1 (-> Url Path-String))
331(define (url->cache-file-path-v1 uri)
332 (define (hash-sha1 str) : (-> String String)
333 (define in (open-input-string str))
334 (define digest (sha1 in))
335 (close-input-port in)
336 digest)
d718efc4 337 (build-path cache-object-dir (hash-sha1 (url->string uri))))
edadb804
SK
338
339(: url->cache-file-path-v2 (-> Url Path-String))
340(define (url->cache-file-path-v2 uri)
d718efc4
SK
341 (build-path cache-object-dir (uri-encode (url->string uri))))
342
0cb1ae9c
SK
343(define url->cache-object-path
344 url->cache-file-path-v2)
d3ac9e11 345
d718efc4
SK
346(define (url->cache-etag-path uri)
347 (build-path cache-dir "etags" (uri-encode (url->string uri))))
348
349(define (url->cache-lmod-path uri)
350 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
9c464d95 351
fee11be9 352(: uri-read-cached (-> Url (Option String)))
4214c0f3 353(define (uri-read-cached uri)
edadb804
SK
354 (define path-v1 (url->cache-file-path-v1 uri))
355 (define path-v2 (url->cache-file-path-v2 uri))
356 (when (file-exists? path-v1)
357 (rename-file-or-directory path-v1 path-v2 #t))
358 (if (file-exists? path-v2)
359 (file->string path-v2)
0e16a46c 360 (begin
b8b29fbb 361 (log-debug "Cache file not found for URI: ~a" (url->string uri))
fee11be9 362 #f)))
4214c0f3 363
b056019b
SK
364(: str->url (-> String (Option String)))
365(define (str->url s)
366 (with-handlers*
367 ([exn:fail? (λ (e) #f)])
368 (string->url s)))
a60c484e 369
0cb1ae9c
SK
370(: peer->str (-> Peer String))
371(define (peer->str peer)
372 (match-define (Peer n _ u c) peer)
373 (format "~a~a~a"
374 (if n (format "~a " n) "")
375 u
376 (if c (format " # ~a" c) "")))
377
378(: str->peer (-> String (Option Peer)))
dbc26280
SK
379(define (str->peer str)
380 (log-debug "Parsing peer string: ~v" str)
b056019b
SK
381 (match
382 (regexp-match
383 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
384 str)
385 [(list _wholething
386 _nick-with-space
387 nick
388 url
389 _comment-with-hash
390 comment)
391 (match (str->url url)
392 [#f
393 (log-error "Invalid URI in peer string: ~v" str)
394 #f]
e2840743
SK
395 [url
396 (Peer nick url (url->string url) comment)])]
b056019b 397 [_
b8b29fbb 398 (log-debug "Invalid peer string: ~v" str)
b056019b 399 #f]))
13c11724 400
b056019b
SK
401(module+ test
402 (check-equal?
403 (str->peer "foo http://bar/file.txt # some rando")
e2840743 404 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
b056019b
SK
405 (check-equal?
406 (str->peer "http://bar/file.txt # some rando")
e2840743 407 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
b056019b
SK
408 (check-equal?
409 (str->peer "http://bar/file.txt #")
e2840743 410 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
b056019b
SK
411 (check-equal?
412 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
e2840743 413 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
b056019b
SK
414 (check-equal?
415 (str->peer "http://bar/file.txt")
e2840743 416 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
417 (check-equal?
418 (str->peer "foo http://bar/file.txt")
e2840743 419 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
420 (check-equal?
421 (str->peer "foo bar # baz")
422 #f)
423 (check-equal?
424 (str->peer "foo bar://baz # quux")
e2840743 425 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
b056019b
SK
426 (check-equal?
427 (str->peer "foo bar//baz # quux")
428 #f))
9c464d95 429
98529d3d 430(: filter-comments (-> (Listof String) (Listof String)))
9c464d95
SK
431(define (filter-comments lines)
432 (filter-not (λ (line) (string-prefix? line "#")) lines))
433
e2840743 434(: str->peers (-> String (Setof Peer)))
dbc26280 435(define (str->peers str)
e2840743 436 (make-immutable-peers (filter-map str->peer (filter-comments (str->lines str)))))
9c464d95 437
e2840743 438(: peers->file (-> (Setof Peers) Path-String Void))
a60c484e
SK
439(define (peers->file peers path)
440 (display-lines-to-file
0cb1ae9c 441 (map peer->str
e2840743
SK
442 (sort (set->list peers)
443 (match-lambda**
444 [((Peer n1 _ _ _) (Peer n2 _ _ _))
445 (string<? (if n1 n1 "")
446 (if n2 n2 ""))])))
a60c484e
SK
447 path
448 #:exists 'replace))
449
e2840743 450(: file->peers (-> Path-String (Setof Peer)))
d0a0e073
SK
451(define (file->peers file-path)
452 (if (file-exists? file-path)
453 (str->peers (file->string file-path))
454 (begin
a60c484e 455 (log-warning "File does not exist: ~v" (path->string file-path))
e2840743 456 (make-immutable-peers))))
9c464d95 457
9c5e4499
SK
458(define re-rfc2822
459 #px"^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-2][0-9]):([0-6][0-9]):([0-6][0-9]) GMT")
460
461(: b->n (-> Bytes (Option Number)))
462(define (b->n b)
463 (string->number (bytes->string/utf-8 b)))
464
465(: mon->num (-> Bytes Natural))
466(define/match (mon->num mon)
467 [(#"Jan") 1]
468 [(#"Feb") 2]
469 [(#"Mar") 3]
470 [(#"Apr") 4]
471 [(#"May") 5]
472 [(#"Jun") 6]
473 [(#"Jul") 7]
474 [(#"Aug") 8]
475 [(#"Sep") 9]
476 [(#"Oct") 10]
477 [(#"Nov") 11]
478 [(#"Dec") 12])
479
480(: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
481(define (rfc2822->epoch timestamp)
482 (match (regexp-match re-rfc2822 timestamp)
483 [(list _ _ dd mo yyyy HH MM SS)
484 #:when (and dd mo yyyy HH MM SS)
485 (find-seconds (b->n SS)
486 (b->n MM)
487 (b->n HH)
488 (b->n dd)
489 (mon->num mo)
490 (b->n yyyy)
491 #f)]
492 [_
493 #f]))
494
98529d3d 495(: user-agent String)
9c464d95
SK
496(define user-agent
497 (let*
498 ([prog-name "tt"]
3c9c8266 499 [prog-version (info:#%info-lookup 'version)]
9c464d95 500 [prog-uri "https://github.com/xandkar/tt"]
dbc26280 501 [user-peer-file (build-path tt-home-dir "me")]
9c464d95 502 [user
dbc26280 503 (if (file-exists? user-peer-file)
e2840743
SK
504 (match (set-first (file->peers user-peer-file))
505 [(Peer #f _ u _) (format "+~a" u )]
506 [(Peer n _ u _) (format "+~a; @~a" u n)])
9c464d95
SK
507 (format "+~a" prog-uri))])
508 (format "~a/~a (~a)" prog-name prog-version user)))
509
d718efc4
SK
510(: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
511(define (header-get headers name)
512 (match (filter-map (curry extract-field name) headers)
513 [(list val) val]
514 [_ #f]))
515
7fd20778
SK
516(: uri-download-from-port
517 (-> Url (Listof (U Bytes String)) Input-Port
518 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
519(define (uri-download-from-port u headers body-input)
520 (define u-str (url->string u))
521 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
d718efc4
SK
522 (define cached-object-path (url->cache-object-path u))
523 (define cached-etag-path (url->cache-etag-path u))
524 (define cached-lmod-path (url->cache-lmod-path u))
7fd20778
SK
525 (define etag (header-get headers #"ETag"))
526 (define lmod (header-get headers #"Last-Modified"))
527 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
528 (define lmod-prev (if (file-exists? cached-lmod-path)
529 (rfc2822->epoch (file->bytes cached-lmod-path))
530 #f))
531 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
532 (define cached?
533 (or (and etag
534 (file-exists? cached-etag-path)
535 (bytes=? etag (file->bytes cached-etag-path))
536 (begin
537 (log-debug "ETags match, skipping the rest of ~v" u-str)
538 #t))
539 (and lmod-curr
540 lmod-prev
541 (<= lmod-curr lmod-prev)
542 (begin
543 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
544 #t))))
545 (if (not cached?)
68bbd2e9
SK
546 (begin
547 (log-debug
548 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
549 u-str etag lmod)
550 (make-parent-directory* cached-object-path)
551 (make-parent-directory* cached-etag-path)
552 (make-parent-directory* cached-lmod-path)
553 (call-with-output-file cached-object-path
554 (curry copy-port body-input)
555 #:exists 'replace)
556 (when etag
557 (display-to-file etag cached-etag-path #:exists 'replace))
558 (when lmod
559 (display-to-file lmod cached-lmod-path #:exists 'replace))
560 'downloaded-new)
561 'skipped-cached))
7fd20778
SK
562
563(: uri-download
564 (-> Positive-Float Url
565 (Result (U 'skipped-cached 'downloaded-new)
566 Any))) ; TODO Maybe more-precise error type?
567(define (uri-download timeout u)
f65d6338 568 (define u-str (url->string u))
f65d6338
SK
569 (define timeout-chan (make-channel))
570 (define result-chan (make-channel))
571 (define timeout-thread
572 (thread (λ ()
573 ; Doing this instead of sync/timeout to distinguish error values,
574 ; rather than just have #f to work with.
575 (sleep timeout)
7fd20778 576 (channel-put timeout-chan '(error . timeout)))))
f65d6338
SK
577 (define result-thread
578 (thread (λ ()
579 ; XXX We timeout getting a response, but body download could
580 ; also take a long time and we might want to time that out as
581 ; well, but then we may end-up with partially downloaded
582 ; objects. But that could happen anyway if the server drops the
583 ; connection for whatever reason.
584 ;
585 ; Maybe that is OK once we start treating the
586 ; downloaded object as an addition to the stored set of
587 ; messages, rather than the final set of messages.
588
589 ; TODO message db
590 ; - 1st try can just be an in-memory set that gets written-to
591 ; and read-from disk as a whole.
592 (define result
593 (with-handlers
7fd20778
SK
594 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
595 ([exn:fail:network?
596 (λ (e) `(error . (net-error . ,e)))]
597 [exn?
598 (λ (e) `(error . (other . ,e)))])
f65d6338
SK
599 (define-values (status-line headers body-input)
600 (http-sendrecv/url
601 u
602 #:headers (list (format "User-Agent: ~a" user-agent))))
7fd20778 603 `(ok . ,(Resp status-line headers body-input))))
f65d6338
SK
604 (channel-put result-chan result))))
605 (define result
606 (sync timeout-chan
607 result-chan))
608 (kill-thread result-thread)
609 (kill-thread timeout-thread)
610 (match result
7fd20778
SK
611 [(cons 'error _)
612 result]
f65d6338
SK
613 [(cons 'ok (Resp status-line headers body-input))
614 (log-debug "headers: ~v" headers)
615 (log-debug "status-line: ~v" status-line)
616 (define status
617 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
618 (log-debug "status: ~v" status)
7fd20778
SK
619 ; TODO Handle redirects. Should be within same timeout as req and body.
620 (let ([result
621 (match status
622 [200
623 `(ok . ,(uri-download-from-port u headers body-input))]
624 [_
625 `(error . (http . ,status))])])
626 (close-input-port body-input)
627 result)]))
4764ff89 628
98529d3d 629(: timeline-print (-> Out-Format (Listof Msg) Void))
b201e854 630(define (timeline-print out-format timeline)
0cb1ae9c
SK
631 (match timeline
632 ['()
633 (void)]
634 [(cons first-msg _)
635 (void (foldl (match-lambda**
636 [((and m (Msg _ _ from _ _)) (cons prev-from i))
637 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
638 (msg-print out-format i m)
639 (cons from i))])
640 (cons (Msg-from first-msg) 0)
641 timeline))]))
4764ff89 642
dbc26280 643(: peer->msgs (-> Peer (Listof Msg)))
b056019b 644(define (peer->msgs peer)
e2840743
SK
645 (match-define (Peer nick uri uri-str _) peer)
646 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
fee11be9 647 (define msgs-data (uri-read-cached uri))
4a23fd99 648 ; TODO Expire cache
fee11be9 649 (if msgs-data
0cb1ae9c 650 (str->msgs peer msgs-data)
fee11be9 651 '()))
4214c0f3 652
7fd20778
SK
653(: peer-download
654 (-> Positive-Float Peer
655 (Result (U 'skipped-cached 'downloaded-new)
656 Any)))
f65d6338 657(define (peer-download timeout peer)
e2840743 658 (match-define (Peer nick uri u _) peer)
7fd20778
SK
659 (log-info "Download BEGIN URL:~a" u)
660 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
f65d6338 661 (time-apply uri-download (list timeout uri)))
7fd20778
SK
662 (define result (car results))
663 (log-info "Download END in ~a seconds, URL:~a, result:~s"
664 (/ tm-real-ms 1000.0)
665 u
666 result)
667 result)
4214c0f3 668
e2840743 669(: timeline-download (-> Integer Positive-Float (Setof Peer) Void))
f65d6338 670(define (timeline-download num-workers timeout peers)
7fd20778
SK
671 (define results
672 (concurrent-filter-map num-workers
673 (λ (p) (cons p (peer-download timeout p)))
e2840743 674 (set->list peers)))
d54812ea
SK
675 (define peers-ok
676 (filter-map (match-lambda
677 [(cons p (cons 'ok _)) p]
678 [(cons _ (cons 'error e)) #f])
679 results))
680 (define peers-err
681 (filter-map (match-lambda
682 [(cons _ (cons 'ok _))
683 #f]
684 [(cons p (cons 'error e))
685 (struct-copy Peer p [comment (format "~s" e)])])
686 results))
7fd20778 687 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
7fd20778 688 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
9a6a9f9a 689
50f0609d 690(: peers->timeline (-> (Setof Peer) (Listof Msg)))
a60c484e 691(define (peers->timeline peers)
e2840743 692 (append* (filter-map peer->msgs (set->list peers))))
a60c484e 693
e2840743 694(: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
a60c484e 695(define (timeline-sort msgs order)
a4899240
SK
696 (define cmp (match order
697 ['old->new <]
698 ['new->old >]))
a60c484e
SK
699 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
700 (Msg-ts-epoch b)))))
4764ff89 701
e2840743 702(: paths->peers (-> (Listof String) (Setof Peer)))
d0a0e073
SK
703(define (paths->peers paths)
704 (let* ([paths (match paths
705 ['()
706 (let ([peer-refs-file (build-path tt-home-dir "peers")])
707 (log-debug
708 "No peer ref file paths provided, defaulting to ~v"
709 (path->string peer-refs-file))
710 (list peer-refs-file))]
711 [paths
712 (log-debug "Peer ref file paths provided: ~v" paths)
713 (map string->path paths)])]
50f0609d 714 [peers (apply peers-union (map file->peers paths))])
e2840743
SK
715 (log-info "Read-in ~a peers." (set-count peers))
716 peers))
d0a0e073 717
50f0609d
SK
718(: cache-filename->peer (-> Path-String (Option Peer)))
719(define (cache-filename->peer filename)
720 (define nick #f) ; TODO Look it up in the nick-db when it exists.
721 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
722 (match (str->url url-str)
723 [#f #f]
724 [url (Peer nick url url-str #f)]))
725
726(: peers-cached (-> (Setof Peer)))
727(define (peers-cached)
728 ; TODO Expire cache?
729 (make-immutable-peers
730 (filter-map cache-filename->peer
731 (directory-list cache-object-dir))))
732
733(: peers-mentioned (-> (Listof Msg) (Setof Peer)))
734(define (peers-mentioned msgs)
e2840743 735 (make-immutable-peers (append* (map Msg-mentions msgs))))
d3ac9e11 736
56de6228
SK
737(: log-writer-stop (-> Thread Void))
738(define (log-writer-stop log-writer)
739 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
740 (thread-wait log-writer))
741
0d3f753c
SK
742(: log-writer-start (-> Log-Level Thread))
743(define (log-writer-start level)
56de6228
SK
744 (let* ([logger
745 (make-logger #f #f level #f)]
746 [log-receiver
747 (make-log-receiver logger level)]
748 [log-writer
749 (thread
750 (λ ()
751 (parameterize
752 ([date-display-format 'iso-8601])
753 (let loop ()
754 (match-define (vector level msg _ topic) (sync log-receiver))
755 (unless (equal? topic 'stop)
756 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
757 (loop))))))])
758 (current-logger logger)
759 log-writer))
01e4c499 760
e8856d5c
SK
761(: crawl (-> Void))
762(define (crawl)
e2840743 763 (let* ([peers-all-file
e8856d5c
SK
764 (build-path tt-home-dir "peers-all")]
765 [peers-mentioned-file
766 (build-path tt-home-dir "peers-mentioned")]
767 [peers-parsed-file
768 (build-path tt-home-dir "peers-parsed")]
50f0609d
SK
769 [peers-cached-file
770 (build-path tt-home-dir "peers-cached")]
771 [peers-cached
772 (peers-cached)]
773 [cached-timeline
774 (peers->timeline peers-cached)]
e8856d5c 775 [peers-mentioned-curr
50f0609d 776 (peers-mentioned cached-timeline)]
e8856d5c
SK
777 [peers-mentioned-prev
778 (file->peers peers-mentioned-file)]
779 [peers-mentioned
50f0609d
SK
780 (peers-union peers-mentioned-prev
781 peers-mentioned-curr)]
e8856d5c
SK
782 [peers-all-prev
783 (file->peers peers-all-file)]
784 [peers-all
50f0609d
SK
785 (peers-union peers-mentioned
786 peers-all-prev
787 peers-cached)]
e8856d5c 788 [peers-discovered
e2840743
SK
789 (set-subtract peers-all
790 peers-all-prev)]
e8856d5c 791 [peers-parsed
e2840743 792 (for/set ([p peers-all] #:when (> (length (peer->msgs p)) 0)) p)])
e8856d5c 793 ; TODO Deeper de-duping
50f0609d 794 (log-info "Known peers cached ~a" (set-count peers-cached))
e2840743
SK
795 (log-info "Known peers mentioned: ~a" (set-count peers-mentioned))
796 (log-info "Known peers parsed ~a" (set-count peers-parsed))
797 (log-info "Known peers total: ~a" (set-count peers-all))
e8856d5c
SK
798 (log-info "Discovered ~a new peers:~n~a"
799 (set-count peers-discovered)
800 (pretty-format (map
e2840743
SK
801 (match-lambda
802 [(Peer n _ u c) (list n u c)])
e8856d5c 803 (set->list peers-discovered))))
50f0609d
SK
804 (peers->file peers-cached
805 peers-cached-file)
e8856d5c
SK
806 (peers->file peers-mentioned
807 peers-mentioned-file)
808 (peers->file peers-parsed
809 peers-parsed-file)
810 (peers->file peers-all
811 peers-all-file)))
812
813(: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
814(define (read file-paths ts-min ts-max order out-format)
815 (let* ([peers
816 (paths->peers file-paths)]
817 [msgs
818 (timeline-sort (peers->timeline peers) order)]
819 [include?
820 (λ (m)
821 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
822 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
823 (timeline-print out-format (filter include? msgs))))
824
825(: upload (-> Void))
826(define (upload)
827 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
828 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
829 (exit 0)
830 (exit 1)))
831
832(: download (-> (Listof String) Positive-Integer Positive-Float Void))
833(define (download file-paths num-workers timeout)
834 (let ([peers (paths->peers file-paths)])
835 (define-values (_res _cpu real-ms _gc)
836 (time-apply timeline-download (list num-workers timeout peers)))
837 (log-info "Downloaded timelines from ~a peers in ~a seconds."
e2840743 838 (set-count peers)
e8856d5c
SK
839 (/ real-ms 1000.0))))
840
841(: dispatch (-> String Void))
842(define (dispatch command)
843 (match command
844 [(or "d" "download")
845 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
846 ; started noticing significant slowdowns. Reducing to 5 seems to help.
847 (let ([num-workers 5]
848 [timeout 10.0])
849 (command-line
850 #:program "tt download"
851 #:once-each
852 [("-j" "--jobs")
853 njobs "Number of concurrent jobs."
854 (set! num-workers (string->number njobs))]
855 [("-t" "--timeout")
856 seconds "Timeout seconds per request."
857 (set! timeout (string->number seconds))]
858 #:args file-paths
859 (download file-paths num-workers timeout)))]
860 [(or "u" "upload")
861 (command-line
862 #:program "tt upload" #:args () (upload))]
863 [(or "r" "read")
864 (let ([out-format 'multi-line]
865 [order 'old->new]
866 [ts-min #f]
867 [ts-max #f])
868 (command-line
869 #:program "tt read"
870 #:once-each
871 [("-r" "--rev")
872 "Reverse displayed timeline order."
873 (set! order 'new->old)]
874 [("-m" "--min")
875 m "Earliest time to display (ignore anything before it)."
876 (set! ts-min (rfc3339->epoch m))]
877 [("-x" "--max")
878 x "Latest time to display (ignore anything after it)."
879 (set! ts-max (rfc3339->epoch x))]
880 #:once-any
881 [("-s" "--short")
882 "Short output format"
883 (set! out-format 'single-line)]
884 [("-l" "--long")
885 "Long output format"
886 (set! out-format 'multi-line)]
887 #:args file-paths
888 (read file-paths ts-min ts-max order out-format)))]
889 [(or "c" "crawl")
890 (command-line
891 #:program "tt crawl" #:args () (crawl))]
892 [command
893 (eprintf "Error: invalid command: ~v\n" command)
894 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
895 (exit 1)]))
896
24c6a76b 897(module+ main
24f1f64b 898 (let ([log-level 'info])
c562bea3 899 (command-line
24f1f64b
SK
900 #:program
901 "tt"
c562bea3 902 #:once-each
01e4c499
SK
903 [("-d" "--debug")
904 "Enable debug log level."
905 (set! log-level 'debug)]
24f1f64b
SK
906 #:help-labels
907 ""
908 "and <command> is one of"
a60c484e 909 "r, read : Read the timeline (offline operation)."
4214c0f3 910 "d, download : Download the timeline."
edadb804 911 ; TODO Add path dynamically
0868c39a 912 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
a60c484e 913 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
24f1f64b
SK
914 ""
915 #:args (command . args)
0d3f753c 916 (define log-writer (log-writer-start log-level))
4214c0f3 917 (current-command-line-arguments (list->vector args))
e8856d5c
SK
918 ; TODO dispatch should return status with which we should exit after cleanups
919 (dispatch command)
0d3f753c 920 (log-writer-stop log-writer))))
This page took 0.179694 seconds and 4 git commands to generate.