1 #lang typed/racket/no-check
11 (require (prefix-in info: "info.rkt"))
19 (define-type Out-Format
23 (define-type Timeline-Order
30 [nick : (Option String)]
33 [mentions : (Listof Peer)]))
36 ([nick : (Option String)]
40 (: tt-home-dir Path-String)
41 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
43 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
44 (define (concurrent-filter-map num-workers f xs)
45 ; TODO preserve order of elements OR communicate that reorder is expected
46 ; TODO switch from mailboxes to channels
47 (define (make-worker id f)
48 (define parent (current-thread))
50 (define self : Thread (current-thread))
51 (: work (∀ (α) (-> α)))
53 (thread-send parent (cons 'next self))
54 (match (thread-receive)
55 ['done (thread-send parent (cons 'exit id))]
56 [(cons 'unit x) (begin
58 (when y (thread-send parent (cons 'result y)))
61 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
62 (define (dispatch ws xs ys)
65 (match (thread-receive)
66 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
67 [(cons 'result y) (dispatch ws xs (cons y ys))]
68 [(cons 'next thd) (match xs
70 (thread-send thd 'done)
73 (thread-send thd (cons 'unit x))
74 (dispatch ws xs ys))])])))
75 (define workers (range num-workers))
76 (define threads (map (λ (id) (thread (make-worker id f))) workers))
77 (define results (dispatch workers xs '()))
78 (for-each thread-wait threads)
82 (let* ([f (λ (x) (if (even? x) x #f))]
84 [actual (sort (concurrent-filter-map 10 f xs) <)]
85 [expected (sort ( filter-map f xs) <)])
86 (check-equal? actual expected "concurrent-filter-map")))
88 (: msg-print (-> Out-Format Integer Msg Void))
90 (let* ([colors (vector 36 33)]
91 [n (vector-length colors)])
92 (λ (out-format color-i msg)
93 (let ([color (vector-ref colors (modulo color-i n))]
95 [uri (url->string (Msg-uri msg))]
97 [mentions (Msg-mentions msg)])
100 (let ([nick (if nick nick uri)])
101 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
103 ([date-display-format 'iso-8601])
104 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
107 (let ([nick (if nick (string-append nick " ") "")])
108 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
110 ([date-display-format 'rfc2822])
111 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
113 nick uri color text))])))))
115 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
116 (define rfc3339->epoch
117 (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}))?$")])
119 (match (regexp-match re ts)
120 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
123 (match* (tz-whole tz-sign tz-HH tz-MM)
126 [(_ (or "-" "+") (? identity h) (? identity m))
127 (let ([h (string->number h)]
128 [m (string->number m)]
129 ; Reverse to get back to UTC:
130 [op (match tz-sign ["+" -] ["-" +])])
131 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
133 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
137 [ts-epoch (find-seconds (if SS (string->number SS) 0)
142 (string->number yyyy)
144 (+ ts-epoch tz-offset))]
146 (log-error "Invalid timestamp: ~v" ts)
149 (: str->msg (-> (Option String) Url String (Option Msg)))
151 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
157 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
158 str nick (url->string uri) e)
160 (match (regexp-match re str)
161 [(list _wholething ts-orig text)
162 (let ([ts-epoch (rfc3339->epoch ts-orig)])
166 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
167 [(list _wholething nick-uri)
168 (str->peer nick-uri)]))
169 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
170 (Msg ts-epoch ts-orig nick uri text mentions))
173 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
174 str nick (url->string uri))
177 (log-debug "Non-msg line from nick:~v, line:~a" nick str)
181 ; TODO Test for when missing-nick case
182 (let* ([tzs (for*/list ([d '("-" "+")]
184 [m '("00" ":00" "57" ":57")])
185 (string-append d h m))]
186 [tzs (list* "" "Z" tzs)])
187 (for* ([n '("fake-nick")]
192 [sep (list "\t" " ")]
193 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
194 (let* ([ts (string-append "2020-11-18T22:22"
195 (if (non-empty-string? s) s ":00")
197 [m (str->msg n u (string-append ts sep txt))])
199 (check-equal? (Msg-nick m) n)
200 (check-equal? (Msg-uri m) u)
201 (check-equal? (Msg-text m) txt)
202 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
205 (let* ([ts "2020-11-18T22:22:09-0500"]
210 [actual (str->msg nick uri (string-append ts tab text))]
211 [expected (Msg 1605756129 ts nick uri text)])
213 (Msg-ts-epoch actual)
214 (Msg-ts-epoch expected)
218 (Msg-ts-orig expected)
233 (: str->lines (-> String (Listof String)))
234 (define (str->lines str)
235 (string-split str (regexp "[\r\n]+")))
238 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
240 (: str->msgs (-> (Option String) Url String (Listof Msg)))
241 (define (str->msgs nick uri str)
242 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
244 (: cache-dir Path-String)
245 (define cache-dir (build-path tt-home-dir "cache"))
247 (: url->cache-file-path-v1 (-> Url Path-String))
248 (define (url->cache-file-path-v1 uri)
249 (define (hash-sha1 str) : (-> String String)
250 (define in (open-input-string str))
251 (define digest (sha1 in))
252 (close-input-port in)
254 (build-path cache-dir (hash-sha1 (url->string uri))))
256 (: url->cache-file-path-v2 (-> Url Path-String))
257 (define (url->cache-file-path-v2 uri)
258 (build-path cache-dir (uri-encode (url->string uri))))
260 (define url->cache-file-path url->cache-file-path-v2)
263 (: uri-read-cached (-> Url String))
264 (define (uri-read-cached uri)
265 (define path-v1 (url->cache-file-path-v1 uri))
266 (define path-v2 (url->cache-file-path-v2 uri))
267 (when (file-exists? path-v1)
268 (rename-file-or-directory path-v1 path-v2 #t))
269 (if (file-exists? path-v2)
270 (file->string path-v2)
272 (log-warning "Cache file not found for URI: ~a" (url->string uri))
275 (: str->peer (String (Option Peer)))
276 (define (str->peer str)
277 (log-debug "Parsing peer string: ~v" str)
281 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
283 (match (string-split str)
284 [(list u) (Peer #f (string->url u))]
285 [(list n u) (Peer n (string->url u))]
287 (log-error "Invalid peer string: ~v" str)
291 (: filter-comments (-> (Listof String) (Listof String)))
292 (define (filter-comments lines)
293 (filter-not (λ (line) (string-prefix? line "#")) lines))
295 (: str->peers (-> String (Listof Peer)))
296 (define (str->peers str)
297 (filter-map str->peer (filter-comments (str->lines str))))
299 (: file->peers (-> Path-String (Listof Peer)))
300 (define (file->peers file-path)
301 (if (file-exists? file-path)
302 (str->peers (file->string file-path))
304 (log-error "File does not exist: ~v" (path->string file-path))
307 (: user-agent String)
311 [prog-version (info:#%info-lookup 'version)]
312 [prog-uri "https://github.com/xandkar/tt"]
313 [user-peer-file (build-path tt-home-dir "me")]
315 (if (file-exists? user-peer-file)
316 (match (first (file->peers user-peer-file))
317 [(Peer #f u) (format "+~a" (url->string u) )]
318 [(Peer n u) (format "+~a; @~a" (url->string u) n)])
319 (format "+~a" prog-uri))])
320 (format "~a/~a (~a)" prog-name prog-version user)))
322 (: uri-download (-> Url Void))
323 (define (uri-download u)
324 (define cache-file-path (url->cache-file-path u))
325 (log-debug "uri-download ~v into ~v" u cache-file-path)
326 (match* ((url-scheme u) (url-host u) (url-port u))
329 (define ssl? (string=? s "https"))
330 (define-values (status-line headers body-input)
331 ; TODO Timeout. Currently hangs on slow connections.
334 (url->string (struct-copy url u [scheme #f] [host #f]))
336 #:port (cond [p p] [ssl? 443] [else 80])
337 #:headers (list (format "User-Agent: ~a" user-agent))
339 (log-debug "headers: ~v" headers)
340 (log-debug "status-line: ~v" status-line)
342 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
343 (log-debug "status: ~v" status)
344 ; TODO Handle redirects
347 (make-parent-directory* cache-file-path)
348 (call-with-output-file cache-file-path
349 (curry copy-port body-input)
353 (log-error "Invalid URI: ~v" u)]))
355 (: timeline-print (-> Out-Format (Listof Msg) Void))
356 (define (timeline-print out-format timeline)
357 (void (foldl (match-lambda**
358 [((and m (Msg _ _ nick _ _ _)) (cons prev-nick i))
359 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
360 (msg-print out-format i m)
365 (: peer->msgs (-> Peer (Listof Msg)))
366 (define (peer->msgs f)
367 (match-define (Peer nick uri) f)
368 (log-info "Reading peer nick:~v uri:~v" nick (url->string uri))
369 (str->msgs nick uri (uri-read-cached uri)))
371 (: peer-download (-> Peer Void))
372 (define (peer-download f)
373 (match-define (Peer nick uri) f)
374 (define u (url->string uri))
375 (log-info "Downloading peer uri:~a" u)
379 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
383 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
385 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
386 (time-apply uri-download (list uri)))
387 (log-info "Peer downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
389 (: timeline-download (-> Integer (Listof Peer) Void))
390 (define (timeline-download num-workers peers)
391 ; TODO No need for map - can just iter
392 (void (concurrent-filter-map num-workers peer-download peers)))
394 ; TODO timeline contract : time-sorted list of messages
395 (: timeline-read (-> Timeline-Order (Listof Peer) (Listof Msg)))
396 (define (timeline-read order peers)
397 (define cmp (match order
400 (sort (append* (filter-map peer->msgs peers))
401 (λ (a b) (cmp (Msg-ts-epoch a) (Msg-ts-epoch b)))))
403 (: paths->peers (-> (Listof String) (Listof Peer)))
404 (define (paths->peers paths)
405 (let* ([paths (match paths
407 (let ([peer-refs-file (build-path tt-home-dir "peers")])
409 "No peer ref file paths provided, defaulting to ~v"
410 (path->string peer-refs-file))
411 (list peer-refs-file))]
413 (log-debug "Peer ref file paths provided: ~v" paths)
414 (map string->path paths)])]
415 [peers (append* (map file->peers paths))])
416 (log-info "Read-in ~a peers." (length peers))
419 (: log-writer-stop (-> Thread Void))
420 (define (log-writer-stop log-writer)
421 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
422 (thread-wait log-writer))
424 (: log-writer-start (-> Log-Level Thread))
425 (define (log-writer-start level)
427 (make-logger #f #f level #f)]
429 (make-log-receiver logger level)]
434 ([date-display-format 'iso-8601])
436 (match-define (vector level msg _ topic) (sync log-receiver))
437 (unless (equal? topic 'stop)
438 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
440 (current-logger logger)
444 (let ([log-level 'info])
450 "Enable debug log level."
451 (set! log-level 'debug)]
454 "and <command> is one of"
455 "r, read i : Read the timeline."
456 "d, download : Download the timeline."
457 ; TODO Add path dynamically
458 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
460 #:args (command . args)
461 (define log-writer (log-writer-start log-level))
462 (current-command-line-arguments (list->vector args))
465 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
466 ; started noticing significant slowdowns. Reducing to 5 seems to help.
467 (let ([num-workers 5])
473 njobs "Number of concurrent jobs."
474 (set! num-workers (string->number njobs))]
476 (define-values (_res _cpu real-ms _gc)
477 (time-apply timeline-download (list num-workers (paths->peers file-paths))))
478 (log-info "Timeline downloaded in ~a seconds." (/ real-ms 1000.0))))]
484 (if (system (path->string (build-path tt-home-dir "upload")))
488 (let ([out-format 'multi-line]
495 "Reverse displayed timeline order."
496 (set! order 'new->old)]
499 "Short output format"
500 (set! out-format 'single-line)]
503 (set! out-format 'multi-line)]
505 (timeline-print out-format (timeline-read order (paths->peers file-paths)))))])
506 (log-writer-stop log-writer))))