           first-redirect (second redirects)
           last-redirect (last redirects)
           ok (= 200 (:status result))]
+          (locking *out* (prn "Finish resolve" doi ok))
           (when ok
             [first-redirect last-redirect]))
     (catch Exception _ nil)))

  (:require [clojure.core.async :as async :refer [<! <!! >!! >! go chan close! merge]]))

(def doi-channel (chan))
(def dois-resolved-channel (chan))

(def issued-type-id (data/get-type-id-by-name "issued"))
(def resolved-type-id (data/get-type-id-by-name "first-resolution-test"))
(def source-id (data/get-source-id-by-name "CrossRefRobot"))

(defn get-resolutions
  "Get the first and last redirects or nil if it doesn't exist."
  [doi]
  (try 
    (let [url (crdoi/normalise-doi doi)
          result (try-try-again {:sleep 5000 :tries 2} #(client/get url
                                                         {:follow-redirects true

          resolve-channel (merge doi-resolve-channels)]
      
      ; Stick the DOIs on a channel for them to be resolved asynchronously and returned via doi-resolve-channels.
      (go
        (doseq [doi dois]
          (locking *out* (prn "Spool" doi))
          (>! doi-channel doi))
        (prn "Closing DOI channel")
        (close! doi-channel))
            
      ; Get resolutions from the merged doi-resolve-channel and insert them.
      ; TODO maybe batch into transactions?
      (loop [resolution (<!! resolve-channel)]
        (when resolution
          (let [[doi first-redirect last-redirect] resolution]
            (insert-resolutions doi first-redirect last-redirect))
          (recur (<!! resolve-channel)))))))
