A platform for community discussion. Free, open, simple.
DEV: Move upcoming change tracking and promotion out of initializers (#37283)
Martin Brennanb8672b3dfbca
diff --git a/app/jobs/scheduled/check_upcoming_changes.rb b/app/jobs/scheduled/check_upcoming_changes.rbnew file mode 100644index 00000000000..29739c19606--- /dev/null+++ b/app/jobs/scheduled/check_upcoming_changes.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++module Jobs+ class CheckUpcomingChanges < ::Jobs::Scheduled+ every 20.minutes++ def execute(args)+ return if !SiteSetting.enable_upcoming_changes++ site = RailsMultisite::ConnectionManagement.current_db+ verbose_log(+ site,+ :info,+ "Starting change tracker and promotion notifier for upcoming changes",+ )++ if SiteSetting.upcoming_change_site_settings.empty?+ verbose_log(site, :info, "No upcoming changes present.")+ return+ end++ DistributedMutex.synchronize("check_upcoming_changes_#{site}", validity: 10.minutes) do+ track_changes(site)+ notify_promotions(site)+ end+ end++ private++ def track_changes(site)+ UpcomingChanges::Track.call(guardian: Discourse.system_user.guardian) do |result|+ on_success do |added_changes:, removed_changes:, notified_admins_for_added_changes:, status_changes:|+ added_changes.each do |change_name|+ verbose_log(site, :info, "Added upcoming change '#{change_name}'")+ end++ notified_admins_for_added_changes.each do |change_name|+ verbose_log(+ site,+ :info,+ "Notified site admins about added upcoming change '#{change_name}'",+ )+ end++ removed_changes.each do |change_name|+ verbose_log(site, :info, "Removed upcoming change '#{change_name}'")+ end++ status_changes.each do |change_name, details|+ verbose_log(+ site,+ :info,+ "Status changed for upcoming change '#{change_name}' from #{details[:previous_value]} to #{details[:new_value]}",+ )+ end+ end++ on_failure do+ verbose_log(+ site,+ :error,+ "Failed to track upcoming changes, an unexpected error occurred.\n\n#{result.inspect_steps}",+ )+ end+ end+ end++ def notify_promotions(site)+ UpcomingChanges::NotifyPromotions.call(guardian: Discourse.system_user.guardian) do |result|+ on_success do |change_notification_statuses:|+ change_notification_statuses.each do |setting_name, status|+ if status[:success]+ verbose_log(site, :info, "Notified site admins about promotion of '#{setting_name}'")+ else+ verbose_log(+ site,+ :error,+ "Failed to notify about promotion of '#{setting_name}': #{status[:error]} with backtrace: #{status[:backtrace]&.join("\n") || "N/A"}",+ )+ end+ end+ end++ on_failure do+ verbose_log(+ site,+ :error,+ "Failed to notify about promotions, an unexpected error occurred.\n\n#{result.inspect_steps}",+ )+ end+ end+ end++ def verbose_log(site, level, message)+ return unless SiteSetting.upcoming_change_verbose_logging+ Rails.logger.public_send(level, "[CheckUpcomingChanges (#{site})] #{message}")+ end+ end+enddiff --git a/app/services/upcoming_changes/notify_promotion.rb b/app/services/upcoming_changes/notify_promotion.rbnew file mode 100644index 00000000000..29f3f7fad29--- /dev/null+++ b/app/services/upcoming_changes/notify_promotion.rb@@ -0,0 +1,108 @@+# frozen_string_literal: true++# Notify admins of a specific upcoming change's promotion,+# which occurs when the change has reached the promotion status+# defined by SiteSetting.promote_upcoming_changes_on_status.+#+# Since the site setting is not actually changed in the database+# when an upcoming change is automatically promoted, we also+# fire off a DiscourseEvent that developers can listen to+# in 015-track-upcoming-change-toggle.rb.+#+# Admins will only be notified once for each upcoming change,+# both via a staff action log and a Notification in the UI.+class UpcomingChanges::NotifyPromotion+ include Service::Base++ params do+ attribute :setting_name, :symbol+ attribute :admin_user_ids, :array+ attribute :changes_already_notified_about_promotion, :array, default: []++ validates :setting_name, presence: true+ validates :admin_user_ids, presence: true+ end++ policy :setting_is_available+ policy :meets_or_exceeds_status+ policy :change_has_not_already_been_notified_about_promotion+ policy :admin_has_not_manually_opted_out++ try do+ step :log_promotion+ model :records+ step :notify_admins+ step :create_event+ step :trigger_discourse_event+ end++ private++ def setting_is_available(params:)+ SiteSetting.respond_to?(params.setting_name)+ end++ def meets_or_exceeds_status(params:)+ UpcomingChanges.meets_or_exceeds_status?(+ params.setting_name,+ SiteSetting.promote_upcoming_changes_on_status.to_sym,+ )+ end++ def change_has_not_already_been_notified_about_promotion(params:)+ !params.changes_already_notified_about_promotion.include?(params.setting_name)+ end++ def admin_has_not_manually_opted_out(params:)+ # If they have opted out this will return false, since it will+ # return true if the change has exceeded the promotion status.+ UpcomingChanges.resolved_value(params.setting_name)+ end++ def log_promotion(params:, guardian:)+ context =+ I18n.t(+ "staff_action_logs.upcoming_changes.log_promoted",+ change_status: UpcomingChanges.change_status(params.setting_name).to_s.titleize,+ base_path: Discourse.base_path,+ )++ StaffActionLogger.new(Discourse.system_user).log_upcoming_change_toggle(+ params.setting_name,+ false,+ true,+ { context: },+ )+ end++ def fetch_records(params:)+ data = {+ upcoming_change_name: params.setting_name,+ upcoming_change_humanized_name: SiteSetting.humanized_name(params.setting_name),+ }.to_json++ params.admin_user_ids.map do |admin_id|+ {+ user_id: admin_id,+ notification_type: Notification.types[:upcoming_change_automatically_promoted],+ data:,+ }+ end+ end++ def notify_admins(records:)+ Notification::Action::BulkCreate.call(records:)+ end++ def create_event(params:)+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: params.setting_name,+ acting_user: Discourse.system_user,+ )+ end++ def trigger_discourse_event(params:)+ DiscourseEvent.trigger(:upcoming_change_enabled, params.setting_name)+ end+enddiff --git a/app/services/upcoming_changes/notify_promotions.rb b/app/services/upcoming_changes/notify_promotions.rbnew file mode 100644index 00000000000..1246efea72b--- /dev/null+++ b/app/services/upcoming_changes/notify_promotions.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++# Notify admins of all upcoming changes' promotions,+# which is called from the Jobs::Scheduled::CheckUpcomingChanges job.+class UpcomingChanges::NotifyPromotions+ include Service::Base++ model :changes_already_notified_about_promotion, optional: true+ model :admin_user_ids+ model :change_notification_statuses++ private++ def fetch_changes_already_notified_about_promotion+ UpcomingChangeEvent+ .where(+ upcoming_change_name: SiteSetting.upcoming_change_site_settings,+ event_type: :admins_notified_automatic_promotion,+ )+ .pluck(:upcoming_change_name)+ .map(&:to_sym)+ end++ def fetch_admin_user_ids+ User.human_users.admins.pluck(:id)+ end++ def fetch_change_notification_statuses(changes_already_notified_about_promotion:, admin_user_ids:)+ SiteSetting.upcoming_change_site_settings.index_with do |setting_name|+ status_hash = {}++ UpcomingChanges::NotifyPromotion.call(+ params: {+ setting_name: setting_name.to_sym,+ changes_already_notified_about_promotion:,+ admin_user_ids:,+ },+ guardian: Discourse.system_user.guardian,+ ) do |result|+ status_hash[:success] = result.success?++ on_failed_policy(:setting_is_available) do |policy|+ status_hash[:error] = "Setting #{setting_name} is not available"+ end++ on_failed_policy(:meets_or_exceeds_status) do |policy|+ status_hash[+ :error+ ] = "Setting #{setting_name} does not meet or exceed the promotion status"+ end++ on_failed_policy(:change_has_not_already_been_notified_about_promotion) do |policy|+ status_hash[+ :error+ ] = "Setting #{setting_name} has already notified admins about promotion"+ end++ on_failed_policy(:admin_has_not_manually_opted_out) do |policy|+ status_hash[:error] = "Setting #{setting_name} has been manually opted out by an admin"+ end++ on_exceptions do |exception|+ status_hash[:error] = exception.message+ status_hash[:backtrace] = exception.backtrace+ end+ end++ status_hash+ end+ end+enddiff --git a/app/services/upcoming_changes/promote.rb b/app/services/upcoming_changes/promote.rbdeleted file mode 100644index 2a8d7c9d1b3..00000000000--- a/app/services/upcoming_changes/promote.rb+++ /dev/null@@ -1,119 +0,0 @@-# frozen_string_literal: true--class UpcomingChanges::Promote- include Service::Base-- params do- attribute :setting_name, :symbol- attribute :promotion_status_threshold, :symbol-- validates :setting_name, presence: true- validates :promotion_status_threshold,- presence: true,- inclusion: {- in: UpcomingChanges.statuses.keys,- }- end-- policy :current_user_is_admin- policy :setting_is_available- policy :meets_promotion_criteria- policy :setting_not_modified- policy :setting_not_already_enabled- step :toggle_upcoming_change- step :log_promotion- step :notify_admins- step :create_event-- private-- def current_user_is_admin(guardian:)- guardian.is_admin?- end-- def setting_is_available(params:)- SiteSetting.respond_to?(params.setting_name)- end-- def meets_promotion_criteria(params:)- UpcomingChanges.meets_or_exceeds_status?(params.setting_name, params.promotion_status_threshold)- end-- def setting_not_modified(params:)- # For permanent changes, we always force promotion no matter what- # the admin has previously done.- if UpcomingChanges.change_status_value(params.setting_name) ==- UpcomingChanges.statuses[:permanent]- return true- end-- !SiteSetting.exists?(name: params.setting_name)- end-- def setting_not_already_enabled(params:)- !SiteSetting.public_send(params.setting_name)- end-- def toggle_upcoming_change(params:, guardian:)- UpcomingChanges::Toggle.call(- params: {- setting_name: params.setting_name,- enabled: true,- },- guardian:,- options: {- log_change: false,- },- ) do |result|- on_failure do- fail!("Unexpected failure when enabling upcoming change #{params.setting_name}")- end- end- end-- def log_promotion(params:, guardian:)- context =- I18n.t(- "staff_action_logs.upcoming_changes.log_promoted",- change_status: UpcomingChanges.change_status(params.setting_name).to_s.titleize,- base_path: Discourse.base_path,- )-- StaffActionLogger.new(Discourse.system_user).log_upcoming_change_toggle(- params.setting_name,- false,- true,- { context: },- )- end-- def notify_admins(params:)- data = {- upcoming_change_name: params.setting_name,- upcoming_change_humanized_name: SiteSetting.humanized_name(params.setting_name),- }.to_json-- records =- User- .human_users- .admins- .pluck(:id)- .map do |admin_id|- {- user_id: admin_id,- notification_type: Notification.types[:upcoming_change_automatically_promoted],- data:,- }- end-- Notification::Action::BulkCreate.call(records:)- end-- def create_event(params:)- UpcomingChangeEvent.create!(- event_type: :admins_notified_automatic_promotion,- upcoming_change_name: params.setting_name,- acting_user: Discourse.system_user,- )- end-enddiff --git a/app/services/upcoming_changes/toggle.rb b/app/services/upcoming_changes/toggle.rbindex 1fe562dd9b8..f5af747feda 100644--- a/app/services/upcoming_changes/toggle.rb+++ b/app/services/upcoming_changes/toggle.rb@@ -12,6 +12,10 @@ class UpcomingChanges::Toggleattribute :enabled, :booleanvalidates :setting_name, presence: truevalidates :enabled, inclusion: [true, false]++ def upcoming_change_event+ enabled ? :upcoming_change_enabled : :upcoming_change_disabled+ endendpolicy :current_user_is_admin@@ -23,6 +27,8 @@ class UpcomingChanges::Togglestep :log_eventend+ step :trigger_event+privatedef current_user_is_admin(guardian:)@@ -72,4 +78,8 @@ class UpcomingChanges::Toggleacting_user: guardian.user,)end++ def trigger_event(params:)+ DiscourseEvent.trigger(params.upcoming_change_event, params.setting_name)+ endenddiff --git a/app/services/upcoming_changes/track.rb b/app/services/upcoming_changes/track.rbindex b37a87d58bf..f0173887c6b 100644--- a/app/services/upcoming_changes/track.rb+++ b/app/services/upcoming_changes/track.rb@@ -5,7 +5,7 @@# upcoming change is available for them to opt-in to, based on certain criteria# that are explained in the Action classes.#-# Called from the TrackingInitializer in the config/initializers/015-track-upcoming-changes.rb file.+# Called from the Jobs::Scheduled::CheckUpcomingChanges job.class UpcomingChanges::Trackinclude Service::Basediff --git a/config/initializers/015-track-upcoming-change-toggle.rb b/config/initializers/015-track-upcoming-change-toggle.rbnew file mode 100644index 00000000000..2ba350b7679--- /dev/null+++ b/config/initializers/015-track-upcoming-change-toggle.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true+#+# Similar to 014-track-setting-changes.rb, we can react to upcoming changes+# being enabled/or disabled here for more complicated scenarios, where+# we are not just changing UI or behaviour when the state of the underlying+# setting is changed.+#+# We need to do this separately from 014-track-setting-changes.rb because+# we don't actually change the underlying setting value in the database+# when an upcoming change is automatically promoted. See UpcomingChanges::NotifyPromotions+# for further context.+#+# We do also send these events when admins manually opt-in or opt-out of an upcoming change+# via the UI and the UpcomingChanges::Toggle service.++DiscourseEvent.on(:upcoming_change_enabled) do |setting_name|+ # Respond to event here, e.g. if setting_name == :experimental_form_templates do X.+end++DiscourseEvent.on(:upcoming_change_disabled) do |setting_name|+ # Respond to event here, e.g. if setting_name == :experimental_form_templates do X.+enddiff --git a/config/initializers/015-track-upcoming-changes.rb b/config/initializers/015-track-upcoming-changes.rbdeleted file mode 100644index f516aeaa00e..00000000000--- a/config/initializers/015-track-upcoming-changes.rb+++ /dev/null@@ -1,27 +0,0 @@-# frozen_string_literal: true-#-# Tracks both the addition and removal of upcoming changes by-# observing site_settings/settings.yml files and writing to-# an upcoming change event log.-#-# Added upcoming changes will send a notification to site admins-# to inform them that the change is now available to opt-in,-# as long as the status of the change is one less than-# SiteSetting.promote_upcoming_changes_on_status. For example,-# if a site has `beta` for the promotion status, we only notify-# admins when the change reaches `alpha`.-#-# We may end up with separate added & status change events, and-# the admin should only be notified when the status is actually-# SiteSetting.promote_upcoming_changes_on_status - 1 OR gte-# SiteSetting.promote_upcoming_changes_on_status.-#-# Removed upcoming changes will be logged. After some time,-# if the setting related to the change no longer exists, the-# setting value in the site_settings table will be deleted-# in a cleanup job.--require "upcoming_changes"-require "upcoming_changes/tracking_initializer"--Rails.application.config.after_initialize { UpcomingChanges::TrackingInitializer.call }diff --git a/config/initializers/016-promote-upcoming-changes.rb b/config/initializers/016-promote-upcoming-changes.rbdeleted file mode 100644index b2e3f76647f..00000000000--- a/config/initializers/016-promote-upcoming-changes.rb+++ /dev/null@@ -1,10 +0,0 @@-# frozen_string_literal: true-#-# Promotes upcoming changes (defined in site_settings.yml) based-# on their status, and the configured promote_upcoming_changes_on_status-# site setting for the site.--require "upcoming_changes"-require "upcoming_changes/auto_promotion_initializer"--Rails.application.config.after_initialize { UpcomingChanges::AutoPromotionInitializer.call }diff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rbindex d1a0e61dfbb..2ba117734a2 100644--- a/lib/site_setting_extension.rb+++ b/lib/site_setting_extension.rb@@ -75,21 +75,40 @@ module SiteSettingExtension@mutex ||= Mutex.newend+ # Represents the current values of all site settings, incorporating+ # the database values and merging them with shadowed settings and+ # default values.def current@containers ||= {}@containers[provider.current_site] ||= {}end+ # Represents settings that actually have a value saved in the+ # database. We currently even store the default value in the+ # DB if an admin saves a different value then changes back+ # to the default.+ def modified+ @modified ||= {}+ @modified[provider.current_site] ||= {}+ end++ # Represents a map of theme IDs to all theme site settings+ # and values.def theme_site_settings@theme_site_settings ||= {}@theme_site_settings[provider.current_site] ||= {}end+ #def humanized_names(name)@humanized_names ||= {}@humanized_names[name] ||= humanized_name(name)end+ # Used for upcoming changes settings to determine which specific+ # groups have the change turned on for them. This is done separately+ # from group-based site settings because upcoming change settings+ # are always booleans.def site_setting_group_ids@site_setting_group_ids ||= {}@site_setting_group_ids[provider.current_site] ||= {}@@ -131,7 +150,9 @@ module SiteSettingExtension# in site_settings.yml:## setting_name:- # setting_options...+ # default: false+ # client: true+ # hidden: true# upcoming_change:# status: "alpha" (see UpcomingChanges.statuses.keys)# impact: "feature,staff" (feature|other for the first part, staff|admins|moderators|all_members|developers for the second part)@@ -500,6 +521,8 @@ module SiteSettingExtension)]+ new_modified = new_hash.dup+refresh_site_setting_group_ids!defaults_view = defaults.all(new_hash[:default_locale])@@ -514,6 +537,8 @@ module SiteSettingExtensionchanges.each { |name, val| current[name] = val }deletions.each { |name, _| current[name] = defaults_view[name] }+ modified.clear+ modified.merge!(new_modified)uploads.clearend@@ -608,6 +633,7 @@ module SiteSettingExtensionold_val = current[name]provider.destroy(name)current[name] = defaults.get(name, default_locale)+ modified.delete(name)return if current[name] == old_val@@ -662,6 +688,7 @@ module SiteSettingExtensionprovider.save(name, sanitized_val, type)current[name] = type_supervisor.to_rb_value(name, sanitized_val)+ modified[name] = current[name]return if current[name] == old_val@@ -980,11 +1007,17 @@ module SiteSettingExtensionrefresh! if current[name].nil?- value = current[name]+ value =+ if upcoming_change_metadata[name]+ UpcomingChanges.resolved_value(name)+ else+ current[name]+ endif mandatory_values[name]return (mandatory_values[name].split("|") | value.to_s.split("|")).join("|")end+valueendenddiff --git a/lib/upcoming_changes.rb b/lib/upcoming_changes.rbindex 0a71e35e6aa..aebc1af7062 100644--- a/lib/upcoming_changes.rb+++ b/lib/upcoming_changes.rb@@ -91,6 +91,31 @@ module UpcomingChanges).order(created_at: :desc)end+ def self.resolved_value(change_setting_name)+ # An admin has modified the setting and a value is stored+ # in the database, since the default for upcoming changes+ # is false.+ #+ # If the change is permanent though, the admin has no choice+ # in the matter.+ if SiteSetting.modified.key?(change_setting_name) &&+ UpcomingChanges.change_status(change_setting_name) != :permanent+ SiteSetting.current[change_setting_name]++ # The change has reached the promotion status and is forcibly+ # enabled, admins can still disable it.+ elsif UpcomingChanges.meets_or_exceeds_status?(+ change_setting_name,+ SiteSetting.promote_upcoming_changes_on_status.to_sym,+ ) || UpcomingChanges.change_status(change_setting_name) == :permanent+ true+ else+ # Otherwise use the default value, which for upcoming changes+ # is false.+ SiteSetting.defaults[change_setting_name]+ end+ end+def self.has_groups?(change_setting_name)group_ids_for(change_setting_name).present?enddiff --git a/lib/upcoming_changes/auto_promotion_initializer.rb b/lib/upcoming_changes/auto_promotion_initializer.rbdeleted file mode 100644index deb591bc974..00000000000--- a/lib/upcoming_changes/auto_promotion_initializer.rb+++ /dev/null@@ -1,91 +0,0 @@-# frozen_string_literal: true--module UpcomingChanges- class AutoPromotionInitializer- def self.log_prefix(site)- "[Upcoming changes promoter (#{site})]: "- end-- def self.verbose_log(site, level, message)- return unless SiteSetting.upcoming_change_verbose_logging- Rails.logger.public_send(level, "#{log_prefix(site)} #{message}")- end-- def self.call- RailsMultisite::ConnectionManagement.safe_each_connection do |site|- next if !SiteSetting.enable_upcoming_changes-- verbose_log(site, :info, "Starting promotion check for upcoming changes.")-- if SiteSetting.upcoming_change_site_settings.empty?- verbose_log(site, :info, "No upcoming changes present.")- next- end-- DistributedMutex.synchronize("promote_upcoming_changes_#{site}") do- SiteSetting.upcoming_change_site_settings.each do |setting_name|- UpcomingChanges::Promote.call(- params: {- setting_name:,- promotion_status_threshold: SiteSetting.promote_upcoming_changes_on_status,- },- guardian: Guardian.new(Discourse.system_user),- ) do |result|- on_failed_policy(:meets_promotion_criteria) do- verbose_log(- site,- :warn,- "'#{setting_name}' did not meet promotion criteria. Current status is #{UpcomingChanges.change_status(setting_name)}, required status is #{SiteSetting.promote_upcoming_changes_on_status}.",- )- end-- on_failed_policy(:setting_not_modified) do- verbose_log(- site,- :warn,- "'#{setting_name}' has already been modified by an admin, skipping promotion.",- )- end-- on_failed_policy(:setting_not_already_enabled) do- verbose_log(- site,- :warn,- "'#{setting_name}' is already enabled, skipping promotion.",- )- end-- on_failed_contract do |contract|- verbose_log(- site,- :error,- "Contract failure when promoting '#{setting_name}': #{contract.errors.full_messages.join(", ")}",- )- end-- on_failed_step(:toggle_upcoming_change) do- verbose_log(- site,- :error,- "Failed to promote '#{setting_name}' via toggle_upcoming_change, an unexpected error occurred.",- )- end-- on_failure do |error|- verbose_log(- site,- :error,- "Failed to promote '#{setting_name}', an unexpected error occurred. Error: #{error&.backtrace&.join("\n")}",- )- end-- on_success do- verbose_log(site, :info, "Successfully promoted '#{setting_name}' to enabled.")- end- end- end- end- end- end- end-enddiff --git a/lib/upcoming_changes/tracking_initializer.rb b/lib/upcoming_changes/tracking_initializer.rbdeleted file mode 100644index 75c6e82a072..00000000000--- a/lib/upcoming_changes/tracking_initializer.rb+++ /dev/null@@ -1,65 +0,0 @@-# frozen_string_literal: true--module UpcomingChanges- class TrackingInitializer- def self.log_prefix(site)- "[Upcoming changes tracker (#{site})]: "- end-- def self.verbose_log(site, level, message)- return unless SiteSetting.upcoming_change_verbose_logging- Rails.logger.public_send(level, "#{log_prefix(site)} #{message}")- end-- def self.call- RailsMultisite::ConnectionManagement.safe_each_connection do |site|- next if !SiteSetting.enable_upcoming_changes-- verbose_log(site, :info, "Beginning tracking initializer for upcoming changes")-- if SiteSetting.upcoming_change_site_settings.empty?- verbose_log(site, :info, "No upcoming changes present.")- next- end-- DistributedMutex.synchronize("track_upcoming_changes_#{site}") do- UpcomingChanges::Track.call(guardian: Guardian.new(Discourse.system_user)) do |result|- on_success do |added_changes:, removed_changes:, notified_admins_for_added_changes:, status_changes:|- added_changes.each do |change_name|- verbose_log(site, :info, "added upcoming change '#{change_name}'")- end-- notified_admins_for_added_changes.each do |change_name|- verbose_log(- site,- :info,- "notified site admins about added upcoming change '#{change_name}'",- )- end-- removed_changes.each do |change_name|- verbose_log(site, :info, "removed upcoming change '#{change_name}'")- end-- status_changes.each do |change_name, details|- verbose_log(- site,- :info,- "status changed for upcoming change '#{change_name}' from #{details[:previous_value]} to #{details[:new_value]}",- )- end- end-- on_failure do |error|- verbose_log(- site,- :error,- "Failed to track upcoming changes', an unexpected error occurred. Error: #{error&.backtrace&.join("\n")}",- )- end- end- end- end- end- end-enddiff --git a/spec/jobs/scheduled/check_upcoming_changes_spec.rb b/spec/jobs/scheduled/check_upcoming_changes_spec.rbnew file mode 100644index 00000000000..6c3f14bbc90--- /dev/null+++ b/spec/jobs/scheduled/check_upcoming_changes_spec.rb@@ -0,0 +1,327 @@+# frozen_string_literal: true++RSpec.describe Jobs::CheckUpcomingChanges do+ describe "#execute" do+ context "when enable_upcoming_changes is disabled" do+ before do+ SiteSetting.enable_upcoming_changes = false+ SiteSetting.upcoming_change_verbose_logging = true+ end++ it "does not log" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos).to be_empty+ expect(logger.errors).to be_empty+ end+ end+ end++ context "when enable_upcoming_changes is enabled" do+ fab!(:admin)++ before do+ SiteSetting.enable_upcoming_changes = true+ SiteSetting.upcoming_change_verbose_logging = true+ SiteSetting.promote_upcoming_changes_on_status = :stable+ end++ context "when there are no upcoming changes" do+ before { SiteSetting.stubs(:upcoming_change_site_settings).returns([]) }++ it "logs start message and that no changes are present" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).to include(+ "Starting change tracker and promotion notifier for upcoming changes",+ )+ expect(logger.infos.join("\n")).to include("No upcoming changes present.")+ end+ end+ end++ context "when there are upcoming changes to track" do+ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :beta,+ impact_type: "other",+ impact_role: "developers",+ },+ enable_user_tips: {+ impact: "feature,all_members",+ status: :alpha,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ it "synchronizes execution using DistributedMutex" do+ DistributedMutex+ .expects(:synchronize)+ .with("check_upcoming_changes_default", validity: 10.minutes)+ .yields+ described_class.new.execute({})+ end++ context "when changes are newly added" do+ before do+ UpcomingChangeEvent.where(+ upcoming_change_name: %i[enable_upload_debug_mode enable_user_tips],+ ).delete_all+ end++ it "logs added changes" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).to include(+ "Added upcoming change 'enable_upload_debug_mode'",+ )+ expect(logger.infos.join("\n")).to include("Added upcoming change 'enable_user_tips'")+ end+ end+ end++ context "when admins are notified about an available change" do+ before do+ UpcomingChangeEvent.where(+ upcoming_change_name: %i[enable_upload_debug_mode enable_user_tips],+ ).delete_all+ end++ it "logs that admins were notified" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).to include(+ "Notified site admins about added upcoming change 'enable_upload_debug_mode'",+ )+ end+ end++ it "does not log notification for changes that do not meet status threshold" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).not_to include(+ "Notified site admins about added upcoming change 'enable_user_tips'",+ )+ end+ end+ end++ context "when changes are removed" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :old_removed_change,+ )+ end++ after { UpcomingChangeEvent.where(upcoming_change_name: :old_removed_change).delete_all }++ it "logs removed changes" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).to include(+ "Removed upcoming change 'old_removed_change'",+ )+ end+ end+ end++ context "when status changes for an existing change" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ event_data: {+ "previous_value" => nil,+ "new_value" => "alpha",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ end++ it "logs status changes" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).to include(+ "Status changed for upcoming change 'enable_upload_debug_mode' from alpha to beta",+ )+ end+ end+ end+ end++ context "when the UpcomingChanges::Track service has an unexpected failure" do+ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :stable,+ impact_type: "other",+ impact_role: "developers",+ },+ },+ )+ end++ it "logs the error" do+ failing_track =+ Class.new(UpcomingChanges::Track) do+ def run!+ context.fail(error: "Simulated failure")+ raise Service::Base::Failure.new(context)+ end+ end++ stub_const(UpcomingChanges, "Track", failing_track) do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.errors.join("\n")).to include(+ "Failed to track upcoming changes, an unexpected error occurred.",+ )+ end+ end+ end+ end++ context "when notifying promotions" do+ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :stable,+ impact_type: "other",+ impact_role: "developers",+ },+ enable_user_tips: {+ impact: "feature,all_members",+ status: :beta,+ impact_type: "feature",+ impact_role: "all_members",+ },+ show_user_menu_avatars: {+ impact: "feature,all_members",+ status: :permanent,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ context "when the change meets promotion criteria" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ UpcomingChangeEvent.where(+ upcoming_change_name: :enable_upload_debug_mode,+ event_type: :admins_notified_automatic_promotion,+ ).delete_all++ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :show_user_menu_avatars,+ )+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :show_user_menu_avatars,+ )+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: :show_user_menu_avatars,+ acting_user: Discourse.system_user,+ )+ end++ it "logs promotion notification" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).to include(+ "Notified site admins about promotion of 'enable_upload_debug_mode'",+ )+ end+ end+ end++ context "when the change does not meet promotion criteria" do+ before { SiteSetting.promote_upcoming_changes_on_status = :never }++ it "does not log promotion" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).not_to include(+ "Notified site admins about promotion of 'enable_upload_debug_mode'",+ )+ end+ end++ it "logs the error" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.errors.join("\n")).to include(+ "Failed to notify about promotion of 'enable_upload_debug_mode': Setting enable_upload_debug_mode does not meet or exceed the promotion status",+ )+ end+ end+ end++ context "when notifying about permanent changes" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :show_user_menu_avatars,+ )+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :show_user_menu_avatars,+ )+ end++ it "logs promotion of permanent change" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos.join("\n")).to include(+ "Notified site admins about promotion of 'show_user_menu_avatars'",+ )+ end+ end+ end+ end+ end++ context "when upcoming_change_verbose_logging is disabled" do+ before do+ SiteSetting.enable_upcoming_changes = true+ SiteSetting.upcoming_change_verbose_logging = false+ SiteSetting.stubs(:upcoming_change_site_settings).returns([])+ end++ it "does not log" do+ track_log_messages do |logger|+ described_class.new.execute({})+ expect(logger.infos).to be_empty+ end+ end+ end+ end+enddiff --git a/spec/lib/site_setting_extension_spec.rb b/spec/lib/site_setting_extension_spec.rbindex 37ee134d7ff..9c5adb7cdcc 100644--- a/spec/lib/site_setting_extension_spec.rb+++ b/spec/lib/site_setting_extension_spec.rb@@ -1240,6 +1240,80 @@ RSpec.describe SiteSettingExtension doendend+ describe "site setting singleton methods" do+ describe "for an upcoming change site setting" do+ let(:setting_name) { :enable_upload_debug_mode }+ let(:default_value) { SiteSetting.defaults[setting_name] }++ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :beta,+ impact_type: "other",+ impact_role: "developers",+ },+ },+ )+ SiteSetting.send(:setup_methods, setting_name)+ SiteSetting.refresh!+ end++ after do+ SiteSetting.remove_override!(setting_name)+ SiteSetting.refresh!+ end++ it "returns the stored value when it differs from the default" do+ SiteSetting.public_send("#{setting_name}=", !default_value)+ expect(SiteSetting.public_send(setting_name)).to eq(!default_value)+ end++ it "returns true when the setting meets the promotion status" do+ SiteSetting.promote_upcoming_changes_on_status = :beta+ expect(SiteSetting.public_send(setting_name)).to eq(true)+ end++ it "returns false when admins have changed the setting to false even if the promotion status is met" do+ SiteSetting.public_send("#{setting_name}=", false)+ expect(SiteSetting.public_send(setting_name)).to eq(false)++ SiteSetting.promote_upcoming_changes_on_status = :beta+ expect(SiteSetting.public_send(setting_name)).to eq(false)+ end++ it "returns the default when the setting does not meet the promotion status" do+ SiteSetting.promote_upcoming_changes_on_status = :stable+ expect(SiteSetting.public_send(setting_name)).to eq(default_value)+ end++ context "when the upcoming change is permanent" do+ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :permanent,+ impact_type: "other",+ impact_role: "developers",+ },+ },+ )+ end++ it "returns true" do+ expect(SiteSetting.public_send(setting_name)).to eq(true)+ end++ it "return true even if the setting value is false in the database" do+ SiteSetting.public_send("#{setting_name}=", false)+ expect(SiteSetting.public_send(setting_name)).to eq(true)+ end+ end+ end+ end+describe "#notify_clients!" docontext "when the site setting is an upcoming change" dobefore dodiff --git a/spec/lib/upcoming_changes/auto_promotion_initializer_multisite_spec.rb b/spec/lib/upcoming_changes/auto_promotion_initializer_multisite_spec.rbdeleted file mode 100644index 771931f379c..00000000000--- a/spec/lib/upcoming_changes/auto_promotion_initializer_multisite_spec.rb+++ /dev/null@@ -1,42 +0,0 @@-# frozen_string_literal: true--RSpec.describe UpcomingChanges::AutoPromotionInitializer, type: :multisite do- context "when enable_upcoming_changes is enabled" do- before do- SiteSetting.enable_upcoming_changes = true- SiteSetting.upcoming_change_verbose_logging = true-- mock_upcoming_change_metadata(- {- enable_upload_debug_mode: {- impact: "other,developers",- status: :beta,- impact_type: "feature",- impact_role: "admins",- },- },- )- end-- it "promotes changes on sites that satisfy promotion criteria" do- test_multisite_connection("default") do- SiteSetting.enable_upload_debug_mode = false- SiteSetting.promote_upcoming_changes_on_status = :beta-- UpcomingChanges::AutoPromotionInitializer.call-- expect(SiteSetting.enable_upload_debug_mode).to be(true)- end-- # beta status doesn't meet stable threshold, so should not be promoted- test_multisite_connection("second") do- SiteSetting.enable_upload_debug_mode = false- SiteSetting.promote_upcoming_changes_on_status = :stable-- UpcomingChanges::AutoPromotionInitializer.call-- expect(SiteSetting.enable_upload_debug_mode).to be(false)- end- end- end-enddiff --git a/spec/lib/upcoming_changes/auto_promotion_initializer_spec.rb b/spec/lib/upcoming_changes/auto_promotion_initializer_spec.rbdeleted file mode 100644index fc0b5b72c31..00000000000--- a/spec/lib/upcoming_changes/auto_promotion_initializer_spec.rb+++ /dev/null@@ -1,167 +0,0 @@-# frozen_string_literal: true--RSpec.describe UpcomingChanges::AutoPromotionInitializer do- context "when enable_upcoming_changes is disabled" do- before do- SiteSetting.enable_upcoming_changes = false- SiteSetting.promote_upcoming_changes_on_status = :stable- end-- it "does nothing" do- SiteSetting.expects(:upcoming_change_site_settings).never- UpcomingChanges::AutoPromotionInitializer.call- end- end-- context "when enable_upcoming_changes is enabled" do- before do- SiteSetting.enable_upcoming_changes = true- SiteSetting.upcoming_change_verbose_logging = true-- mock_upcoming_change_metadata(- {- enable_upload_debug_mode: {- impact: "other,developers",- status: :stable,- impact_type: "other",- impact_role: "developers",- },- enable_user_tips: {- impact: "feature,all_members",- status: :beta,- impact_type: "feature",- impact_role: "all_members",- },- show_user_menu_avatars: {- impact: "feature,all_members",- status: :permanent,- impact_type: "feature",- impact_role: "all_members",- },- },- )- end-- it "synchronizes execution using DistributedMutex" do- DistributedMutex.expects(:synchronize).with("promote_upcoming_changes_default").yields- UpcomingChanges::AutoPromotionInitializer.call- end-- context "when the change does not meet the promotion criteria" do- before { SiteSetting.promote_upcoming_changes_on_status = :never }-- it "does not enable the upcoming change and logs output" do- track_log_messages do |logger|- UpcomingChanges::AutoPromotionInitializer.call- expect(logger.warnings.join("\n")).to include(- "'enable_upload_debug_mode' did not meet promotion criteria. Current status is stable, required status is never.",- )- expect(logger.warnings.join("\n")).to include(- "'enable_user_tips' did not meet promotion criteria. Current status is beta, required status is never.",- )- end- end- end-- context "when the upcoming change has already been set by the admin" do- before do- SiteSetting.enable_upload_debug_mode = false- SiteSetting.create!(- name: "enable_upload_debug_mode",- value: false,- data_type: SiteSetting.types[:bool],- )- end-- after { SiteSetting.find_by(name: "enable_upload_debug_mode").destroy! }-- it "does not enable the upcoming change and logs output" do- track_log_messages do |logger|- UpcomingChanges::AutoPromotionInitializer.call- expect(logger.warnings.join("\n")).to include(- "'enable_upload_debug_mode' has already been modified by an admin, skipping promotion.",- )- end- end-- context "when the upcoming change has reached the permanent state" do- before do- SiteSetting.show_user_menu_avatars = false- SiteSetting.create!(- name: "show_user_menu_avatars",- value: false,- data_type: SiteSetting.types[:bool],- )- end-- after { SiteSetting.find_by(name: "show_user_menu_avatars").destroy! }-- it "does enable the upcoming change and logs output" do- track_log_messages do |logger|- UpcomingChanges::AutoPromotionInitializer.call- expect(logger.infos.join("\n")).to include(- /Successfully promoted 'show_user_menu_avatars' to enabled/,- )- end- expect(SiteSetting.show_user_menu_avatars).to be(true)- end- end- end-- context "when the upcoming change is already enabled" do- before { SiteSetting.enable_upload_debug_mode = true }-- it "does not enable the upcoming change and logs output" do- track_log_messages do |logger|- UpcomingChanges::AutoPromotionInitializer.call- expect(logger.warnings.join("\n")).to include(- "'enable_upload_debug_mode' is already enabled, skipping promotion.",- )- end- end- end-- context "when the UpcomingChanges::Toggle service has an unexpected failure" do- it "does not enable the upcoming change and logs output" do- failing_toggle =- Class.new(UpcomingChanges::Toggle) do- def run!- context.fail(error: "Simulated failure")- raise Service::Base::Failure.new(context)- end- end-- stub_const(UpcomingChanges, "Toggle", failing_toggle) do- track_log_messages do |logger|- UpcomingChanges::AutoPromotionInitializer.call- expect(logger.errors.join("\n")).to include(- "Failed to promote 'enable_upload_debug_mode' via toggle_upcoming_change, an unexpected error occurred.",- )- end- end- end- end-- context "when everything is ok" do- it "enables the upcoming change and logs output" do- track_log_messages do |logger|- UpcomingChanges::AutoPromotionInitializer.call- expect(logger.infos.join("\n")).to include(- /Successfully promoted 'enable_upload_debug_mode' to enabled/,- )- end- expect(SiteSetting.enable_upload_debug_mode).to be(true)- end-- it "does not enable an upcoming change that does not meet promotion status criteria" do- track_log_messages do |logger|- UpcomingChanges::AutoPromotionInitializer.call- expect(logger.warnings.join("\n")).to include(- /'enable_user_tips' did not meet promotion criteria. Current status is beta, required status is stable./,- )- end- expect(SiteSetting.enable_upload_debug_mode).to be(true)- end- end- end-enddiff --git a/spec/lib/upcoming_changes/tracking_initializer_multisite_spec.rb b/spec/lib/upcoming_changes/tracking_initializer_multisite_spec.rbdeleted file mode 100644index 74798435868..00000000000--- a/spec/lib/upcoming_changes/tracking_initializer_multisite_spec.rb+++ /dev/null@@ -1,56 +0,0 @@-# frozen_string_literal: true--RSpec.describe UpcomingChanges::TrackingInitializer, type: :multisite do- context "when enable_upcoming_changes is enabled" do- before do- SiteSetting.enable_upcoming_changes = true- SiteSetting.upcoming_change_verbose_logging = true- SiteSetting.promote_upcoming_changes_on_status = :stable-- mock_upcoming_change_metadata(- {- enable_upload_debug_mode: {- impact: "other,developers",- status: :beta,- impact_type: "feature",- impact_role: "admins",- },- },- )- end-- it "tracks changes across all sites" do- test_multisite_connection("default") do- Fabricate(:admin)- SiteSetting.enable_upcoming_changes = true- SiteSetting.promote_upcoming_changes_on_status = :stable- UpcomingChangeEvent.where(upcoming_change_name: :enable_upload_debug_mode).delete_all-- UpcomingChanges::TrackingInitializer.call-- expect(- UpcomingChangeEvent.exists?(- upcoming_change_name: :enable_upload_debug_mode,- event_type: :added,- ),- ).to be(true)- end-- test_multisite_connection("second") do- Fabricate(:admin)- SiteSetting.enable_upcoming_changes = true- SiteSetting.promote_upcoming_changes_on_status = :stable- UpcomingChangeEvent.where(upcoming_change_name: :enable_upload_debug_mode).delete_all-- UpcomingChanges::TrackingInitializer.call-- expect(- UpcomingChangeEvent.exists?(- upcoming_change_name: :enable_upload_debug_mode,- event_type: :added,- ),- ).to be(true)- end- end- end-enddiff --git a/spec/lib/upcoming_changes/tracking_initializer_spec.rb b/spec/lib/upcoming_changes/tracking_initializer_spec.rbdeleted file mode 100644index 40373d50f44..00000000000--- a/spec/lib/upcoming_changes/tracking_initializer_spec.rb+++ /dev/null@@ -1,176 +0,0 @@-# frozen_string_literal: true--RSpec.describe UpcomingChanges::TrackingInitializer do- context "when enable_upcoming_changes is disabled" do- before do- SiteSetting.enable_upcoming_changes = false- SiteSetting.promote_upcoming_changes_on_status = :stable- end-- it "does nothing" do- SiteSetting.expects(:upcoming_change_site_settings).never- UpcomingChanges::TrackingInitializer.call- end- end-- context "when enable_upcoming_changes is enabled" do- before do- SiteSetting.enable_upcoming_changes = true- SiteSetting.upcoming_change_verbose_logging = true- SiteSetting.promote_upcoming_changes_on_status = :stable- end-- context "when there are upcoming changes to track" do- fab!(:admin)-- before do- mock_upcoming_change_metadata(- {- enable_upload_debug_mode: {- impact: "other,developers",- status: :beta,- impact_type: "other",- impact_role: "developers",- },- enable_user_tips: {- impact: "feature,all_members",- status: :alpha,- impact_type: "feature",- impact_role: "all_members",- },- },- )- end-- it "synchronizes execution using DistributedMutex" do- DistributedMutex.expects(:synchronize).with("track_upcoming_changes_default").yields- UpcomingChanges::TrackingInitializer.call- end-- context "when changes are newly added" do- before do- UpcomingChangeEvent.where(- upcoming_change_name: %i[enable_upload_debug_mode enable_user_tips],- ).delete_all- end-- it "logs added changes" do- track_log_messages do |logger|- UpcomingChanges::TrackingInitializer.call- expect(logger.infos.join("\n")).to include(- "added upcoming change 'enable_upload_debug_mode'",- )- expect(logger.infos.join("\n")).to include("added upcoming change 'enable_user_tips'")- end- end- end-- context "when admins are notified about an available change" do- before do- UpcomingChangeEvent.where(- upcoming_change_name: %i[enable_upload_debug_mode enable_user_tips],- ).delete_all- end-- it "logs that admins were notified" do- track_log_messages do |logger|- UpcomingChanges::TrackingInitializer.call- expect(logger.infos.join("\n")).to include(- "notified site admins about added upcoming change 'enable_upload_debug_mode'",- )- end- end-- it "does not log notification for changes that do not meet status threshold" do- track_log_messages do |logger|- UpcomingChanges::TrackingInitializer.call- expect(logger.infos.join("\n")).not_to include(- "notified site admins about added upcoming change 'enable_user_tips'",- )- end- end- end-- context "when changes are removed" do- before do- UpcomingChangeEvent.create!(event_type: :added, upcoming_change_name: :old_removed_change)- end-- after { UpcomingChangeEvent.where(upcoming_change_name: :old_removed_change).delete_all }-- it "logs removed changes" do- track_log_messages do |logger|- UpcomingChanges::TrackingInitializer.call- expect(logger.infos.join("\n")).to include(- "removed upcoming change 'old_removed_change'",- )- end- end- end-- context "when status changes for an existing change" do- before do- UpcomingChangeEvent.create!(- event_type: :added,- upcoming_change_name: :enable_upload_debug_mode,- )- UpcomingChangeEvent.create!(- event_type: :status_changed,- upcoming_change_name: :enable_upload_debug_mode,- event_data: {- "previous_value" => nil,- "new_value" => "alpha",- },- )- UpcomingChangeEvent.create!(- event_type: :admins_notified_available_change,- upcoming_change_name: :enable_upload_debug_mode,- )- end-- it "logs status changes" do- track_log_messages do |logger|- UpcomingChanges::TrackingInitializer.call- expect(logger.infos.join("\n")).to include(- "status changed for upcoming change 'enable_upload_debug_mode' from alpha to beta",- )- end- end- end- end-- context "when the UpcomingChanges::Track service has an unexpected failure" do- before do- mock_upcoming_change_metadata(- {- enable_upload_debug_mode: {- impact: "other,developers",- status: :stable,- impact_type: "other",- impact_role: "developers",- },- },- )- end-- it "logs the error" do- failing_track =- Class.new(UpcomingChanges::Track) do- def run!- context.fail(error: "Simulated failure")- raise Service::Base::Failure.new(context)- end- end-- stub_const(UpcomingChanges, "Track", failing_track) do- track_log_messages do |logger|- UpcomingChanges::TrackingInitializer.call- expect(logger.errors.join("\n")).to include(- "Failed to track upcoming changes', an unexpected error occurred.",- )- end- end- end- end- end-enddiff --git a/spec/services/problem_check/upcoming_change_stable_opted_out_spec.rb b/spec/services/problem_check/upcoming_change_stable_opted_out_spec.rbindex fbd69a0d127..4e7833d4c18 100644--- a/spec/services/problem_check/upcoming_change_stable_opted_out_spec.rb+++ b/spec/services/problem_check/upcoming_change_stable_opted_out_spec.rb@@ -35,6 +35,8 @@ RSpec.describe ProblemCheck::UpcomingChangeStableOptedOut doendcontext "when upcoming change is stable and not opted in" do+ before { SiteSetting.enable_upload_debug_mode = false }+it doexpect(check).to have_a_problem.with_priority("low").with_target("enable_upload_debug_mode",@@ -58,25 +60,6 @@ RSpec.describe ProblemCheck::UpcomingChangeStableOptedOut doit { expect(check).to be_chill_about_it }end-- context "when upcoming change is permanent and not opted in" do- before do- mock_upcoming_change_metadata(- enable_upload_debug_mode: {- impact: "other,developers",- status: :permanent,- impact_type: "other",- impact_role: "developers",- },- )- end-- it do- expect(check).to have_a_problem.with_priority("low").with_target(- "enable_upload_debug_mode",- )- end- endendendenddiff --git a/spec/services/upcoming_changes/notify_promotion_spec.rb b/spec/services/upcoming_changes/notify_promotion_spec.rbnew file mode 100644index 00000000000..06ed7ce5d78--- /dev/null+++ b/spec/services/upcoming_changes/notify_promotion_spec.rb@@ -0,0 +1,135 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::NotifyPromotion do+ describe UpcomingChanges::NotifyPromotion::Contract, type: :model do+ it { is_expected.to validate_presence_of(:setting_name) }+ it { is_expected.to validate_presence_of(:admin_user_ids) }+ end++ describe ".call" do+ subject(:result) do+ described_class.call(+ params: {+ setting_name:,+ admin_user_ids:,+ changes_already_notified_about_promotion:,+ },+ guardian: Discourse.system_user.guardian,+ )+ end++ fab!(:admin)+ fab!(:admin_2, :admin)++ let(:setting_name) { :enable_upload_debug_mode }+ let(:admin_user_ids) { [admin.id, admin_2.id] }+ let(:changes_already_notified_about_promotion) { [] }+ let(:setting_status) { :stable }++ before do+ SiteSetting.promote_upcoming_changes_on_status = :stable+ mock_upcoming_change_metadata(+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: setting_status,+ impact_type: "other",+ impact_role: "developers",+ },+ )+ end++ context "when data is invalid" do+ let(:setting_name) { nil }++ it { is_expected.to fail_a_contract }+ end++ context "when setting is not available" do+ let(:setting_name) { :nonexistent_setting }++ it { is_expected.to fail_a_policy(:setting_is_available) }+ end++ context "when setting does not meet or exceed promotion status" do+ let(:setting_status) { :beta }++ it { is_expected.to fail_a_policy(:meets_or_exceeds_status) }+ end++ context "when change has already been notified about promotion" do+ let(:changes_already_notified_about_promotion) { [:enable_upload_debug_mode] }++ it { is_expected.to fail_a_policy(:change_has_not_already_been_notified_about_promotion) }+ end++ context "when admin has manually opted out" do+ before { SiteSetting.enable_upload_debug_mode = false }++ it { is_expected.to fail_a_policy(:admin_has_not_manually_opted_out) }+ end++ context "when everything's ok" do+ let(:notification) do+ Notification.where("data::text LIKE ?", "%enable_upload_debug_mode%").last+ end+ let(:events) { DiscourseEvent.track_events { result } }+ let(:event) do+ events.find do |e|+ e[:event_name] == :upcoming_change_enabled &&+ e[:params].first == :enable_upload_debug_mode+ end+ end++ it { is_expected.to run_successfully }++ it "logs the change context in the staff action log" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_toggled],+ subject: "enable_upload_debug_mode",+ ).count+ }.by(1)++ expect(UserHistory.last.context).to eq(+ I18n.t(+ "staff_action_logs.upcoming_changes.log_promoted",+ change_status: UpcomingChanges.change_status(:enable_upload_debug_mode).to_s.titleize,+ base_path: Discourse.base_path,+ ),+ )+ end++ it "notifies admins about the upcoming change" do+ expect { result }.to change {+ Notification+ .where(+ notification_type: Notification.types[:upcoming_change_automatically_promoted],+ user_id: [admin.id, admin_2.id],+ )+ .where("data::text LIKE ?", "%enable_upload_debug_mode%")+ .count+ }.by(2)++ expect(notification.data).to eq(+ {+ upcoming_change_name: :enable_upload_debug_mode,+ upcoming_change_humanized_name: "Enable upload debug mode",+ }.to_json,+ )+ end++ it "creates an admins_notified_automatic_promotion event" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: :enable_upload_debug_mode,+ ).count+ }.by(1)+ end++ it "triggers DiscourseEvent for the promoted setting" do+ expect(event[:params]).to eq([:enable_upload_debug_mode])+ end+ end+ end+enddiff --git a/spec/services/upcoming_changes/notify_promotions_spec.rb b/spec/services/upcoming_changes/notify_promotions_spec.rbnew file mode 100644index 00000000000..d509617528f--- /dev/null+++ b/spec/services/upcoming_changes/notify_promotions_spec.rb@@ -0,0 +1,246 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::NotifyPromotions do+ describe ".call" do+ subject(:result) { described_class.call }++ fab!(:admin)+ fab!(:admin_2, :admin)++ let(:enable_upload_debug_mode_status) { :stable }+ let(:show_user_menu_avatars_status) { :beta }++ before do+ SiteSetting.promote_upcoming_changes_on_status = :stable+ SiteSetting.stubs(:upcoming_change_site_settings).returns(+ %i[enable_upload_debug_mode show_user_menu_avatars],+ )++ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: enable_upload_debug_mode_status,+ impact_type: "other",+ impact_role: "developers",+ },+ show_user_menu_avatars: {+ impact: "feature,all_members",+ status: show_user_menu_avatars_status,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ context "when there is an error when trying to process a change" do+ before do+ StaffActionLogger+ .any_instance+ .stubs(:log_upcoming_change_toggle)+ .raises(StandardError, "test error")+ end++ it "returns the errors" do+ expect(result[:change_notification_statuses]).to match(+ enable_upload_debug_mode: {+ success: false,+ error: "test error",+ backtrace: a_kind_of(Array),+ },+ show_user_menu_avatars: {+ success: false,+ error: "Setting show_user_menu_avatars does not meet or exceed the promotion status",+ },+ )+ end+ end++ context "when everything is ok" do+ it { is_expected.to run_successfully }++ it "returns a state of all settings as success or failure, along with the related error message" do+ expect(result[:change_notification_statuses]).to match(+ enable_upload_debug_mode: {+ success: true,+ },+ show_user_menu_avatars: {+ success: false,+ error: "Setting show_user_menu_avatars does not meet or exceed the promotion status",+ },+ )+ end++ it "logs the change context in the staff action log" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_toggled],+ subject: "enable_upload_debug_mode",+ ).count+ }.by(1)++ expect(UserHistory.last.context).to eq(+ I18n.t(+ "staff_action_logs.upcoming_changes.log_promoted",+ change_status: UpcomingChanges.change_status(:enable_upload_debug_mode).to_s.titleize,+ base_path: Discourse.base_path,+ ),+ )+ end++ it "notifies admins about the upcoming change" do+ expect { result }.to change {+ Notification+ .where(+ notification_type: Notification.types[:upcoming_change_automatically_promoted],+ user_id: [admin.id, admin_2.id],+ )+ .where("data::text LIKE ?", "%enable_upload_debug_mode%")+ .count+ }.by(2)++ notification = Notification.where("data::text LIKE ?", "%enable_upload_debug_mode%").last+ expect(notification.data).to eq(+ {+ upcoming_change_name: :enable_upload_debug_mode,+ upcoming_change_humanized_name: "Enable upload debug mode",+ }.to_json,+ )+ end++ it "creates an admins_notified_automatic_promotion event" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: :enable_upload_debug_mode,+ ).count+ }.by(1)+ end++ it "triggers DiscourseEvent for the promoted setting" do+ events = DiscourseEvent.track_events { result }+ event =+ events.find do |e|+ e[:event_name] == :upcoming_change_enabled &&+ e[:params].first == :enable_upload_debug_mode+ end++ expect(event).to be_present+ expect(event[:params]).to eq([:enable_upload_debug_mode])+ end++ context "when multiple settings meet promotion criteria" do+ let(:show_user_menu_avatars_status) { :stable }++ it "processes all eligible settings" do+ expect { result }.to change {+ Notification.where(+ notification_type: Notification.types[:upcoming_change_automatically_promoted],+ user_id: [admin.id, admin_2.id],+ ).count+ }.by(4)+ end++ it "creates events for all promoted settings" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars],+ ).count+ }.by(2)+ end++ it "triggers DiscourseEvent for all promoted settings" do+ events = DiscourseEvent.track_events { result }+ promoted_events = events.select { |e| e[:event_name] == :upcoming_change_enabled }++ expect(promoted_events.length).to eq(2)+ expect(promoted_events.map { |e| e[:params].first }).to contain_exactly(+ :enable_upload_debug_mode,+ :show_user_menu_avatars,+ )+ end+ end++ context "when there are no upcoming changes" do+ before { SiteSetting.stubs(:upcoming_change_site_settings).returns([]) }++ it "does not create any notifications" do+ expect { result }.not_to change { Notification.count }+ end++ it "does not trigger any events" do+ events = DiscourseEvent.track_events { result }+ expect(events.select { |e| e[:event_name] == :upcoming_change_enabled }).to be_empty+ end+ end++ context "when settings do not meet promotion status" do+ let(:enable_upload_debug_mode_status) { :beta }+ let(:show_user_menu_avatars_status) { :alpha }++ it "does not create any notifications" do+ expect { result }.not_to change { Notification.count }+ end++ it "does not trigger any events" do+ events = DiscourseEvent.track_events { result }+ expect(events.select { |e| e[:event_name] == :upcoming_change_enabled }).to be_empty+ end+ end++ context "when settings are already notified about promotion" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: :enable_upload_debug_mode,+ acting_user: Discourse.system_user,+ )+ end++ it "does not notify admins again for the already-notified setting" do+ expect { result }.not_to change {+ Notification+ .where(notification_type: Notification.types[:upcoming_change_automatically_promoted])+ .where("data::text LIKE ?", "%enable_upload_debug_mode%")+ .count+ }+ end++ it "does not trigger event for the already-notified setting" do+ events = DiscourseEvent.track_events { result }+ expect(+ events.select do |e|+ e[:event_name] == :upcoming_change_enabled &&+ e[:params].first == :enable_upload_debug_mode+ end,+ ).to be_empty+ end+ end++ context "when settings are opted out" do+ before { SiteSetting.enable_upload_debug_mode = false }++ it "does not notify admins for opted-out settings" do+ expect { result }.not_to change {+ Notification+ .where(notification_type: Notification.types[:upcoming_change_automatically_promoted])+ .where("data::text LIKE ?", "%enable_upload_debug_mode%")+ .count+ }+ end++ it "does not trigger event for opted-out settings" do+ events = DiscourseEvent.track_events { result }+ expect(+ events.select do |e|+ e[:event_name] == :upcoming_change_enabled &&+ e[:params].first == :enable_upload_debug_mode+ end,+ ).to be_empty+ end+ end+ end+ end+enddiff --git a/spec/services/upcoming_changes/promote_spec.rb b/spec/services/upcoming_changes/promote_spec.rbdeleted file mode 100644index 0d25392d2c9..00000000000--- a/spec/services/upcoming_changes/promote_spec.rb+++ /dev/null@@ -1,158 +0,0 @@-# frozen_string_literal: true--RSpec.describe UpcomingChanges::Promote do- describe UpcomingChanges::Promote::Contract, type: :model do- subject(:contract) { described_class.new }-- it { is_expected.to validate_presence_of(:setting_name) }- it { is_expected.to validate_presence_of(:promotion_status_threshold) }- it do- is_expected.to validate_inclusion_of(:promotion_status_threshold).in_array(- UpcomingChanges.statuses.keys,- )- end- end-- describe ".call" do- subject(:result) { described_class.call(params:, **dependencies) }-- fab!(:admin)- let(:current_change_status) { :beta }- let(:dependencies) { { guardian: } }- let(:guardian) { admin.guardian }- let(:params) { { setting_name: :enable_upload_debug_mode, promotion_status_threshold: } }-- before do- mock_upcoming_change_metadata(- {- enable_upload_debug_mode: {- impact: "other,developers",- status: current_change_status,- impact_type: "other",- impact_role: "developers",- },- },- )- end-- context "when contract is invalid" do- let(:params) { {} }-- it { is_expected.to fail_a_contract }- end-- context "when the upcoming change does not meet the status promotion criteria" do- let(:promotion_status_threshold) { :stable }-- it { is_expected.to fail_a_policy(:meets_promotion_criteria) }- end-- context "when the underlying setting for the upcoming change already exists in the DB (admin has modified it)" do- let(:promotion_status_threshold) { :beta }-- before do- SiteSetting.enable_upload_debug_mode = false- SiteSetting.create!(- name: "enable_upload_debug_mode",- value: false,- data_type: SiteSetting.types[:bool],- )- end-- after { SiteSetting.find_by(name: "enable_upload_debug_mode").destroy! }-- context "when the current_change_status is not permanent" do- let(:current_change_status) { :beta }-- it { is_expected.to fail_a_policy(:setting_not_modified) }- end-- context "when the current_change_status is permanent" do- let(:current_change_status) { :permanent }-- it "enables the upcoming change setting" do- expect { result }.to change { SiteSetting.enable_upload_debug_mode }.to be_truthy- end-- it "logs the change context in the staff action log" do- expect { result }.to change {- UserHistory.where(- action: UserHistory.actions[:upcoming_change_toggled],- subject: "enable_upload_debug_mode",- ).count- }.by(1)-- expect(UserHistory.last.context).to eq(- I18n.t(- "staff_action_logs.upcoming_changes.log_promoted",- change_status: UpcomingChanges.change_status(:enable_upload_debug_mode).to_s.titleize,- base_path: Discourse.base_path,- ),- )- end- end- end-- context "when the upcoming change is already enabled" do- let(:promotion_status_threshold) { :beta }-- before { SiteSetting.enable_upload_debug_mode = true }-- it { is_expected.to fail_a_policy(:setting_not_already_enabled) }- end-- context "when everything is ok" do- fab!(:admin_2, :admin)-- let(:promotion_status_threshold) { :beta }-- it { is_expected.to run_successfully }-- it "enables the upcoming change setting" do- expect { result }.to change { SiteSetting.enable_upload_debug_mode }.to be_truthy- end-- it "logs the change context in the staff action log" do- expect { result }.to change {- UserHistory.where(- action: UserHistory.actions[:upcoming_change_toggled],- subject: "enable_upload_debug_mode",- ).count- }.by(1)-- expect(UserHistory.last.context).to eq(- I18n.t(- "staff_action_logs.upcoming_changes.log_promoted",- change_status: UpcomingChanges.change_status(:enable_upload_debug_mode).to_s.titleize,- base_path: Discourse.base_path,- ),- )- end-- it "notifies admins about the upcoming change" do- expect { result }.to change {- Notification.where(- notification_type: Notification.types[:upcoming_change_automatically_promoted],- user_id: [admin.id, admin_2.id],- ).count- }.by(2)-- expect(Notification.last.data).to eq(- {- upcoming_change_name: :enable_upload_debug_mode,- upcoming_change_humanized_name: "Enable upload debug mode",- }.to_json,- )- end-- it "creates an admins_notified_automatic_promotion event" do- expect { result }.to change {- UpcomingChangeEvent.where(- event_type: :admins_notified_automatic_promotion,- upcoming_change_name: :enable_upload_debug_mode,- ).count- }.by(1)- end- end- end-enddiff --git a/spec/services/upcoming_changes/toggle_spec.rb b/spec/services/upcoming_changes/toggle_spec.rbindex 15106878c30..068442a8203 100644--- a/spec/services/upcoming_changes/toggle_spec.rb+++ b/spec/services/upcoming_changes/toggle_spec.rb@@ -62,6 +62,15 @@ RSpec.describe UpcomingChanges::Toggle doit "does not create an UpcomingChangeEvent" doexpect { result }.not_to change { UpcomingChangeEvent.count }end++ it "triggers the upcoming_change_enabled event" do+ events =+ DiscourseEvent+ .track_events { result }+ .select { |e| e[:event_name] == :upcoming_change_enabled }++ expect(events.first[:params]).to eq([setting_name.to_s])+ endendcontext "when disabling the setting" do@@ -85,6 +94,15 @@ RSpec.describe UpcomingChanges::Toggle doit "does not create an UpcomingChangeEvent" doexpect { result }.not_to change { UpcomingChangeEvent.count }end++ it "triggers the upcoming_change_disabled event" do+ events =+ DiscourseEvent+ .track_events { result }+ .select { |e| e[:event_name] == :upcoming_change_disabled }++ expect(events.first[:params]).to eq([setting_name.to_s])+ endendend@@ -135,6 +153,15 @@ RSpec.describe UpcomingChanges::Toggle doit "does not create an UpcomingChangeEvent" doexpect { result }.not_to change { UpcomingChangeEvent.count }end++ it "triggers the upcoming_change_disabled event" do+ events =+ DiscourseEvent+ .track_events { result }+ .select { |e| e[:event_name] == :upcoming_change_disabled }++ expect(events.first[:params]).to eq([setting_name.to_s])+ endendendend@@ -175,6 +202,15 @@ RSpec.describe UpcomingChanges::Toggle do).count}.by(1)end++ it "triggers the upcoming_change_enabled event" do+ events =+ DiscourseEvent+ .track_events { result }+ .select { |e| e[:event_name] == :upcoming_change_enabled }++ expect(events.first[:params]).to eq([setting_name.to_s])+ endendcontext "when disabling the setting" do@@ -207,6 +243,15 @@ RSpec.describe UpcomingChanges::Toggle do).count}.by(1)end++ it "triggers the upcoming_change_disabled event" do+ events =+ DiscourseEvent+ .track_events { result }+ .select { |e| e[:event_name] == :upcoming_change_disabled }++ expect(events.first[:params]).to eq([setting_name.to_s])+ endendend@@ -234,6 +279,15 @@ RSpec.describe UpcomingChanges::Toggle doit "does not create an UpcomingChangeEvent" doexpect { result }.not_to change { UpcomingChangeEvent.count }end++ it "triggers the upcoming_change_enabled event" do+ events =+ DiscourseEvent+ .track_events { result }+ .select { |e| e[:event_name] == :upcoming_change_enabled }++ expect(events.first[:params]).to eq([setting_name.to_s])+ endendcontext "when disabling the setting" do@@ -257,6 +311,15 @@ RSpec.describe UpcomingChanges::Toggle doit "does not create an UpcomingChangeEvent" doexpect { result }.not_to change { UpcomingChangeEvent.count }end++ it "triggers the upcoming_change_disabled event" do+ events =+ DiscourseEvent+ .track_events { result }+ .select { |e| e[:event_name] == :upcoming_change_disabled }++ expect(events.first[:params]).to eq([setting_name.to_s])+ endendendenddiff --git a/spec/system/admin_upcoming_changes_spec.rb b/spec/system/admin_upcoming_changes_spec.rbindex 1af7a17c96c..ce2d3c917d9 100644--- a/spec/system/admin_upcoming_changes_spec.rb+++ b/spec/system/admin_upcoming_changes_spec.rb@@ -24,6 +24,7 @@ describe "Admin upcoming changes", type: :system do},)+ SiteSetting.about_page_extra_groups_show_description = falsesign_in(current_user)enddiff --git a/spec/system/member_upcoming_changes_spec.rb b/spec/system/member_upcoming_changes_spec.rbindex 8c49783d8ce..57b8eef49f1 100644--- a/spec/system/member_upcoming_changes_spec.rb+++ b/spec/system/member_upcoming_changes_spec.rb@@ -26,6 +26,7 @@ RSpec.describe "Member upcoming changes", type: :system do)SiteSetting.enable_upload_debug_mode = true+ SiteSetting.about_page_extra_groups_show_description = falseendcontext "when user is logged in" do