Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix(currency): skip an exchange rate refresh that already happened today (#1199)
thorstenhornung154f822b0e6ec
diff --git a/endpoints/cronjobs/updateexchange.php b/endpoints/cronjobs/updateexchange.phpindex 5c26bb2..e1bd456 100644--- a/endpoints/cronjobs/updateexchange.php+++ b/endpoints/cronjobs/updateexchange.php@@ -1,6 +1,7 @@<?phprequire_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';+require_once __DIR__ . '/../../includes/exchange_rate_freshness.php';require 'settimezone.php';@@ -19,6 +20,15 @@ while ($userToUpdateExchange = $usersToUpdateExchange->fetchArray(SQLITE3_ASSOC)$userId = $userToUpdateExchange['id'];echo "For user: " . $userToUpdateExchange['username'] . "<br />";+ // Asked before anything is read or fetched. This job also runs on every+ // container start, so without this a deploy costs one provider request per+ // account, and a free plan's monthly allowance goes on refreshing rates+ // that were already current.+ if (wallos_rates_refreshed_today($db, $userId)) {+ echo "Rates are already current today.<br />";+ continue;+ }+$query = "SELECT api_key, provider FROM fixer WHERE user_id = :userId";$stmt = $db->prepare($query);$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);diff --git a/endpoints/currency/update_exchange.php b/endpoints/currency/update_exchange.phpindex 742965d..1fb0c03 100644--- a/endpoints/currency/update_exchange.php+++ b/endpoints/currency/update_exchange.php@@ -1,24 +1,18 @@<?phprequire_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint.php';+require_once '../../includes/exchange_rate_freshness.php';$shouldUpdate = true;if (isset($_POST['force']) && $_POST['force'] === "true") {$shouldUpdate = true;} else {- $query = "SELECT date FROM last_exchange_update WHERE user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- if ($result) {- $lastUpdateDate = new DateTime($result);- $currentDate = new DateTime();- $lastUpdateDateString = $lastUpdateDate->format('Y-m-d');- $currentDateString = $currentDate->format('Y-m-d');- $shouldUpdate = $lastUpdateDateString < $currentDateString;- }+ // This branch could not run. It built a DateTime out of the SQLite3Result+ // rather than out of a value fetched from it, which on PHP 8 is a+ // TypeError and a fatal, and it went unnoticed because the interface only+ // ever posts force=true, so nothing has reached it.+ $shouldUpdate = !wallos_rates_refreshed_today($db, $userId);if (!$shouldUpdate) {echo "Rates are current, no need to update.";diff --git a/includes/exchange_rate_freshness.php b/includes/exchange_rate_freshness.phpnew file mode 100644index 0000000..4abc7df--- /dev/null+++ b/includes/exchange_rate_freshness.php@@ -0,0 +1,44 @@+<?php++/**+ * Whether this account's exchange rates were already refreshed today.+ *+ * The scheduled job runs daily and again on every container start, and the+ * provider is asked once per account with a key. Without this, a deploy costs+ * one request per account, and on a free plan that is how a month's allowance+ * disappears in a fortnight. What the user sees then is not an error: the rates+ * simply stop moving, and nothing on any screen says why.+ *+ * The date read here is the one updateexchange.php writes after a refresh that+ * succeeded, so a run that failed is retried rather than skipped.+ *+ * Deliberately a comparison of two Y-m-d strings rather than of DateTime+ * objects. That is how the value is stored, it is the comparison the manual+ * endpoint was written to make, and it needs no object built from a value that+ * might be missing.+ *+ * @param SQLite3 $db+ * @param int $userId+ * @return bool false whenever the answer is not certain, so an uncertain case+ * refreshes rather than silently skipping+ */+function wallos_rates_refreshed_today($db, $userId)+{+ $statement = $db->prepare('SELECT date FROM last_exchange_update WHERE user_id = :userId');++ if ($statement === false) {+ return false;+ }++ $statement->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $statement->execute();++ if ($result === false) {+ return false;+ }++ $row = $result->fetchArray(SQLITE3_ASSOC);++ return $row !== false && !empty($row['date'])+ && $row['date'] >= (new DateTime())->format('Y-m-d');+}diff --git a/tests/cases/rate_freshness_test.php b/tests/cases/rate_freshness_test.phpnew file mode 100644index 0000000..da6b955--- /dev/null+++ b/tests/cases/rate_freshness_test.php@@ -0,0 +1,92 @@+<?php+/*+ Rates fetched today are not fetched again.++ The scheduled job runs daily and again on every container start, and asks the+ provider once per account with a key. Without a freshness check a deploy costs+ one request per account, and on a free monthly allowance that is how the+ rates quietly stop moving halfway through a month, with nothing on any screen+ saying why.++ The check already existed in the manual endpoint and could not run: it built a+ DateTime out of the SQLite3Result rather than out of a value fetched from it,+ which on PHP 8 is a TypeError. Nothing reached it because the interface only+ ever posts force=true, so the defect sat behind a branch nobody took.+*/++require_once WALLOS_ROOT . '/includes/exchange_rate_freshness.php';++/**+ * @param SQLite3 $db+ * @param int $userId+ * @param string $date+ */+function freshness_record($db, $userId, $date)+{+ $statement = $db->prepare('INSERT INTO last_exchange_update (date, user_id) VALUES (:date, :userId)');+ $statement->bindValue(':date', $date, SQLITE3_TEXT);+ $statement->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $statement->execute();+}++wallos_test('a refresh from today counts and one from yesterday does not', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ wallos_test_create_user($db, 2, 'bob');++ freshness_record($db, 1, (new DateTime())->format('Y-m-d'));+ freshness_record($db, 2, (new DateTime('-1 day'))->format('Y-m-d'));++ assert_true(wallos_rates_refreshed_today($db, 1), 'today is current');+ assert_true(wallos_rates_refreshed_today($db, 2) === false, 'yesterday is not');++ $db->close();+});++wallos_test('an account that never refreshed is not current', function () {+ // The case a deploy hits on a fresh installation, and the one where+ // answering "current" would leave every rate at its seeded value forever.+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ assert_true(wallos_rates_refreshed_today($db, 1) === false,+ 'no row means no refresh, so it is due');++ $db->close();+});++wallos_test('an unreadable answer refreshes rather than skipping', function () {+ // The direction of the uncertainty is the decision here. Skipping on doubt+ // stops the rates silently; refreshing on doubt costs one request. Only one+ // of those two is noticed.+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ freshness_record($db, 1, '');++ assert_true(wallos_rates_refreshed_today($db, 1) === false,+ 'an empty date is not a refresh');++ $db->close();+});++wallos_test('both refresh paths ask before they fetch', function () {+ // The scheduled job had no check at all, and the manual one had a check it+ // could not reach. A guard on both, because one of them running unchecked+ // is the whole cost.+ foreach ([+ 'endpoints/cronjobs/updateexchange.php',+ 'endpoints/currency/update_exchange.php',+ ] as $path) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $path);++ assert_contains('wallos_rates_refreshed_today($db, $userId)', $source,+ $path . ' asks whether the rates are already current');+ assert_contains('exchange_rate_freshness.php', $source,+ $path . ' includes the helper that answers it');+ }++ // And the shape that could never run does not come back.+ $manual = file_get_contents(WALLOS_ROOT . '/endpoints/currency/update_exchange.php');+ assert_true(strpos($manual, 'new DateTime($result)') === false,+ 'no DateTime is built out of a result set');+});