-(: uri-download (-> Url Void))
-(define (uri-download u)
- (define cache-file-path (url->cache-file-path u))
- (log-debug "uri-download ~v into ~v" u cache-file-path)
- (match* ((url-scheme u) (url-host u) (url-port u))
- [(s h p)
- #:when (and s h)
- (define ssl? (string=? s "https"))
- (define-values (status-line headers body-input)
- ; TODO Timeout. Currently hangs on slow connections.
- (http-sendrecv
- h
- (url->string (struct-copy url u [scheme #f] [host #f]))
- #:ssl? ssl?
- #:port (cond [p p] [ssl? 443] [else 80])
- #:headers (list (format "User-Agent: ~a" user-agent))
- ))
+(: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
+(define (header-get headers name)
+ (match (filter-map (curry extract-field name) headers)
+ [(list val) val]
+ [_ #f]))
+
+(: uri-download (-> Positive-Float Url Void))
+(define (uri-download timeout u)
+ (define cached-object-path (url->cache-object-path u))
+ (define cached-etag-path (url->cache-etag-path u))
+ (define cached-lmod-path (url->cache-lmod-path u))
+ (define u-str (url->string u))
+ (log-debug "uri-download ~v into ~v" u-str cached-object-path)
+ (define timeout-chan (make-channel))
+ (define result-chan (make-channel))
+ (define timeout-thread
+ (thread (λ ()
+ ; Doing this instead of sync/timeout to distinguish error values,
+ ; rather than just have #f to work with.
+ (sleep timeout)
+ (channel-put timeout-chan (cons 'error 'timeout)))))
+ (define result-thread
+ (thread (λ ()
+ ; XXX We timeout getting a response, but body download could
+ ; also take a long time and we might want to time that out as
+ ; well, but then we may end-up with partially downloaded
+ ; objects. But that could happen anyway if the server drops the
+ ; connection for whatever reason.
+ ;
+ ; Maybe that is OK once we start treating the
+ ; downloaded object as an addition to the stored set of
+ ; messages, rather than the final set of messages.
+
+ ; TODO message db
+ ; - 1st try can just be an in-memory set that gets written-to
+ ; and read-from disk as a whole.
+ (define result
+ (with-handlers
+ ([exn:fail? (λ (e) (cons 'error (cons 'net-error e)))])
+ (define-values (status-line headers body-input)
+ (http-sendrecv/url
+ u
+ #:headers (list (format "User-Agent: ~a" user-agent))))
+ (cons 'ok (Resp status-line headers body-input))))
+ (channel-put result-chan result))))
+ (define result
+ (sync timeout-chan
+ result-chan))
+ (kill-thread result-thread)
+ (kill-thread timeout-thread)
+ (match result
+ [(cons 'error 'timeout)
+ (log-error "Download failed: timeout. URL:~v" u-str)]
+ [(cons 'error (cons 'net-error e))
+ (log-error "Download failed. Network error. URL:~v EXN:~v" u-str e)]
+ [(cons 'ok (Resp status-line headers body-input))