The personal finance app for everyone (by everyone)
Ruby
Push follow-ups: APNs 410 through the ledger, own settings section, recheck after morph (#5373)
Chris Knuteson1c2e9b7a0388
diff --git a/app/models/push_notification_test.rb b/app/models/push_notification_test.rbindex 0a9faa0d75..22366ca5c0 100644--- a/app/models/push_notification_test.rb+++ b/app/models/push_notification_test.rb@@ -95,6 +95,10 @@ class PushNotificationTest)endend+ if result == :gone+ subscription.invalidate_if_unchanged!+ result = :unregistered+ endrecord(request_id, push_subscription_id, result)rescue Apns::Client::TransientErrorrecord(request_id, push_subscription_id, :retrying)diff --git a/app/models/push_subscription.rb b/app/models/push_subscription.rbindex 1acf6a2705..510faed983 100644--- a/app/models/push_subscription.rb+++ b/app/models/push_subscription.rb@@ -75,19 +75,19 @@ class PushSubscription < ApplicationRecordraise PushDelivery::TransientError, e.messageend- # A response may arrive after the app has registered again. Only remove the- # exact registration sent, and respect APNs' invalidation timestamp when given.- # Destroy (not delete) so the subscription's ledger rows are cleaned up with- # it; a surviving row would claim against a parent that no longer exists.- def invalidate_if_unchanged!(response)- return unless response.status.to_i == 410-+ # APNs answers 410 with the moment the token stopped being valid. A device+ # that registered again after that moment keeps its row.+ def unregistered_by?(response)timestamp = response.body.is_a?(Hash) && response.body["timestamp"]- if timestamp- return unless timestamp.is_a?(Numeric) && timestamp.positive? && timestamp.finite?- return if last_registered_at.to_f * 1000 > timestamp- end+ return true unless timestamp++ timestamp.is_a?(Numeric) && timestamp.positive? && timestamp.finite? &&+ last_registered_at.to_f * 1000 <= timestamp+ end+ # A response may arrive after the app has registered again: only remove the+ # exact registration sent. Destroy (not delete) so its ledger rows go with it.+ def invalidate_if_unchanged!self.class.where(id: id, token: token, environment: environment,last_registered_at: last_registered_at).destroy_allenddiff --git a/app/models/push_subscription/delivery.rb b/app/models/push_subscription/delivery.rbindex 111e9d87e6..c55d5c962e 100644--- a/app/models/push_subscription/delivery.rb+++ b/app/models/push_subscription/delivery.rb@@ -18,14 +18,10 @@ class PushSubscription::Deliveryendrecord_failure(status)- if status == 410- @subscription.invalidate_if_unchanged!(response)- :unregistered- else- # BadDeviceToken can mean the environment is wrong. Preserve the record- # for diagnosis and renewal rather than deleting every 400 response.- :rejected- end+ # :gone leaves removing the subscription to the caller. BadDeviceToken can+ # mean the environment is wrong, so other errors preserve the record for+ # diagnosis and renewal.+ status == 410 && @subscription.unregistered_by?(response) ? :gone : :rejectedrescue Apns::Client::UnavailableError:skippedrescue Apns::Client::ConfigurationErrordiff --git a/app/views/settings/preferences/_push_notifications.html.erb b/app/views/settings/preferences/_push_notifications.html.erbnew file mode 100644index 0000000000..1f1981ed00--- /dev/null+++ b/app/views/settings/preferences/_push_notifications.html.erb@@ -0,0 +1,14 @@+<%= settings_section title: t("push_notifications.title"), subtitle: t("push_notifications.description") do %>+ <%= form_with url: settings_preferences_path, method: :patch,+ data: { controller: "auto-submit-form" } do %>+ <label for="user_push_budget_warnings_enabled" class="flex cursor-pointer items-center justify-between gap-4">+ <div class="text-sm space-y-1">+ <p class="font-medium text-primary"><%= t("push_notifications.budget_title") %></p>+ <p class="text-secondary"><%= t("push_notifications.budget_description") %></p>+ </div>+ <%= render DS::Toggle.new(id: "user_push_budget_warnings_enabled",+ name: "user[push_budget_warnings_enabled]", checked: @user.push_budget_warnings_enabled?,+ data: { auto_submit_form_target: "auto" }) %>+ </label>+ <% end %>+<% end %>diff --git a/app/views/settings/preferences/_web_push.html.erb b/app/views/settings/preferences/_web_push.html.erbindex 91c086501f..a9af9b42a7 100644--- a/app/views/settings/preferences/_web_push.html.erb+++ b/app/views/settings/preferences/_web_push.html.erb@@ -1,5 +1,7 @@<%= settings_section title: t("web_push.title"), subtitle: t("web_push.description") do %>- <div class="space-y-4"+ <%# Permanent: a save elsewhere on this page morphs it, and the morph would put+ back the server's "checking" placeholder over the controller's state. %>+ <div id="web-push-device" class="space-y-4" data-turbo-permanentdata-controller="web-push"data-web-push-public-key-value="<%= @web_push_public_key %>"data-web-push-registrations-value="<%= @web_push_registrations.to_json %>"@@ -19,17 +21,5 @@data: { action: "web-push#test", web_push_target: "test" }) %></div><p class="text-sm text-secondary"><%= t("web_push.session_notice") %></p>- <%= form_with url: settings_preferences_path, method: :patch,- data: { controller: "auto-submit-form" } do %>- <label for="user_push_budget_warnings_enabled" class="flex cursor-pointer items-center justify-between gap-4">- <div class="text-sm space-y-1">- <p class="font-medium text-primary"><%= t("web_push.budget_title") %></p>- <p class="text-secondary"><%= t("web_push.budget_description") %></p>- </div>- <%= render DS::Toggle.new(id: "user_push_budget_warnings_enabled",- name: "user[push_budget_warnings_enabled]", checked: @user.push_budget_warnings_enabled?,- data: { auto_submit_form_target: "auto" }) %>- </label>- <% end %></div><% end %>diff --git a/app/views/settings/preferences/show.html.erb b/app/views/settings/preferences/show.html.erbindex 2ea014fcb6..ceb13dd84b 100644--- a/app/views/settings/preferences/show.html.erb+++ b/app/views/settings/preferences/show.html.erb@@ -345,4 +345,5 @@<% if preview_features_enabled? %><%= render "web_push" %>+ <%= render "push_notifications" %><% end %>diff --git a/config/locales/views/push_notifications/en.yml b/config/locales/views/push_notifications/en.ymlnew file mode 100644index 0000000000..49578ed16b--- /dev/null+++ b/config/locales/views/push_notifications/en.yml@@ -0,0 +1,6 @@+en:+ push_notifications:+ budget_description: Also notify me when a budget category nears its limit. Over-budget alerts are always sent. Off by default.+ budget_title: Budget warnings+ description: Applies to every device you have enabled, browser and iOS.+ title: Push notificationsdiff --git a/config/locales/views/web_push/en.yml b/config/locales/views/web_push/en.ymlindex 9c2545e6b3..41a5d1803f 100644--- a/config/locales/views/web_push/en.yml+++ b/config/locales/views/web_push/en.yml@@ -8,8 +8,6 @@ en:preview: Previewsession_notice: Notifications stop when you sign out or your session expires after 30 days of inactivity. Open Sure regularly to keep your session active.ios_guidance: On iPhone or iPad, open Sure in Safari, choose Share → Add to Home Screen, then enable notifications from the installed app. Requires iOS or iPadOS 16.4 or later.- budget_title: Budget warnings- budget_description: Also notify me when a budget category nears its limit. Over-budget alerts are always sent. Off by default; applies to all my push devices, browser and iOS.notification:body: A new financial alert is available. Open Sure to review it.test_body: Your test notification has arrived. Open Sure to continue.diff --git a/docs/hosting/push-notifications.md b/docs/hosting/push-notifications.mdindex 6e19893c7b..2ea1bf68be 100644--- a/docs/hosting/push-notifications.md+++ b/docs/hosting/push-notifications.md@@ -161,8 +161,8 @@ Sure replaces the old row so queued jobs cannot reach the new account through itEvery channel uses one policy, `Insight#notifies?`: an enabled device receivesnew or materially resurfaced, high-priority active insights visible to thefamily, including over-budget `budget_at_risk` warnings. Enabling a device does-not send a backlog. **Budget warnings** is a per-user preference, off by-default, that adds the medium-priority near-limit `budget_at_risk` insights on+not send a backlog. **Budget warnings**, under **Push notifications** in+Preferences, is a per-user setting, off by default, that adds the medium-priority near-limit `budget_at_risk` insights onall of that user's push devices, browser and iOS. `budget_on_track` is lowpriority and never pushed. Existing financial generators and categorythresholds are unchanged.diff --git a/test/controllers/settings/preferences_controller_test.rb b/test/controllers/settings/preferences_controller_test.rbindex c6ad38c686..115b7f6fa9 100644--- a/test/controllers/settings/preferences_controller_test.rb+++ b/test/controllers/settings/preferences_controller_test.rb@@ -129,11 +129,14 @@ class Settings::PreferencesControllerTest < ActionDispatch::IntegrationTesttest "browser notification card is preview gated" doget settings_preferences_urlassert_select "[data-controller='web-push']", count: 0+ assert_select "input[name='user[push_budget_warnings_enabled]']", count: 0user = users(:family_admin)user.update!(preferences: user.preferences.merge("preview_features_enabled" => true))get settings_preferences_urlassert_select "[data-controller='web-push']", count: 1- assert_select "input[name='user[push_budget_warnings_enabled]']"+ # The opt in covers iOS too, so it is not part of the browser card.+ assert_select "#user_push_budget_warnings_enabled", count: 1+ assert_select "[data-controller='web-push'] input[name='user[push_budget_warnings_enabled]']", count: 0endtest "budget warnings default off and are saved only for this user" dodiff --git a/test/jobs/deliver_insight_notification_job_test.rb b/test/jobs/deliver_insight_notification_job_test.rbindex fd9acb9a06..2c2fbf6d14 100644--- a/test/jobs/deliver_insight_notification_job_test.rb+++ b/test/jobs/deliver_insight_notification_job_test.rb@@ -213,13 +213,30 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCaseresponse = stub(ok?: false, status: "410", body: { "reason" => "Unregistered" })Apns::Client.any_instance.stubs(:deliver).returns(response)- DeliverInsightNotificationJob.perform_now(push_delivery_id: delivery.id)+ # Called without perform_now's discard_on: the ledger, not a swallowed+ # RecordNotFound, finishes the attempt.+ DeliverInsightNotificationJob.new.perform(push_delivery_id: delivery.id)assert_not PushSubscription.exists?(@subscription.id)assert_not PushDelivery.exists?(delivery.id)assert_not PushDelivery.exists?(sibling.id)end+ test "a device that registers again while APNs answers 410 keeps its subscription" do+ delivery = record_delivery+ Apns::Client.any_instance.stubs(:deliver).with do |**_arguments|+ travel 1.second do+ PushSubscription.find(@subscription.id).update!(last_registered_at: Time.current)+ end+ true+ end.returns(stub(ok?: false, status: "410", body: {}))++ DeliverInsightNotificationJob.new.perform(push_delivery_id: delivery.id)++ assert PushSubscription.exists?(@subscription.id)+ assert_equal "rejected", delivery.reload.status+ end+test "self hosted mode records no apns rows and cannot execute a stale row" doRails.application.config.stubs(:app_mode).returns("self_hosted".inquiry)PushDelivery.record_for_insight!(@insight)diff --git a/test/models/push_notification_test_test.rb b/test/models/push_notification_test_test.rbindex 90f54530cc..f982a78069 100644--- a/test/models/push_notification_test_test.rb+++ b/test/models/push_notification_test_test.rb@@ -161,6 +161,14 @@ class PushNotificationTestTest < ActiveJob::TestCaseassert_nil PushNotificationTest.new(users(:family_admin)).latestend+ test "an unregistered device is removed and reported" do+ @test.request!+ Apns::Client.any_instance.stubs(:deliver_test).returns(stub(ok?: false, status: "410", body: { "reason" => "Unregistered" }))+ deliver+ assert_equal "unregistered", result_status+ assert_not PushSubscription.exists?(@subscription.id)+ end+test "transient errors retry without reporting success" do@test.request!Apns::Client.any_instance.stubs(:deliver_test).returns(stub(ok?: false, status: "503"))diff --git a/test/models/push_subscription/delivery_test.rb b/test/models/push_subscription/delivery_test.rbindex 0a288a93fd..3729be8f7f 100644--- a/test/models/push_subscription/delivery_test.rb+++ b/test/models/push_subscription/delivery_test.rb@@ -24,29 +24,24 @@ class PushSubscription::DeliveryTest < ActiveSupport::TestCaserefute_includes DebugLogEntry.last.metadata.to_json, @subscription.tokenend- test "invalidates an unchanged unregistered token" do- assert_difference "PushSubscription.count", -1 do- assert_equal :unregistered, deliver("410", { "timestamp" => Time.current.to_i * 1000 })- end- end-- test "a response predating registration cannot invalidate the token" do+ test "an unregistered token is reported gone and its removal left to the caller" doassert_no_difference "PushSubscription.count" do- deliver("410", { "timestamp" => 2.minutes.ago.to_i * 1000 })+ assert_equal :gone, deliver("410", { "timestamp" => Time.current.to_i * 1000 })endend- test "renewal while APNs is responding is preserved" do- original = @subscription- PushSubscription.find(original.id).update!(last_registered_at: Time.current)- assert_no_difference "PushSubscription.count" do- deliver("410", { "timestamp" => Time.current.to_i * 1000 })- end+ test "a response predating registration is a rejection, not an invalidation" do+ assert_equal :rejected, deliver("410", { "timestamp" => 2.minutes.ago.to_i * 1000 })endtest "malformed invalidation timestamp cannot remove a token" do+ assert_equal :rejected, deliver("410", { "timestamp" => "invalid" })+ end++ test "renewal while APNs is responding is preserved" do+ PushSubscription.find(@subscription.id).update!(last_registered_at: Time.current)assert_no_difference "PushSubscription.count" do- deliver("410", { "timestamp" => "invalid" })+ @subscription.invalidate_if_unchanged!endenddiff --git a/test/system/web_push_notifications_test.rb b/test/system/web_push_notifications_test.rbindex 752d7f494e..9957a9e6cc 100644--- a/test/system/web_push_notifications_test.rb+++ b/test/system/web_push_notifications_test.rb@@ -48,6 +48,20 @@ class WebPushNotificationsTest < ApplicationSystemTestCaseassert_empty @user.web_push_subscriptionsend+ test "saving another preference leaves the device card in its state" do+ visit settings_preferences_path+ install_browser_push_double(web_push_attributes)+ click_on I18n.t("web_push.enable")+ assert_text I18n.t("web_push.status.enabled")++ # The save redirects back and Turbo morphs the page.+ find("#user_push_budget_warnings_enabled + label").click+ assert_selector "#user_push_budget_warnings_enabled[checked]"+ assert_no_text I18n.t("web_push.status.checking")+ assert_text I18n.t("web_push.status.enabled")+ assert_selector "[data-web-push-target='test']:not([disabled])"+ end+privatedef capture_notification_cardcard = "[data-controller='web-push']"