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