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