A platform for community discussion. Free, open, simple.
FEATURE: Automatic promotion of upcoming changes (#36211)
Martin Brennanf6d85d1a2a85
diff --git a/app/services/problem_check/upcoming_change_stable_opted_out.rb b/app/services/problem_check/upcoming_change_stable_opted_out.rbindex 7c9a85c1b56..fea11c3b53b 100644--- a/app/services/problem_check/upcoming_change_stable_opted_out.rb+++ b/app/services/problem_check/upcoming_change_stable_opted_out.rb@@ -2,6 +2,7 @@class ProblemCheck::UpcomingChangeStableOptedOut < ProblemCheckself.perform_every = 1.hour+ self.targets = -> { SiteSetting.upcoming_change_site_settings }def callreturn no_problem if !SiteSetting.enable_upcoming_changes@@ -25,8 +26,4 @@ class ProblemCheck::UpcomingChangeStableOptedOut < ProblemCheckdef translation_data(upcoming_change){ upcoming_change: SiteSetting.humanized_name(upcoming_change) }end-- def targets- SiteSetting.upcoming_change_site_settings- endenddiff --git a/app/services/upcoming_changes/promote.rb b/app/services/upcoming_changes/promote.rbnew file mode 100644index 00000000000..6789d1300a6--- /dev/null+++ b/app/services/upcoming_changes/promote.rb@@ -0,0 +1,87 @@+# 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++ 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+enddiff --git a/app/services/upcoming_changes/toggle.rb b/app/services/upcoming_changes/toggle.rbindex 060ec6b5d76..e4c6493949c 100644--- a/app/services/upcoming_changes/toggle.rb+++ b/app/services/upcoming_changes/toggle.rb@@ -3,6 +3,10 @@class UpcomingChanges::Toggleinclude Service::Base+ # For cases like the UpcomingChanges::Promote where we don't want to log+ # the change again since it's already being logged there.+ options { attribute :log_change, default: true }+params doattribute :setting_name, :stringattribute :enabled, :boolean@@ -24,7 +28,7 @@ class UpcomingChanges::ToggleSiteSetting.respond_to?(params.setting_name)end- def toggle(params:, guardian:)+ def toggle(params:, guardian:, options:)# TODO (martin) Remove this once we release upcoming changes,# otherwise it will be confusing for people to see log messages# about upcoming changes via "What's new?" experimental toggles@@ -32,14 +36,21 @@ class UpcomingChanges::Toggleif SiteSetting.enable_upcoming_changesprevious_value = SiteSetting.public_send(params.setting_name)SiteSetting.send("#{params.setting_name}=", params.enabled)- StaffActionLogger.new(guardian.user).log_upcoming_change_toggle(- params.setting_name,- previous_value,- params.enabled,- { context: I18n.t("staff_action_logs.upcoming_changes.log_manually_toggled") },- )++ if options.log_change+ StaffActionLogger.new(guardian.user).log_upcoming_change_toggle(+ params.setting_name,+ previous_value,+ params.enabled,+ { context: I18n.t("staff_action_logs.upcoming_changes.log_manually_toggled") },+ )+ endelse- SiteSetting.set_and_log(params.setting_name, params.enabled, guardian.user)+ if options.log_change+ SiteSetting.set_and_log(params.setting_name, params.enabled, guardian.user)+ else+ SiteSetting.public_send("#{params.setting_name}=", params.enabled)+ endendendenddiff --git a/config/initializers/015_promote_upcoming_changes.rb b/config/initializers/015_promote_upcoming_changes.rbnew file mode 100644index 00000000000..bd694b1ee91--- /dev/null+++ b/config/initializers/015_promote_upcoming_changes.rb@@ -0,0 +1,91 @@+# 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_relative "../../lib/upcoming_changes"++Rails.application.config.after_initialize { UpcomingChanges::AutoPromotionInitializer.call }++class UpcomingChanges::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++ 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.",+ )+ end++ on_success do+ verbose_log(site, :info, "Successfully promoted '#{setting_name}' to enabled.")+ end+ end+ end+ end+ end+enddiff --git a/config/initializers/100-logster.rb b/config/initializers/100-logster.rbindex debcbaf0a66..6f12cb1e54d 100644--- a/config/initializers/100-logster.rb+++ b/config/initializers/100-logster.rb@@ -7,6 +7,11 @@ if GlobalSetting.skip_redis?returnend+if (Rails.env.local?) && ENV["FORCE_RAILS_LOGS_STDOUT"] == "1"+ Rails.logger = Logger.new(STDOUT)+ return+end+if Rails.env.development? && !Sidekiq.server? && ENV["RAILS_LOGS_STDOUT"] == "1"Rails.application.config.after_initialize doconsole = ActiveSupport::Logger.new(STDOUT)diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex de69d7110c0..53c9c939659 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -5638,9 +5638,7 @@ en:upcoming_changes:log_manually_toggled: "Manually toggled by user"log_promoted: >- This upcoming change was automatically enabled because it reached the '%{change_status}' status, which meets or exceeds the defined promotion status of '%{promotion_status_threshold}' on your site.-- See the <a href="%{base_url}/admin/config/upcoming-changes">upcoming changes page</a> for more detail.+ This upcoming change reached '%{change_status}' status, so it was automatically enabled on your site. See the <a href="%{base_path}/admin/config/upcoming-changes">upcoming changes page</a> for more detail.reviewables:already_handled: "Thanks, but we've already reviewed that post and determined it does not need to be flagged again."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 0d64a8fa34e..0ce64852ca4 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -583,6 +583,9 @@ basic:- stable- neverhidden: true+ upcoming_change_verbose_logging:+ default: false+ hidden: truelogin:login_required:@@ -4299,11 +4302,3 @@ experimental:default: falsehidden: trueclient: true- fake_upcoming_change:- default: false- hidden: true- client: true- upcoming_change:- status: "alpha"- impact: "other,all_members"- learn_more_url: "https://meta.discourse.org"diff --git a/lib/upcoming_changes.rb b/lib/upcoming_changes.rbindex 7056e3acd08..f79c4b009e9 100644--- a/lib/upcoming_changes.rb+++ b/lib/upcoming_changes.rb@@ -2,7 +2,8 @@module UpcomingChangesdef self.statuses- @statuses ||= Enum.new(experimental: 0, alpha: 100, beta: 200, stable: 300, permanent: 500)+ @statuses ||=+ Enum.new(experimental: 0, alpha: 100, beta: 200, stable: 300, permanent: 500, never: 9999)enddef self.image_exists?(change_setting_name)diff --git a/spec/initializers/015_promote_upcoming_changes_spec.rb b/spec/initializers/015_promote_upcoming_changes_spec.rbnew file mode 100644index 00000000000..96e437523f7--- /dev/null+++ b/spec/initializers/015_promote_upcoming_changes_spec.rb@@ -0,0 +1,162 @@+# frozen_string_literal: true++RSpec.describe "Promote upcoming changes initializer" 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++ 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/multisite/015_promote_upcoming_changes_initializer_spec.rb b/spec/multisite/015_promote_upcoming_changes_initializer_spec.rbnew file mode 100644index 00000000000..981af10d1b2--- /dev/null+++ b/spec/multisite/015_promote_upcoming_changes_initializer_spec.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++RSpec.describe "Promote upcoming changes initializer", 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: :stable,+ impact_type: "feature",+ impact_role: "admins",+ },+ },+ )+ end++ it "works for multisites that satisfy promotion criteria" do+ test_multisite_connection("default") do+ expect(SiteSetting.enable_upload_debug_mode).to be(false)+ end+ test_multisite_connection("second") do+ expect(SiteSetting.enable_upload_debug_mode).to be(false)+ end++ UpcomingChanges::AutoPromotionInitializer.call++ test_multisite_connection("default") do+ expect(SiteSetting.enable_upload_debug_mode).to be(true)+ end+ test_multisite_connection("second") do+ expect(SiteSetting.enable_upload_debug_mode).to be(true)+ end+ end+ end+enddiff --git a/spec/services/staff_action_logger_spec.rb b/spec/services/staff_action_logger_spec.rbindex 6f73455449d..d80cc3902a9 100644--- a/spec/services/staff_action_logger_spec.rb+++ b/spec/services/staff_action_logger_spec.rb@@ -229,7 +229,12 @@ RSpec.describe StaffActionLogger doit "records the details of why the toggle happened" dodetails =- "This upcoming change was automatically enabled because it reached the 'Beta' status, which meets or exceeds the defined promotion status of 'Beta' on your site. See <a href='#{Discourse.base_url}/admin/config/upcoming-changes'>the upcoming changes page for details</a>."+ I18n.t(+ "staff_action_logs.upcoming_changes.log_promoted",+ change_status: UpcomingChanges.change_status(:allow_user_locale),+ base_path: Discourse.base_path,+ )+result = logger.log_upcoming_change_toggle("allow_user_locale", false, true, { details: })expect(result.details).to eq(details)enddiff --git a/spec/services/upcoming_changes/promote_spec.rb b/spec/services/upcoming_changes/promote_spec.rbnew file mode 100644index 00000000000..a00d3f0e05a--- /dev/null+++ b/spec/services/upcoming_changes/promote_spec.rb@@ -0,0 +1,131 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::Promote do+ describe described_class::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+ 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+ end+ end+enddiff --git a/spec/support/fake_logger.rb b/spec/support/fake_logger.rbindex d7c291d9cef..7ce3fd8f2b4 100644--- a/spec/support/fake_logger.rb+++ b/spec/support/fake_logger.rb@@ -14,6 +14,14 @@ class FakeLogger@severities = { 0 => :debugs, 1 => :infos, 2 => :warnings, 3 => :errors, 4 => :fatals }end+ def all_messages_to_s+ @debugs.each { |msg| puts "DEBUG: #{msg}" }+ @infos.each { |msg| puts "INFO: #{msg}" }+ @warnings.each { |msg| puts "WARN: #{msg}" }+ @errors.each { |msg| puts "ERROR: #{msg}" }+ @fatals.each { |msg| puts "FATAL: #{msg}" }+ end+def debug(message = nil)@debugs << messageend