DEV: factor code to reduce risk of crashed collector thread

DEV: factor code to reduce risk of crashed collector thread

Previously there was a subtle edge case (closed stderr) where an iteration could fail.

This avoids this by problem by ensuring that no matter what an iteration passes

diff --git a/lib/reporter/global.rb b/lib/reporter/global.rb
index 180aba0..1cf833c 100644
--- a/lib/reporter/global.rb
+++ b/lib/reporter/global.rb
@@ -2,31 +2,31 @@
 
 module DiscoursePrometheus::Reporter
   class Global
+
     def self.clear_connections!
       ActiveRecord::Base.connection_handler.clear_active_connections!
+    end
+
+    def self.iteration(global_collector, client)
+      clear_connections!
+      metric = global_collector.collect
+      client.send_json metric
+      clear_connections!
     rescue => e
       begin
         Discourse.warn_exception(e, message: "Failed to clear active connections")
       rescue => e1
-        # never crash this thread
-        STDERR.puts "ERR failed to log warning: #{e1}"
+        # never crash an iteration
+        STDERR.puts "ERR failed to log warning: #{e1}" rescue nil
       end
     end
 
     def self.start(client)
       global_collector = new
       Thread.new do
-        clear_connections!
         while true
-          begin
-            metric = global_collector.collect
-            client.send_json metric
-          rescue => e
-            Discourse.warn_exception(e, message: "Prometheus Discourse Failed To Collect Global Stats")
-          ensure
-            clear_connections!
-            sleep 5
-          end
+          iteration(global_collector, client)
+          sleep 5
         end
       end
 

GitHub sha: 5b7a8bbc

2 Likes