diff --git a/lib/ldclient-rb/impl/integrations/file_data_source.rb b/lib/ldclient-rb/impl/integrations/file_data_source.rb index 1b3cbf8b..63dfc37b 100644 --- a/lib/ldclient-rb/impl/integrations/file_data_source.rb +++ b/lib/ldclient-rb/impl/integrations/file_data_source.rb @@ -43,6 +43,7 @@ def initialize(data_store, data_source_update_sink, logger, options={}) @version_lock = Mutex.new @last_version = 1 + @load_lock = Mutex.new end def initialized? @@ -56,24 +57,38 @@ def start # the difference can be detected by checking "initialized?" ready.set - load_all - if @auto_update - # If we're going to watch files, then the start event will be set the first time we get - # a successful load. - @listener = start_listener + begin + @listener = start_listener + rescue => e + @logger.error { "[LDClient] Unable to watch data files for changes, so file changes will not be applied: #{e.message}" } + end + end + + loaded = false + begin + load_all + loaded = true + ensure + stop unless loaded end ready end def stop - @listener.stop unless @listener.nil? + listener = @listener + @listener = nil + listener&.stop end private def load_all + @load_lock.synchronize { load_all_locked } + end + + def load_all_locked all_data = { Impl::DataStore::FEATURES => {}, Impl::DataStore::SEGMENTS => {}, @@ -174,7 +189,13 @@ def start_listener_with_listen_gem(resolved_paths) load_all end end - l.start + started = false + begin + l.start + started = true + ensure + l.stop unless started + end l end diff --git a/lib/ldclient-rb/impl/integrations/file_data_source_v2.rb b/lib/ldclient-rb/impl/integrations/file_data_source_v2.rb index 3e9753bd..bfeb259e 100644 --- a/lib/ldclient-rb/impl/integrations/file_data_source_v2.rb +++ b/lib/ldclient-rb/impl/integrations/file_data_source_v2.rb @@ -116,9 +116,23 @@ def fetch(selector_store) # @return [void] # def sync(selector_store) - # First yield initial data + listener = nil + begin + listener = start_listener unless @lock.synchronize { @closed } + rescue => e + @logger.error { "[LDClient] Unable to watch data files for changes, so file changes will not be applied: #{e.message}" } + end + if listener + closed = @lock.synchronize do + @listener = listener unless @closed + @closed + end + listener.stop if closed + end + initial_fetch = fetch(selector_store) unless initial_fetch.success? + stop_listener yield LaunchDarkly::Interfaces::DataSystem::Update.new( state: LaunchDarkly::Interfaces::DataSource::Status::OFF, error: LaunchDarkly::Interfaces::DataSource::ErrorInfo.new( @@ -136,11 +150,6 @@ def sync(selector_store) change_set: initial_fetch.value.change_set ) - # Start watching for file changes - @lock.synchronize do - @listener = start_listener unless @closed - end - until @closed begin update = @update_queue.pop @@ -173,17 +182,22 @@ def stop @lock.synchronize do return if @closed @closed = true - - listener = @listener - @listener = nil - - listener&.stop end + stop_listener # Signal shutdown to sync generator @update_queue.push(nil) end + private def stop_listener + listener = @lock.synchronize do + l = @listener + @listener = nil + l + end + listener&.stop + end + # # Load all files and build a changeset. # @@ -362,7 +376,7 @@ def stop # # Start watching files for changes. # - # @return [Object] auto-updater instance + # @return [Object, nil] auto-updater instance, or nil if no path can be watched # private def start_listener resolved_paths = @paths.map do |p| @@ -373,6 +387,7 @@ def stop nil end end.compact + return nil if resolved_paths.empty? if @@have_listen start_listener_with_listen_gem(resolved_paths) @@ -397,7 +412,13 @@ def stop on_file_change end end - l.start + started = false + begin + l.start + started = true + ensure + l.stop unless started + end l end end diff --git a/lib/ldclient-rb/impl/integrations/file_override_source.rb b/lib/ldclient-rb/impl/integrations/file_override_source.rb index e9214f3d..30277a0b 100644 --- a/lib/ldclient-rb/impl/integrations/file_override_source.rb +++ b/lib/ldclient-rb/impl/integrations/file_override_source.rb @@ -52,8 +52,8 @@ def initialize(paths:, duplicate_keys_handling:, change_detection:, poll_interva attr_reader :poll_interval # - # Performs the initial load synchronously, so overrides present in the files are in effect - # when this method returns, then starts change detection. A file that does not exist yet + # Starts change detection, then performs the initial load synchronously, so overrides + # present in the files are in effect when this method returns. A file that does not exist yet # contributes no overrides. A file that cannot be read or parsed is not fatal: the client # runs with the last good overrides, the failure is logged, and the retry plus the change # signal recover once the file is readable. @@ -61,7 +61,7 @@ def initialize(paths:, duplicate_keys_handling:, change_detection:, poll_interva # (see LaunchDarkly::Interfaces::Overrides::OverrideSource#start) # def start(sink) - @lock.synchronize do + reloader = @lock.synchronize do return if @stopped @reloader = FileData::Reloader.new( @@ -77,12 +77,6 @@ def start(sink) log_overrides_in_effect(merged) end ) - end - - @reloader.reload_now - - @lock.synchronize do - return if @stopped trigger = @reloader.method(:trigger) @change_detector = @@ -91,7 +85,10 @@ def start(sink) else FileData::Poller.new(@paths, @poll_interval, trigger, @logger) end + @reloader end + + reloader.reload_now end # (see LaunchDarkly::Interfaces::Overrides::OverrideSource#stop) diff --git a/lib/ldclient-rb/integrations/file_data.rb b/lib/ldclient-rb/integrations/file_data.rb index ebd82648..9ad7cb28 100644 --- a/lib/ldclient-rb/integrations/file_data.rb +++ b/lib/ldclient-rb/integrations/file_data.rb @@ -101,7 +101,9 @@ module FileData # Note that the default implementation of this feature is based on polling the filesystem, # which may not perform well. If you install the 'listen' gem (not included by default, to # avoid adding unwanted dependencies to the SDK), its native file watching mechanism will be - # used instead. + # used instead. On platforms other than Linux, the 'listen' gem can miss a change that occurs + # while the data source starts. The data source then uses the earlier contents until the + # next change to a file. # @option options [Float] :poll_interval The minimum interval, in seconds, between checks for # file modifications - used only if auto_update is true, and if the native file-watching # mechanism from 'listen' is not being used. The default value is 1 second. @@ -125,7 +127,9 @@ def self.data_source(options={}) # may be absolute paths or relative to the current working directory. (Required) # @option options [Float] :poll_interval The minimum interval, in seconds, between checks for # file modifications - used only if the native file-watching mechanism from 'listen' is not - # being used. The default value is 1 second. + # being used. The default value is 1 second. On platforms other than Linux, the 'listen' gem can miss a change that occurs + # while the data source starts. The data source then uses the earlier contents until the + # next change to a file. # @return [FileDataSourceV2Builder] a builder that can be used as an FDv2 initializer or synchronizer # # @example Using as an initializer @@ -225,7 +229,8 @@ def self.data_source_v2(options = {}) # including the update of a mounted Kubernetes ConfigMap. It does not follow a deployment that # points a link further along the path, or a configured directory, at another location, such as a # `current` link to a release directory, or that replaces a configured directory. Use polling for - # such deployments. + # such deployments. On platforms other than Linux, watching can miss a change that occurs while + # the source starts. The source then uses the earlier contents until the next change to a file. # @option options [Numeric] :poll_interval Seconds between examinations of the files in polling # mode. The default is 1. An interval below 1 is raised to 1 with a warning. # @return [FileOverrideSourceBuilder] a builder for {LaunchDarkly::DataSystem::ConfigBuilder#overrides} diff --git a/spec/integrations/file_data_source_spec.rb b/spec/integrations/file_data_source_spec.rb index 4ba8e9b1..3959cdba 100644 --- a/spec/integrations/file_data_source_spec.rb +++ b/spec/integrations/file_data_source_spec.rb @@ -328,6 +328,121 @@ def test_auto_reload(options) test_auto_reload({ auto_update: true, force_polling: true, poll_interval: 0.1 }) end + def test_reload_of_change_during_first_load(options) + file = make_temp_file(flag_only_json) + options[:paths] = [ file.path ] + + with_data_source(options) do |ds| + first_load = true + allow(ds).to receive(:load_all_locked).and_wrap_original do |original| + original.call + if first_load + first_load = false + sleep(1) + IO.write(file, all_properties_json) + end + end + + ds.start + + max_time = 10 + ok = wait_for_condition(max_time) { @store.all(LaunchDarkly::Impl::DataStore::SEGMENTS).keys == all_segment_keys } + expect(ok).to eq(true), "Waited #{max_time}s after modifying file during the first load and it did not reload" + end + end + + it "reloads a file modified during the first load if auto-update is on" do + test_reload_of_change_during_first_load({ auto_update: true }) + end + + it "reloads a file modified during the first load in polling mode" do + test_reload_of_change_during_first_load({ auto_update: true, force_polling: true, poll_interval: 0.1 }) + end + + def test_reload_of_change_before_first_store_update(options) + file = make_temp_file(flag_only_json) + options[:paths] = [ file.path ] + sink = @config.data_source_update_sink + + with_data_source(options) do |ds| + first_init = true + allow(sink).to receive(:init).and_wrap_original do |original, data| + if first_init + first_init = false + sleep(1) + IO.write(file, all_properties_json) + sleep(1.5) + end + original.call(data) + end + + ds.start + + max_time = 10 + ok = wait_for_condition(max_time) { @store.all(LaunchDarkly::Impl::DataStore::SEGMENTS).keys == all_segment_keys } + expect(ok).to eq(true), "Waited #{max_time}s and the older first load replaced the newer data" + end + end + + it "keeps a change made before the first load updates the store if auto-update is on" do + test_reload_of_change_before_first_store_update({ auto_update: true, poll_interval: 0.1 }) + end + + it "keeps a change made before the first load updates the store in polling mode" do + test_reload_of_change_before_first_store_update({ auto_update: true, force_polling: true, poll_interval: 0.1 }) + end + + def test_stop_watching_if_first_load_raises(options, error_class = StandardError) + file = make_temp_file(flag_only_json) + sink = @config.data_source_update_sink + allow(sink).to receive(:init).and_raise(error_class, "store failure") + ds = FileData.data_source(options.merge(paths: [ file.path ], auto_update: true)).call('', @config) + listener = nil + allow(ds).to receive(:start_listener).and_wrap_original do |original| + listener = original.call + end + + expect { ds.start }.to raise_error(error_class, "store failure") + yield listener + expect { ds.stop }.not_to raise_error + end + + it "stops watching if the first load raises" do + test_stop_watching_if_first_load_raises({}) do |listener| + expect(listener.stopped?).to eq(true) + end + end + + it "stops watching if the first load raises an exception that is not a StandardError" do + test_stop_watching_if_first_load_raises({}, Interrupt) do |listener| + expect(listener.stopped?).to eq(true) + end + end + + it "stops polling if the first load raises" do + test_stop_watching_if_first_load_raises({ force_polling: true, poll_interval: 0.1 }) do |listener| + expect(listener.instance_variable_get(:@thread).join(2)).not_to be_nil + end + end + + it "loads the files if the file watcher cannot start" do + file = make_temp_file(all_properties_json) + + with_data_source({ paths: [ file.path ], auto_update: true }) do |ds| + allow(ds).to receive(:start_listener).and_raise(StandardError, "watch failure") + expect { ds.start }.not_to raise_error + expect(@store.initialized?).to eq(true) + expect(@store.all(LaunchDarkly::Impl::DataStore::SEGMENTS).keys).to eq(all_segment_keys) + end + end + + it "reports a missing file instead of raising if auto-update is on" do + with_data_source({ paths: [ bad_file_path ], auto_update: true }) do |ds| + expect { ds.start }.not_to raise_error + expect(@store.initialized?).to eq(false) + end + end + it "evaluates simplified flag with client as expected" do file = make_temp_file(all_properties_json) factory = FileData.data_source({ paths: file.path }) diff --git a/spec/integrations/file_data_source_v2_spec.rb b/spec/integrations/file_data_source_v2_spec.rb index 2f157999..f4e8db33 100644 --- a/spec/integrations/file_data_source_v2_spec.rb +++ b/spec/integrations/file_data_source_v2_spec.rb @@ -362,6 +362,156 @@ def no_selector_store end end + def expect_change_during_initial_fetch_detected + file = make_temp_file(flag_only_json) + + source = Impl::Integrations::FileDataSourceV2.new( + logger, + paths: [file.path], + poll_interval: 0.1 + ) + + first_load = true + allow(source).to receive(:load_all_to_changeset).and_wrap_original do |original| + result = original.call + if first_load + first_load = false + sleep 1 + IO.write(file, segment_only_json) + end + result + end + + updates = [] + update_received = Concurrent::Event.new + + begin + sync_thread = Thread.new do + source.sync(no_selector_store) do |update| + updates << update + update_received.set if updates.length >= 2 + break if updates.length >= 2 + end + end + + expect(update_received.wait(5)).to eq(true), "Did not receive an update for the change made during the initial fetch" + expect(updates[1].state).to eq(LaunchDarkly::Interfaces::DataSource::Status::VALID) + + segment_changes = updates[1].change_set.changes.select { |c| c.kind == LaunchDarkly::Interfaces::DataSystem::ObjectKind::SEGMENT } + expect(segment_changes.length).to eq(1) + ensure + source.stop + sync_thread&.join(2) + end + end + + it "detects a file change made during the initial fetch" do + expect_change_during_initial_fetch_detected + end + + it "detects a file change made during the initial fetch in polling mode" do + have_listen = Impl::Integrations::FileDataSourceV2.class_variable_get(:@@have_listen) + Impl::Integrations::FileDataSourceV2.class_variable_set(:@@have_listen, false) + begin + expect_change_during_initial_fetch_detected + ensure + Impl::Integrations::FileDataSourceV2.class_variable_set(:@@have_listen, have_listen) + end + end + + def first_sync_update(source) + updates = [] + sync_thread = Thread.new do + source.sync(no_selector_store) do |update| + updates << update + break + end + end + expect(sync_thread.join(5)).not_to be_nil, "sync did not return" + updates[0] + ensure + source.stop + sync_thread&.join(2) + end + + it "does not watch the working directory when no path exists" do + expect(Listen).not_to receive(:to) if defined?(Listen) + source = Impl::Integrations::FileDataSourceV2.new(logger, paths: [File.join(@tmp_dir, "no-such-file")]) + + update = first_sync_update(source) + + expect(update.state).to eq(LaunchDarkly::Interfaces::DataSource::Status::OFF) + end + + it "yields the file data if the file watcher cannot start" do + file = make_temp_file(all_properties_json) + source = Impl::Integrations::FileDataSourceV2.new(logger, paths: [file.path]) + allow(source).to receive(:start_listener).and_raise(StandardError, "watch failure") + + update = first_sync_update(source) + + expect(update.state).to eq(LaunchDarkly::Interfaces::DataSource::Status::VALID) + expect(update.change_set.changes).not_to be_empty + end + + it "stops a file watcher that fails part way through its start" do + file = make_temp_file(all_properties_json) + source = Impl::Integrations::FileDataSourceV2.new(logger, paths: [file.path]) + listener = nil + lock_held_at_stop = nil + allow(Listen).to receive(:to).and_wrap_original do |original, *args, **opts, &block| + listener = original.call(*args, **opts, &block) + allow(listener).to receive(:start).and_raise(StandardError, "watch failure") + allow(listener).to receive(:stop).and_wrap_original do |stop, *stop_args| + lock_held_at_stop = source.instance_variable_get(:@lock).owned? + stop.call(*stop_args) + end + listener + end + + update = first_sync_update(source) + + expect(update.state).to eq(LaunchDarkly::Interfaces::DataSource::Status::VALID) + expect(listener.stopped?).to eq(true) + expect(lock_held_at_stop).to eq(false) + end + + it "stops a file watcher whose start raises an exception that is not a StandardError" do + file = make_temp_file(all_properties_json) + source = Impl::Integrations::FileDataSourceV2.new(logger, paths: [file.path]) + error_class = Interrupt + listener = nil + allow(Listen).to receive(:to).and_wrap_original do |original, *args, **opts, &block| + listener = original.call(*args, **opts, &block) + allow(listener).to receive(:start).and_raise(error_class, "watch failure") + listener + end + + begin + expect { source.sync(no_selector_store) { |_update| break } }.to raise_error(error_class) + expect(listener.stopped?).to eq(true) + ensure + source.stop + end + end + + it "stops the file watcher if the source stops while the watcher starts" do + file = make_temp_file(all_properties_json) + source = Impl::Integrations::FileDataSourceV2.new(logger, paths: [file.path]) + listener = nil + allow(source).to receive(:start_listener).and_wrap_original do |original| + listener = original.call + source.stop + listener + end + + first_sync_update(source) + + expect(listener).not_to be_nil + expect(source.instance_variable_get(:@listener)).to be_nil + expect(listener.stopped?).to eq(true) + end + it "reports error on invalid file update" do file = make_temp_file(flag_only_json) diff --git a/spec/integrations/file_override_source_spec.rb b/spec/integrations/file_override_source_spec.rb index bbc7a894..0535bdd9 100644 --- a/spec/integrations/file_override_source_spec.rb +++ b/spec/integrations/file_override_source_spec.rb @@ -95,6 +95,20 @@ def make_source(paths, duplicate_keys_handling: :fail, change_detection: :pollin ) end + # Writes the file once, right after the initial load reads the files. + def write_after_initial_load(name, content) + first = true + allow_any_instance_of(Impl::FileData::Reloader).to receive(:reload_now).and_wrap_original do |original, *args| + result = original.call(*args) + if first + first = false + sleep(1) + File.write(path(name), content) + end + result + end + end + def with_source(paths, **options) source = make_source(paths, **options) sink = RecordingSink.new @@ -375,6 +389,16 @@ def deleted_message(category, key, file) end describe "polling change detection" do + it "applies a change made during the initial load" do + a = write("a.json", values_doc({ flag1: "a" })) + write_after_initial_load("a.json", values_doc({ flag1: "bb" })) + + with_source([a]) do |_source, sink| + expect(wait_for { sink.snapshots.length == 2 }).to be true + expect(sink.flag_values).to eq({ "flag1" => "bb" }) + end + end + it "applies a changed file" do a = write("a.json", values_doc({ flag1: "a" })) @@ -467,6 +491,16 @@ def deleted_message(category, key, file) skip "the listen gem is not installed" unless Impl::FileData::Watcher.available? end + it "applies a change made during the initial load" do + a = write("a.json", values_doc({ flag1: "a" })) + write_after_initial_load("a.json", values_doc({ flag1: "bb" })) + + with_source([a], change_detection: :watching) do |_source, sink| + expect(wait_for { sink.snapshots.length == 2 }).to be true + expect(sink.flag_values).to eq({ "flag1" => "bb" }) + end + end + it "applies a changed file" do a = write("a.json", values_doc({ flag1: "a" }))