From 2ab93a440eb19c5d6b6035caaacedaed652be5ff Mon Sep 17 00:00:00 2001 From: Christian Sutter Date: Wed, 8 Jan 2025 11:15:37 +0000 Subject: [PATCH] Add feature flag to toggle autocomplete This adds a feature flag to disable autocomplete in case of unforeseen problems by returning an empty set of completion results in the response. This is controlled by the env var `ENABLE_SEARCH_AUTOCOMPLETE`, and will allow us to consolidate the logic behind disabling autocomplete in a single place instead of having it scattered across several apps (as the component will not render completions if no results are returned). --- app/controllers/autocompletes_controller.rb | 8 +++++++- config/application.rb | 6 ++++++ spec/requests/autocomplete_request_spec.rb | 15 +++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/app/controllers/autocompletes_controller.rb b/app/controllers/autocompletes_controller.rb index 156b6e4..21458fa 100644 --- a/app/controllers/autocompletes_controller.rb +++ b/app/controllers/autocompletes_controller.rb @@ -1,10 +1,16 @@ class AutocompletesController < ApplicationController def show - render json: DiscoveryEngine::Autocomplete::Complete.new(query).completion_result + render json: completion_result end private + def completion_result + return CompletionResult.new(suggestions: []) unless Rails.configuration.enable_autocomplete + + DiscoveryEngine::Autocomplete::Complete.new(query).completion_result + end + def query params[:q] end diff --git a/config/application.rb b/config/application.rb index 272479c..fd7ec0e 100644 --- a/config/application.rb +++ b/config/application.rb @@ -40,5 +40,11 @@ class Application < Rails::Application ## currently only using a single instance (the Publishing "shared" Redis). If we ever need to ## use multiple Redis instances, this is the only place that needs updating. config.redlock_redis_instances = [config.redis_url] + + # Feature flags + def self.feature_flag(name, default: false) + ActiveModel::Type::Boolean.new.cast(ENV.fetch(name, default)) + end + config.enable_autocomplete = feature_flag("GOVUK_SEARCH_ENABLE_AUTOCOMPLETE", default: true) end end diff --git a/spec/requests/autocomplete_request_spec.rb b/spec/requests/autocomplete_request_spec.rb index ce6c0ee..1278233 100644 --- a/spec/requests/autocomplete_request_spec.rb +++ b/spec/requests/autocomplete_request_spec.rb @@ -17,4 +17,19 @@ }) end end + + context "when autocomplete is disabled through the feature flag" do + before do + allow(Rails.configuration).to receive(:enable_autocomplete).and_return(false) + end + + it "returns empty suggestions" do + get "/autocomplete.json?q=foo" + + expect(response).to have_http_status(:ok) + expect(JSON.parse(response.body)).to eq({ + "suggestions" => [], + }) + end + end end