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