Fetch tomorow

This commit is contained in:
2026-09-09 18:01:56 +02:00
parent 8de68da1d3
commit 84f064abd8
2 changed files with 51 additions and 9 deletions
@@ -13,7 +13,10 @@
(java.sql (java.sql
Timestamp) Timestamp)
(java.time (java.time
Duration
Instant
LocalDate LocalDate
LocalTime
ZoneId) ZoneId)
(java.time.format (java.time.format
DateTimeFormatter))) DateTimeFormatter)))
@@ -125,11 +128,49 @@
(get-prices-for-date query-fn (.plusDays (LocalDate/now dk-zone) 1) "DK1")) (get-prices-for-date query-fn (.plusDays (LocalDate/now dk-zone) 1) "DK1"))
(def ^:private tomorrow-published-at
"Day-ahead prices for tomorrow are published around 13:00 CET."
(LocalTime/of 13 0))
(defn- tomorrow-available?
"True once tomorrow's prices are expected to be published."
[]
(not (.isBefore (LocalTime/now dk-zone) tomorrow-published-at)))
(def ^:private retry-interval
"Minimum wait between fetches when the API has nothing new yet."
(Duration/ofMinutes 15))
(defonce ^:private last-fetch-attempt (atom nil))
(defn- retry-due?
"True when enough time has passed since the last fetch attempt."
[]
(let [last @last-fetch-attempt]
(or (nil? last)
(>= (.compareTo (Duration/between last (Instant/now)) retry-interval) 0))))
(defn ensure-current-prices! (defn ensure-current-prices!
"Fetch prices only when today's DK1 prices are missing from the database." "Fetch prices when today's DK1 prices are missing, or - after 13:00 - when
tomorrow's are still missing."
[query-fn] [query-fn]
(if (seq (get-today-prices query-fn)) (cond
(empty? (get-today-prices query-fn))
(do (reset! last-fetch-attempt (Instant/now))
(fetch-and-save! query-fn))
(and (tomorrow-available?)
(empty? (get-tomorrow-prices query-fn))
(retry-due?))
(do (reset! last-fetch-attempt (Instant/now))
(fetch-and-save! query-fn))
:else
(do (do
(log/info "Day-ahead prices already exist; skipping API fetch") (log/info "Day-ahead prices already exist; skipping API fetch")
nil) nil)))
(fetch-and-save! query-fn)))
+6 -5
View File
@@ -47,11 +47,12 @@
rows (elprice/get-or-fetch! query-fn d)] rows (elprice/get-or-fetch! query-fn d)]
(http-response/ok (http-response/ok
{:date date {:date date
:prices (mapv (fn [r] {:time_dk (str (:time_dk r)) :prices (mapv (fn [r]
:price_area (:price_area r) {:time_dk (str (:time_dk r))
:price_dkk (:price_dkk r) :price_area (:price_area r)
:tariff_dkk (:tariff_dkk r) :price_dkk (:price_dkk r)
:total_dkk (:total_dkk r)}) :tariff_dkk (:tariff_dkk r)
:total_dkk (:total_dkk r)})
rows)})) rows)}))
(catch DateTimeParseException _ (catch DateTimeParseException _
(http-response/bad-request {:error "date must be YYYY-MM-DD"})))) (http-response/bad-request {:error "date must be YYYY-MM-DD"}))))