1 #lang typed/racket/no-check
12 (require (prefix-in info: "info.rkt"))
20 (define-type Out-Format
24 (define-type Timeline-Order
31 [nick : (Option String)]
34 [mentions : (Listof Peer)]))
37 ([nick : (Option String)]
41 (: tt-home-dir Path-String)
42 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
44 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
45 (define (concurrent-filter-map num-workers f xs)
46 ; TODO preserve order of elements OR communicate that reorder is expected
47 ; TODO switch from mailboxes to channels
48 (define (make-worker id f)
49 (define parent (current-thread))
51 (define self : Thread (current-thread))
52 (: work (∀ (α) (-> α)))
54 (thread-send parent (cons 'next self))
55 (match (thread-receive)
56 ['done (thread-send parent (cons 'exit id))]
57 [(cons 'unit x) (begin
59 (when y (thread-send parent (cons 'result y)))
62 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
63 (define (dispatch ws xs ys)
66 (match (thread-receive)
67 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
68 [(cons 'result y) (dispatch ws xs (cons y ys))]
69 [(cons 'next thd) (match xs
71 (thread-send thd 'done)
74 (thread-send thd (cons 'unit x))
75 (dispatch ws xs ys))])])))
76 (define workers (range num-workers))
77 (define threads (map (λ (id) (thread (make-worker id f))) workers))
78 (define results (dispatch workers xs '()))
79 (for-each thread-wait threads)
83 (let* ([f (λ (x) (if (even? x) x #f))]
85 [actual (sort (concurrent-filter-map 10 f xs) <)]
86 [expected (sort ( filter-map f xs) <)])
87 (check-equal? actual expected "concurrent-filter-map")))
89 (: msg-print (-> Out-Format Integer Msg Void))
91 (let* ([colors (vector 36 33)]
92 [n (vector-length colors)])
93 (λ (out-format color-i msg)
94 (let ([color (vector-ref colors (modulo color-i n))]
96 [uri (url->string (Msg-uri msg))]
98 [mentions (Msg-mentions msg)])
101 (let ([nick (if nick nick uri)])
102 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
104 ([date-display-format 'iso-8601])
105 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
108 (let ([nick (if nick (string-append nick " ") "")])
109 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
111 ([date-display-format 'rfc2822])
112 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
114 nick uri color text))])))))
116 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
117 (define rfc3339->epoch
118 (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}))?$")])
120 (match (regexp-match re ts)
121 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
124 (match* (tz-whole tz-sign tz-HH tz-MM)
127 [(_ (or "-" "+") (? identity h) (? identity m))
128 (let ([h (string->number h)]
129 [m (string->number m)]
130 ; Reverse to get back to UTC:
131 [op (match tz-sign ["+" -] ["-" +])])
132 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
134 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
138 [ts-epoch (find-seconds (if SS (string->number SS) 0)
143 (string->number yyyy)
145 (+ ts-epoch tz-offset))]
147 (log-error "Invalid timestamp: ~v" ts)
150 (: str->msg (-> (Option String) Url String (Option Msg)))
152 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
158 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
159 str nick (url->string uri) e)
161 (match (regexp-match re str)
162 [(list _wholething ts-orig text)
163 (let ([ts-epoch (rfc3339->epoch ts-orig)])
167 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
168 [(list _wholething nick-uri)
169 (str->peer nick-uri)]))
170 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
171 (Msg ts-epoch ts-orig nick uri text mentions))
174 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
175 str nick (url->string uri))
178 (log-debug "Non-msg line from nick:~v, line:~a" nick str)
182 ; TODO Test for when missing-nick case
183 (let* ([tzs (for*/list ([d '("-" "+")]
185 [m '("00" ":00" "57" ":57")])
186 (string-append d h m))]
187 [tzs (list* "" "Z" tzs)])
188 (for* ([n '("fake-nick")]
193 [sep (list "\t" " ")]
194 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
195 (let* ([ts (string-append "2020-11-18T22:22"
196 (if (non-empty-string? s) s ":00")
198 [m (str->msg n u (string-append ts sep txt))])
200 (check-equal? (Msg-nick m) n)
201 (check-equal? (Msg-uri m) u)
202 (check-equal? (Msg-text m) txt)
203 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
206 (let* ([ts "2020-11-18T22:22:09-0500"]
211 [actual (str->msg nick uri (string-append ts tab text))]
212 [expected (Msg 1605756129 ts nick uri text)])
214 (Msg-ts-epoch actual)
215 (Msg-ts-epoch expected)
219 (Msg-ts-orig expected)
234 (: str->lines (-> String (Listof String)))
235 (define (str->lines str)
236 (string-split str (regexp "[\r\n]+")))
239 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
241 (: str->msgs (-> (Option String) Url String (Listof Msg)))
242 (define (str->msgs nick uri str)
243 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
245 (: cache-dir Path-String)
246 (define cache-dir (build-path tt-home-dir "cache"))
248 (define cache-object-dir (build-path cache-dir "objects"))
250 (: url->cache-file-path-v1 (-> Url Path-String))
251 (define (url->cache-file-path-v1 uri)
252 (define (hash-sha1 str) : (-> String String)
253 (define in (open-input-string str))
254 (define digest (sha1 in))
255 (close-input-port in)
257 (build-path cache-object-dir (hash-sha1 (url->string uri))))
259 (: url->cache-file-path-v2 (-> Url Path-String))
260 (define (url->cache-file-path-v2 uri)
261 (build-path cache-object-dir (uri-encode (url->string uri))))
263 (define url->cache-object-path url->cache-file-path-v2)
265 (define (url->cache-etag-path uri)
266 (build-path cache-dir "etags" (uri-encode (url->string uri))))
268 (define (url->cache-lmod-path uri)
269 (build-path cache-dir "lmods" (uri-encode (url->string uri))))
272 (: uri-read-cached (-> Url String))
273 (define (uri-read-cached uri)
274 (define path-v1 (url->cache-file-path-v1 uri))
275 (define path-v2 (url->cache-file-path-v2 uri))
276 (when (file-exists? path-v1)
277 (rename-file-or-directory path-v1 path-v2 #t))
278 (if (file-exists? path-v2)
279 (file->string path-v2)
281 (log-warning "Cache file not found for URI: ~a" (url->string uri))
284 (: str->peer (String (Option Peer)))
285 (define (str->peer str)
286 (log-debug "Parsing peer string: ~v" str)
290 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
292 (match (string-split str)
293 [(list u) (Peer #f (string->url u))]
294 [(list n u) (Peer n (string->url u))]
296 (log-error "Invalid peer string: ~v" str)
300 (: filter-comments (-> (Listof String) (Listof String)))
301 (define (filter-comments lines)
302 (filter-not (λ (line) (string-prefix? line "#")) lines))
304 (: str->peers (-> String (Listof Peer)))
305 (define (str->peers str)
306 (filter-map str->peer (filter-comments (str->lines str))))
308 (: file->peers (-> Path-String (Listof Peer)))
309 (define (file->peers file-path)
310 (if (file-exists? file-path)
311 (str->peers (file->string file-path))
313 (log-error "File does not exist: ~v" (path->string file-path))
316 (: user-agent String)
320 [prog-version (info:#%info-lookup 'version)]
321 [prog-uri "https://github.com/xandkar/tt"]
322 [user-peer-file (build-path tt-home-dir "me")]
324 (if (file-exists? user-peer-file)
325 (match (first (file->peers user-peer-file))
326 [(Peer #f u) (format "+~a" (url->string u) )]
327 [(Peer n u) (format "+~a; @~a" (url->string u) n)])
328 (format "+~a" prog-uri))])
329 (format "~a/~a (~a)" prog-name prog-version user)))
331 (: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
332 (define (header-get headers name)
333 (match (filter-map (curry extract-field name) headers)
337 (: uri-download (-> Url Void))
338 (define (uri-download u)
339 (define cached-object-path (url->cache-object-path u))
340 (define cached-etag-path (url->cache-etag-path u))
341 (define cached-lmod-path (url->cache-lmod-path u))
342 (log-debug "uri-download ~v into ~v" u cached-object-path)
343 (match* ((url-scheme u) (url-host u) (url-port u))
346 (define ssl? (string=? s "https"))
347 (define-values (status-line headers body-input)
348 ; TODO Timeout. Currently hangs on slow connections.
351 (url->string (struct-copy url u [scheme #f] [host #f]))
353 #:port (cond [p p] [ssl? 443] [else 80])
354 #:headers (list (format "User-Agent: ~a" user-agent))))
355 (log-debug "headers: ~v" headers)
356 (log-debug "status-line: ~v" status-line)
358 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
359 (log-debug "status: ~v" status)
360 ; TODO Handle redirects
363 (let ([etag (header-get headers #"ETag")]
364 [lmod (header-get headers #"Last-Modified")])
366 (file-exists? cached-etag-path)
367 (bytes=? etag (file->bytes cached-etag-path)))
368 (log-info "ETags match, skipping the rest of ~v" (url->string u))
371 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
372 (url->string u) etag lmod)
373 (make-parent-directory* cached-object-path)
374 (make-parent-directory* cached-etag-path)
375 (make-parent-directory* cached-lmod-path)
376 (call-with-output-file cached-object-path
377 (curry copy-port body-input)
380 (display-to-file etag cached-etag-path #:exists 'replace))
382 (display-to-file etag cached-lmod-path #:exists 'replace))))
383 (close-input-port body-input))]
387 (log-error "Invalid URI: ~v" u)]))
389 (: timeline-print (-> Out-Format (Listof Msg) Void))
390 (define (timeline-print out-format timeline)
391 (void (foldl (match-lambda**
392 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
393 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
394 (msg-print out-format i m)
399 (: peer->msgs (-> Peer (Listof Msg)))
400 (define (peer->msgs f)
401 (match-define (Peer nick uri) f)
402 (log-info "Reading peer nick:~v uri:~v" nick (url->string uri))
403 (str->msgs nick uri (uri-read-cached uri)))
405 (: peer-download (-> Peer Void))
406 (define (peer-download f)
407 (match-define (Peer nick uri) f)
408 (define u (url->string uri))
409 (log-info "Downloading peer uri:~a" u)
413 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
417 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
419 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
420 (time-apply uri-download (list uri)))
421 (log-info "Peer downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
423 (: timeline-download (-> Integer (Listof Peer) Void))
424 (define (timeline-download num-workers peers)
425 ; TODO No need for map - can just iter
426 (void (concurrent-filter-map num-workers peer-download peers)))
428 ; TODO timeline contract : time-sorted list of messages
429 (: timeline-read (-> Timeline-Order (Listof Peer) (Listof Msg)))
430 (define (timeline-read order peers)
431 (define cmp (match order
434 (sort (append* (filter-map peer->msgs peers))
435 (λ (a b) (cmp (Msg-ts-epoch a) (Msg-ts-epoch b)))))
437 (: paths->peers (-> (Listof String) (Listof Peer)))
438 (define (paths->peers paths)
439 (let* ([paths (match paths
441 (let ([peer-refs-file (build-path tt-home-dir "peers")])
443 "No peer ref file paths provided, defaulting to ~v"
444 (path->string peer-refs-file))
445 (list peer-refs-file))]
447 (log-debug "Peer ref file paths provided: ~v" paths)
448 (map string->path paths)])]
449 [peers (append* (map file->peers paths))])
450 (log-info "Read-in ~a peers." (length peers))
453 (: log-writer-stop (-> Thread Void))
454 (define (log-writer-stop log-writer)
455 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
456 (thread-wait log-writer))
458 (: log-writer-start (-> Log-Level Thread))
459 (define (log-writer-start level)
461 (make-logger #f #f level #f)]
463 (make-log-receiver logger level)]
468 ([date-display-format 'iso-8601])
470 (match-define (vector level msg _ topic) (sync log-receiver))
471 (unless (equal? topic 'stop)
472 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
474 (current-logger logger)
478 (let ([log-level 'info])
484 "Enable debug log level."
485 (set! log-level 'debug)]
488 "and <command> is one of"
489 "r, read i : Read the timeline."
490 "d, download : Download the timeline."
491 ; TODO Add path dynamically
492 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
494 #:args (command . args)
495 (define log-writer (log-writer-start log-level))
496 (current-command-line-arguments (list->vector args))
499 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
500 ; started noticing significant slowdowns. Reducing to 5 seems to help.
501 (let ([num-workers 5])
507 njobs "Number of concurrent jobs."
508 (set! num-workers (string->number njobs))]
510 (define-values (_res _cpu real-ms _gc)
511 (time-apply timeline-download (list num-workers (paths->peers file-paths))))
512 (log-info "Timeline downloaded in ~a seconds." (/ real-ms 1000.0))))]
518 (if (system (path->string (build-path tt-home-dir "upload")))
522 (let ([out-format 'multi-line]
529 "Reverse displayed timeline order."
530 (set! order 'new->old)]
533 "Short output format"
534 (set! out-format 'single-line)]
537 (set! out-format 'multi-line)]
539 (timeline-print out-format (timeline-read order (paths->peers file-paths)))))])
540 (log-writer-stop log-writer))))