Leave reminder to parse metadata along with messages
[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
cd868590
SK
410; TODO Should return 2 things: 1) msgs; 2) metadata parsed from comments
411; TODO Update peer nick based on metadata?
0cb1ae9c
SK
412(: str->msgs (-> Peer String (Listof Msg)))
413(define (str->msgs peer str)
414 (filter-map (λ (line) (str->msg peer line))
415 (filter-comments (str->lines str))))
4764ff89 416
edadb804
SK
417(: cache-dir Path-String)
418(define cache-dir (build-path tt-home-dir "cache"))
419
d718efc4
SK
420(define cache-object-dir (build-path cache-dir "objects"))
421
edadb804
SK
422(: url->cache-file-path-v1 (-> Url Path-String))
423(define (url->cache-file-path-v1 uri)
424 (define (hash-sha1 str) : (-> String String)
425 (define in (open-input-string str))
426 (define digest (sha1 in))
427 (close-input-port in)
428 digest)
d718efc4 429 (build-path cache-object-dir (hash-sha1 (url->string uri))))
edadb804
SK
430
431(: url->cache-file-path-v2 (-> Url Path-String))
432(define (url->cache-file-path-v2 uri)
d718efc4
SK
433 (build-path cache-object-dir (uri-encode (url->string uri))))
434
0cb1ae9c
SK
435(define url->cache-object-path
436 url->cache-file-path-v2)
d3ac9e11 437
d718efc4
SK
438(define (url->cache-etag-path uri)
439 (build-path cache-dir "etags" (uri-encode (url->string uri))))
440
441(define (url->cache-lmod-path uri)
442 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
9c464d95 443
fee11be9 444(: uri-read-cached (-> Url (Option String)))
4214c0f3 445(define (uri-read-cached uri)
edadb804
SK
446 (define path-v1 (url->cache-file-path-v1 uri))
447 (define path-v2 (url->cache-file-path-v2 uri))
448 (when (file-exists? path-v1)
449 (rename-file-or-directory path-v1 path-v2 #t))
450 (if (file-exists? path-v2)
451 (file->string path-v2)
0e16a46c 452 (begin
b8b29fbb 453 (log-debug "Cache file not found for URI: ~a" (url->string uri))
fee11be9 454 #f)))
4214c0f3 455
b056019b
SK
456(: str->url (-> String (Option String)))
457(define (str->url s)
458 (with-handlers*
459 ([exn:fail? (λ (e) #f)])
460 (string->url s)))
a60c484e 461
0cb1ae9c
SK
462(: peer->str (-> Peer String))
463(define (peer->str peer)
464 (match-define (Peer n _ u c) peer)
465 (format "~a~a~a"
466 (if n (format "~a " n) "")
467 u
468 (if c (format " # ~a" c) "")))
469
470(: str->peer (-> String (Option Peer)))
dbc26280
SK
471(define (str->peer str)
472 (log-debug "Parsing peer string: ~v" str)
b056019b
SK
473 (match
474 (regexp-match
475 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
476 str)
477 [(list _wholething
478 _nick-with-space
479 nick
480 url
481 _comment-with-hash
482 comment)
483 (match (str->url url)
484 [#f
485 (log-error "Invalid URI in peer string: ~v" str)
486 #f]
e2840743
SK
487 [url
488 (Peer nick url (url->string url) comment)])]
b056019b 489 [_
b8b29fbb 490 (log-debug "Invalid peer string: ~v" str)
b056019b 491 #f]))
13c11724 492
b056019b
SK
493(module+ test
494 (check-equal?
495 (str->peer "foo http://bar/file.txt # some rando")
e2840743 496 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
b056019b
SK
497 (check-equal?
498 (str->peer "http://bar/file.txt # some rando")
e2840743 499 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
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" ""))
b056019b
SK
503 (check-equal?
504 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
e2840743 505 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
b056019b
SK
506 (check-equal?
507 (str->peer "http://bar/file.txt")
e2840743 508 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
509 (check-equal?
510 (str->peer "foo http://bar/file.txt")
e2840743 511 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
512 (check-equal?
513 (str->peer "foo bar # baz")
514 #f)
515 (check-equal?
516 (str->peer "foo bar://baz # quux")
e2840743 517 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
b056019b
SK
518 (check-equal?
519 (str->peer "foo bar//baz # quux")
520 #f))
9c464d95 521
98529d3d 522(: filter-comments (-> (Listof String) (Listof String)))
9c464d95
SK
523(define (filter-comments lines)
524 (filter-not (λ (line) (string-prefix? line "#")) lines))
525
dd098ae3 526(: str->peers (-> String (Listof Peer)))
dbc26280 527(define (str->peers str)
dd098ae3 528 (filter-map str->peer (filter-comments (str->lines str))))
9c464d95 529
dd098ae3 530(: peers->file (-> (Listof Peers) Path-String Void))
a60c484e
SK
531(define (peers->file peers path)
532 (display-lines-to-file
0cb1ae9c 533 (map peer->str
dd098ae3 534 (sort peers
e2840743
SK
535 (match-lambda**
536 [((Peer n1 _ _ _) (Peer n2 _ _ _))
537 (string<? (if n1 n1 "")
538 (if n2 n2 ""))])))
a60c484e
SK
539 path
540 #:exists 'replace))
541
dd098ae3 542(: file->peers (-> Path-String (Listof Peer)))
d0a0e073
SK
543(define (file->peers file-path)
544 (if (file-exists? file-path)
545 (str->peers (file->string file-path))
546 (begin
a60c484e 547 (log-warning "File does not exist: ~v" (path->string file-path))
dd098ae3 548 '())))
9c464d95 549
9c5e4499
SK
550(define re-rfc2822
551 #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")
552
553(: b->n (-> Bytes (Option Number)))
554(define (b->n b)
555 (string->number (bytes->string/utf-8 b)))
556
557(: mon->num (-> Bytes Natural))
558(define/match (mon->num mon)
559 [(#"Jan") 1]
560 [(#"Feb") 2]
561 [(#"Mar") 3]
562 [(#"Apr") 4]
563 [(#"May") 5]
564 [(#"Jun") 6]
565 [(#"Jul") 7]
566 [(#"Aug") 8]
567 [(#"Sep") 9]
568 [(#"Oct") 10]
569 [(#"Nov") 11]
570 [(#"Dec") 12])
571
572(: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
573(define (rfc2822->epoch timestamp)
574 (match (regexp-match re-rfc2822 timestamp)
575 [(list _ _ dd mo yyyy HH MM SS)
576 #:when (and dd mo yyyy HH MM SS)
577 (find-seconds (b->n SS)
578 (b->n MM)
579 (b->n HH)
580 (b->n dd)
581 (mon->num mo)
582 (b->n yyyy)
583 #f)]
584 [_
585 #f]))
586
d718efc4
SK
587(: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
588(define (header-get headers name)
589 (match (filter-map (curry extract-field name) headers)
590 [(list val) val]
591 [_ #f]))
592
7fd20778
SK
593(: uri-download-from-port
594 (-> Url (Listof (U Bytes String)) Input-Port
595 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
596(define (uri-download-from-port u headers body-input)
597 (define u-str (url->string u))
598 (log-debug "uri-download-from-port ~v into ~v" u-str cached-object-path)
d718efc4
SK
599 (define cached-object-path (url->cache-object-path u))
600 (define cached-etag-path (url->cache-etag-path u))
601 (define cached-lmod-path (url->cache-lmod-path u))
7fd20778
SK
602 (define etag (header-get headers #"ETag"))
603 (define lmod (header-get headers #"Last-Modified"))
604 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
605 (define lmod-prev (if (file-exists? cached-lmod-path)
606 (rfc2822->epoch (file->bytes cached-lmod-path))
607 #f))
608 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
609 (define cached?
610 (or (and etag
611 (file-exists? cached-etag-path)
612 (bytes=? etag (file->bytes cached-etag-path))
613 (begin
614 (log-debug "ETags match, skipping the rest of ~v" u-str)
615 #t))
616 (and lmod-curr
617 lmod-prev
618 (<= lmod-curr lmod-prev)
619 (begin
620 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
621 #t))))
622 (if (not cached?)
68bbd2e9
SK
623 (begin
624 (log-debug
625 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
626 u-str etag lmod)
627 (make-parent-directory* cached-object-path)
628 (make-parent-directory* cached-etag-path)
629 (make-parent-directory* cached-lmod-path)
630 (call-with-output-file cached-object-path
631 (curry copy-port body-input)
632 #:exists 'replace)
633 (when etag
634 (display-to-file etag cached-etag-path #:exists 'replace))
635 (when lmod
636 (display-to-file lmod cached-lmod-path #:exists 'replace))
637 'downloaded-new)
638 'skipped-cached))
7fd20778
SK
639
640(: uri-download
641 (-> Positive-Float Url
642 (Result (U 'skipped-cached 'downloaded-new)
643 Any))) ; TODO Maybe more-precise error type?
644(define (uri-download timeout u)
f65d6338 645 (define u-str (url->string u))
f65d6338
SK
646 (define timeout-chan (make-channel))
647 (define result-chan (make-channel))
648 (define timeout-thread
649 (thread (λ ()
650 ; Doing this instead of sync/timeout to distinguish error values,
651 ; rather than just have #f to work with.
652 (sleep timeout)
7fd20778 653 (channel-put timeout-chan '(error . timeout)))))
f65d6338
SK
654 (define result-thread
655 (thread (λ ()
656 ; XXX We timeout getting a response, but body download could
657 ; also take a long time and we might want to time that out as
658 ; well, but then we may end-up with partially downloaded
659 ; objects. But that could happen anyway if the server drops the
660 ; connection for whatever reason.
661 ;
662 ; Maybe that is OK once we start treating the
663 ; downloaded object as an addition to the stored set of
664 ; messages, rather than the final set of messages.
665
666 ; TODO message db
667 ; - 1st try can just be an in-memory set that gets written-to
668 ; and read-from disk as a whole.
669 (define result
670 (with-handlers
7fd20778
SK
671 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
672 ([exn:fail:network?
673 (λ (e) `(error . (net-error . ,e)))]
674 [exn?
675 (λ (e) `(error . (other . ,e)))])
f65d6338
SK
676 (define-values (status-line headers body-input)
677 (http-sendrecv/url
678 u
7296ed94 679 #:headers (list (format "User-Agent: ~a" user-agent-str))))
7fd20778 680 `(ok . ,(Resp status-line headers body-input))))
f65d6338
SK
681 (channel-put result-chan result))))
682 (define result
683 (sync timeout-chan
684 result-chan))
685 (kill-thread result-thread)
686 (kill-thread timeout-thread)
687 (match result
7fd20778
SK
688 [(cons 'error _)
689 result]
f65d6338
SK
690 [(cons 'ok (Resp status-line headers body-input))
691 (log-debug "headers: ~v" headers)
692 (log-debug "status-line: ~v" status-line)
693 (define status
694 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
695 (log-debug "status: ~v" status)
7fd20778
SK
696 ; TODO Handle redirects. Should be within same timeout as req and body.
697 (let ([result
698 (match status
699 [200
700 `(ok . ,(uri-download-from-port u headers body-input))]
701 [_
702 `(error . (http . ,status))])])
703 (close-input-port body-input)
704 result)]))
4764ff89 705
98529d3d 706(: timeline-print (-> Out-Format (Listof Msg) Void))
b201e854 707(define (timeline-print out-format timeline)
0cb1ae9c
SK
708 (match timeline
709 ['()
710 (void)]
711 [(cons first-msg _)
712 (void (foldl (match-lambda**
713 [((and m (Msg _ _ from _ _)) (cons prev-from i))
714 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
715 (msg-print out-format i m)
716 (cons from i))])
717 (cons (Msg-from first-msg) 0)
718 timeline))]))
4764ff89 719
dbc26280 720(: peer->msgs (-> Peer (Listof Msg)))
b056019b 721(define (peer->msgs peer)
e2840743
SK
722 (match-define (Peer nick uri uri-str _) peer)
723 (log-debug "Reading peer nick:~v uri:~v" nick uri-str)
fee11be9 724 (define msgs-data (uri-read-cached uri))
4a23fd99 725 ; TODO Expire cache
fee11be9 726 (if msgs-data
0cb1ae9c 727 (str->msgs peer msgs-data)
fee11be9 728 '()))
4214c0f3 729
7fd20778
SK
730(: peer-download
731 (-> Positive-Float Peer
732 (Result (U 'skipped-cached 'downloaded-new)
733 Any)))
f65d6338 734(define (peer-download timeout peer)
e2840743 735 (match-define (Peer nick uri u _) peer)
7fd20778
SK
736 (log-info "Download BEGIN URL:~a" u)
737 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
f65d6338 738 (time-apply uri-download (list timeout uri)))
7fd20778
SK
739 (define result (car results))
740 (log-info "Download END in ~a seconds, URL:~a, result:~s"
741 (/ tm-real-ms 1000.0)
742 u
743 result)
744 result)
4214c0f3 745
dd098ae3 746(: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
f65d6338 747(define (timeline-download num-workers timeout peers)
7fd20778
SK
748 (define results
749 (concurrent-filter-map num-workers
750 (λ (p) (cons p (peer-download timeout p)))
dd098ae3 751 peers))
d54812ea
SK
752 (define peers-ok
753 (filter-map (match-lambda
754 [(cons p (cons 'ok _)) p]
755 [(cons _ (cons 'error e)) #f])
756 results))
757 (define peers-err
758 (filter-map (match-lambda
759 [(cons _ (cons 'ok _))
760 #f]
761 [(cons p (cons 'error e))
762 (struct-copy Peer p [comment (format "~s" e)])])
763 results))
7fd20778 764 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok"))
7fd20778 765 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err")))
9a6a9f9a 766
dd098ae3 767(: peers->timeline (-> (Listof Peer) (Listof Msg)))
a60c484e 768(define (peers->timeline peers)
dd098ae3 769 (append* (filter-map peer->msgs peers)))
a60c484e 770
e2840743 771(: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
a60c484e 772(define (timeline-sort msgs order)
a4899240
SK
773 (define cmp (match order
774 ['old->new <]
775 ['new->old >]))
a60c484e
SK
776 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
777 (Msg-ts-epoch b)))))
4764ff89 778
dd098ae3 779(: paths->peers (-> (Listof String) (Listof Peer)))
d0a0e073
SK
780(define (paths->peers paths)
781 (let* ([paths (match paths
782 ['()
783 (let ([peer-refs-file (build-path tt-home-dir "peers")])
784 (log-debug
785 "No peer ref file paths provided, defaulting to ~v"
786 (path->string peer-refs-file))
787 (list peer-refs-file))]
788 [paths
789 (log-debug "Peer ref file paths provided: ~v" paths)
790 (map string->path paths)])]
dd098ae3
SK
791 [peers (apply peers-merge (map file->peers paths))])
792 (log-info "Read-in ~a peers." (length peers))
e2840743 793 peers))
d0a0e073 794
50f0609d
SK
795(: cache-filename->peer (-> Path-String (Option Peer)))
796(define (cache-filename->peer filename)
797 (define nick #f) ; TODO Look it up in the nick-db when it exists.
798 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
799 (match (str->url url-str)
800 [#f #f]
801 [url (Peer nick url url-str #f)]))
802
dd098ae3 803(: peers-cached (-> (Listof Peer)))
50f0609d
SK
804(define (peers-cached)
805 ; TODO Expire cache?
dd098ae3 806 (filter-map cache-filename->peer (directory-list cache-object-dir)))
50f0609d 807
dd098ae3 808(: peers-mentioned (-> (Listof Msg) (Listof Peer)))
50f0609d 809(define (peers-mentioned msgs)
dd098ae3 810 (append* (map Msg-mentions msgs)))
d3ac9e11 811
56de6228
SK
812(: log-writer-stop (-> Thread Void))
813(define (log-writer-stop log-writer)
814 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
815 (thread-wait log-writer))
816
0d3f753c
SK
817(: log-writer-start (-> Log-Level Thread))
818(define (log-writer-start level)
56de6228
SK
819 (let* ([logger
820 (make-logger #f #f level #f)]
821 [log-receiver
822 (make-log-receiver logger level)]
823 [log-writer
824 (thread
825 (λ ()
826 (parameterize
827 ([date-display-format 'iso-8601])
828 (let loop ()
829 (match-define (vector level msg _ topic) (sync log-receiver))
830 (unless (equal? topic 'stop)
831 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
832 (loop))))))])
833 (current-logger logger)
834 log-writer))
01e4c499 835
651cf37d
SK
836(: msgs->nick-hist (-> (Listof Msg) Nick-Hist))
837(define (msgs->nick-hist msgs)
5272d418 838 (foldl
651cf37d
SK
839 (λ (msg url->nick->hist)
840 (match-define (Msg curr _ from _ mentions) msg)
841 (foldl
842 (λ (peer url->nick->hist)
843 (match-define (Peer nick url _ _) peer)
844 (if nick
845 (hash-update url->nick->hist
846 url
847 (λ (nick->hist)
848 (hash-update nick->hist
849 nick
850 (match-lambda
851 [(Hist freq prev)
852 (Hist (+ 1 freq) (max prev curr))])
853 (Hist 0 0)))
854 (hash))
855 url->nick->hist))
856 url->nick->hist
857 (cons from mentions)))
5272d418 858 (hash)
651cf37d 859 msgs))
5272d418 860
651cf37d
SK
861(: update-nicks-history (-> (Listof Msg) Void))
862(define (update-nicks-history msgs)
5272d418 863 (hash-for-each
651cf37d
SK
864 (msgs->nick-hist msgs)
865 (λ (url nick->hist)
5272d418 866 (define path (build-path tt-home-dir "nicks" "seen" (uri-encode (url->string url))))
651cf37d 867 (make-parent-directory* path)
5272d418 868 (display-lines-to-file
651cf37d
SK
869 (map (match-lambda
870 [(cons nick (Hist freq last))
871 (format "~a ~a ~a" nick freq last)])
872 (sort (hash->list nick->hist)
873 (match-lambda**
874 [((cons _ (Hist a _)) (cons _ (Hist b _)))
875 (> a b)])))
5272d418
SK
876 path
877 #:exists 'replace))))
878
651cf37d
SK
879(: nick-hist-most-by (-> Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
880(define (nick-hist-most-by url->nick->hist url by)
881 (match (hash-ref url->nick->hist url #f)
882 [#f #f]
883 [nick->hist
884 (match (sort (hash->list nick->hist)
885 (λ (a b) (> (by (cdr a))
886 (by (cdr b)))))
887 ['() #f]
888 [(cons (cons nick _) _) nick])]))
889
890(: nick-hist-latest (-> Nick-Hist Url (Option String)))
891(define (nick-hist-latest nick-hist url)
892 (nick-hist-most-by nick-hist url Hist-last))
893
894(: nick-hist-common (-> Nick-Hist Url (Option String)))
895(define (nick-hist-common nick-hist url)
896 (nick-hist-most-by nick-hist url Hist-freq))
897
898(module+ test
899 (let* ([url-str "http://foo"]
900 [url (string->url url-str)]
901 [nick1 "a"]
902 [nick2 "b"]
903 [nick3 "c"]
904 [ts-str-1 "2021-11-29T23:29:08-0500"]
905 [ts-str-2 "2021-11-29T23:30:00-0500"]
906 [ts-1 (rfc3339->epoch ts-str-1)]
907 [ts-2 (rfc3339->epoch ts-str-2)]
908 [msgs
909 (map (match-lambda
910 [(cons ts-str nick)
911 (str->msg (str->peer "test http://test")
912 (string-append ts-str " Hi @<" nick " " url-str ">"))])
913 (list (cons ts-str-2 nick1)
914 (cons ts-str-1 nick2)
915 (cons ts-str-1 nick2)
916 (cons ts-str-1 nick3)
917 (cons ts-str-1 nick3)
918 (cons ts-str-1 nick3)))]
919 [hist
920 (msgs->nick-hist msgs)])
921 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
922 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
923 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
924 (check-equal? (nick-hist-common hist url) nick3)
925 (check-equal? (nick-hist-latest hist url) nick1)))
926
e8856d5c
SK
927(: crawl (-> Void))
928(define (crawl)
dd098ae3 929 ; TODO Test the non-io parts of crawling
e2840743 930 (let* ([peers-all-file
e8856d5c
SK
931 (build-path tt-home-dir "peers-all")]
932 [peers-mentioned-file
933 (build-path tt-home-dir "peers-mentioned")]
934 [peers-parsed-file
935 (build-path tt-home-dir "peers-parsed")]
50f0609d
SK
936 [peers-cached-file
937 (build-path tt-home-dir "peers-cached")]
938 [peers-cached
939 (peers-cached)]
940 [cached-timeline
941 (peers->timeline peers-cached)]
e8856d5c 942 [peers-mentioned-curr
50f0609d 943 (peers-mentioned cached-timeline)]
e8856d5c
SK
944 [peers-mentioned-prev
945 (file->peers peers-mentioned-file)]
e8856d5c
SK
946 [peers-all-prev
947 (file->peers peers-all-file)]
5272d418
SK
948 [peers-mentioned
949 (begin
950 ; XXX Updating nicks before running peers-merge,
951 ; since peers-merge is expected to refer to it in the future.
651cf37d 952 (update-nicks-history cached-timeline)
5272d418
SK
953 (peers-merge peers-mentioned-prev
954 peers-mentioned-curr))]
e8856d5c 955 [peers-all
dd098ae3 956 (peers-merge peers-mentioned
50f0609d
SK
957 peers-all-prev
958 peers-cached)]
e8856d5c 959 [peers-discovered
dd098ae3
SK
960 (set->list (set-subtract (make-immutable-peers peers-all)
961 (make-immutable-peers peers-all-prev)))]
e8856d5c 962 [peers-parsed
dd098ae3 963 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
e8856d5c 964 ; TODO Deeper de-duping
dd098ae3
SK
965 (log-info "Known peers cached ~a" (length peers-cached))
966 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
967 (log-info "Known peers parsed ~a" (length peers-parsed))
968 (log-info "Known peers total: ~a" (length peers-all))
e8856d5c 969 (log-info "Discovered ~a new peers:~n~a"
dd098ae3 970 (length peers-discovered)
e8856d5c 971 (pretty-format (map
e2840743
SK
972 (match-lambda
973 [(Peer n _ u c) (list n u c)])
dd098ae3 974 peers-discovered)))
50f0609d
SK
975 (peers->file peers-cached
976 peers-cached-file)
e8856d5c
SK
977 (peers->file peers-mentioned
978 peers-mentioned-file)
979 (peers->file peers-parsed
980 peers-parsed-file)
981 (peers->file peers-all
982 peers-all-file)))
983
984(: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
985(define (read file-paths ts-min ts-max order out-format)
986 (let* ([peers
987 (paths->peers file-paths)]
988 [msgs
989 (timeline-sort (peers->timeline peers) order)]
990 [include?
991 (λ (m)
992 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
993 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
994 (timeline-print out-format (filter include? msgs))))
995
996(: upload (-> Void))
997(define (upload)
998 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
999 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
1000 (exit 0)
1001 (exit 1)))
1002
1003(: download (-> (Listof String) Positive-Integer Positive-Float Void))
1004(define (download file-paths num-workers timeout)
1005 (let ([peers (paths->peers file-paths)])
1006 (define-values (_res _cpu real-ms _gc)
1007 (time-apply timeline-download (list num-workers timeout peers)))
1008 (log-info "Downloaded timelines from ~a peers in ~a seconds."
dd098ae3 1009 (length peers)
e8856d5c
SK
1010 (/ real-ms 1000.0))))
1011
1012(: dispatch (-> String Void))
1013(define (dispatch command)
1014 (match command
1015 [(or "d" "download")
1016 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
1017 ; started noticing significant slowdowns. Reducing to 5 seems to help.
1018 (let ([num-workers 5]
1019 [timeout 10.0])
1020 (command-line
1021 #:program "tt download"
1022 #:once-each
1023 [("-j" "--jobs")
1024 njobs "Number of concurrent jobs."
1025 (set! num-workers (string->number njobs))]
1026 [("-t" "--timeout")
1027 seconds "Timeout seconds per request."
1028 (set! timeout (string->number seconds))]
1029 #:args file-paths
1030 (download file-paths num-workers timeout)))]
1031 [(or "u" "upload")
1032 (command-line
1033 #:program "tt upload" #:args () (upload))]
1034 [(or "r" "read")
1035 (let ([out-format 'multi-line]
1036 [order 'old->new]
1037 [ts-min #f]
1038 [ts-max #f])
1039 (command-line
1040 #:program "tt read"
1041 #:once-each
1042 [("-r" "--rev")
1043 "Reverse displayed timeline order."
1044 (set! order 'new->old)]
1045 [("-m" "--min")
1046 m "Earliest time to display (ignore anything before it)."
1047 (set! ts-min (rfc3339->epoch m))]
1048 [("-x" "--max")
1049 x "Latest time to display (ignore anything after it)."
1050 (set! ts-max (rfc3339->epoch x))]
1051 #:once-any
1052 [("-s" "--short")
1053 "Short output format"
1054 (set! out-format 'single-line)]
1055 [("-l" "--long")
1056 "Long output format"
1057 (set! out-format 'multi-line)]
1058 #:args file-paths
1059 (read file-paths ts-min ts-max order out-format)))]
1060 [(or "c" "crawl")
1061 (command-line
1062 #:program "tt crawl" #:args () (crawl))]
1063 [command
1064 (eprintf "Error: invalid command: ~v\n" command)
1065 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1066 (exit 1)]))
1067
24c6a76b 1068(module+ main
24f1f64b 1069 (let ([log-level 'info])
c562bea3 1070 (command-line
24f1f64b
SK
1071 #:program
1072 "tt"
c562bea3 1073 #:once-each
01e4c499
SK
1074 [("-d" "--debug")
1075 "Enable debug log level."
1076 (set! log-level 'debug)]
24f1f64b
SK
1077 #:help-labels
1078 ""
1079 "and <command> is one of"
a60c484e 1080 "r, read : Read the timeline (offline operation)."
4214c0f3 1081 "d, download : Download the timeline."
edadb804 1082 ; TODO Add path dynamically
0868c39a 1083 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
a60c484e 1084 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
24f1f64b
SK
1085 ""
1086 #:args (command . args)
0d3f753c 1087 (define log-writer (log-writer-start log-level))
4214c0f3 1088 (current-command-line-arguments (list->vector args))
7296ed94 1089 (set-user-agent-str (build-path tt-home-dir "me"))
e8856d5c
SK
1090 ; TODO dispatch should return status with which we should exit after cleanups
1091 (dispatch command)
0d3f753c 1092 (log-writer-stop log-writer))))
This page took 0.221634 seconds and 4 git commands to generate.