From f2fae5b852221e61910894b851f8cf2588ca9485 Mon Sep 17 00:00:00 2001 From: Owen Stephens Date: Thu, 5 Oct 2023 18:58:10 +0100 Subject: [PATCH] Use more-efficient Redis `sismember` command to check if feature exists --- lib/flipper/adapter.rb | 7 +++++++ lib/flipper/adapters/redis.rb | 5 +++++ lib/flipper/feature.rb | 2 +- spec/flipper/adapters/redis_spec.rb | 6 ++++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/flipper/adapter.rb b/lib/flipper/adapter.rb index edd8ff6fb..bfc962659 100644 --- a/lib/flipper/adapter.rb +++ b/lib/flipper/adapter.rb @@ -43,6 +43,13 @@ def get_multi(features) result end + # Public: Does a feature with this key exist. + # + # Returns true if a feature exists with this key, else false. + def exist?(key) + features.include?(key) + end + # Public: Ensure that adapter is in sync with source adapter provided. # # source - The source dsl, adapter or export to import. diff --git a/lib/flipper/adapters/redis.rb b/lib/flipper/adapters/redis.rb index 1edf6267f..d60ef84e7 100644 --- a/lib/flipper/adapters/redis.rb +++ b/lib/flipper/adapters/redis.rb @@ -32,6 +32,11 @@ def features read_feature_keys end + # Public: Does a feature with this key exist. + def exist?(key) + @client.sismember(features_key, key) + end + # Public: Adds a feature to the set of known features. def add(feature) if redis_sadd_returns_boolean? diff --git a/lib/flipper/feature.rb b/lib/flipper/feature.rb index f446f921e..81e457d5a 100644 --- a/lib/flipper/feature.rb +++ b/lib/flipper/feature.rb @@ -79,7 +79,7 @@ def add # # Returns true if exists in adapter else false. def exist? - instrument(:exist?) { adapter.features.include?(key) } + instrument(:exist?) { adapter.exist?(key) } end # Public: Removes this feature. diff --git a/spec/flipper/adapters/redis_spec.rb b/spec/flipper/adapters/redis_spec.rb index b4fb7472d..f7c59f35b 100644 --- a/spec/flipper/adapters/redis_spec.rb +++ b/spec/flipper/adapters/redis_spec.rb @@ -20,6 +20,12 @@ it_should_behave_like 'a flipper adapter' + it 'correctly identifies if a with feature with the given name exists' do + expect { + subject.add(Flipper::Feature.new(:foo, subject)) + }.to change { subject.exist?(:foo) }.from(false).to(true) + end + it 'configures itself on load' do Flipper.configuration = nil Flipper.instance = nil