changeset 219:17461f7682a2

One client for everyone
author nanaya <me@nanaya.pro>
date Thu, 27 May 2021 02:28:18 +0900
parents c5a101bc4a09
children 0e15b4db2da8
files app/lib/clients.rb app/models/tweet.rb
diffstat 2 files changed, 26 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/app/lib/clients.rb	Thu May 27 02:28:18 2021 +0900
@@ -0,0 +1,23 @@
+class Clients
+  def self.client_options(id)
+    {
+      :timeouts => {
+        :connect => 5,
+        :read => 5,
+        :write => 5,
+      },
+    }.merge $cfg[:twitter][id]
+  end
+
+  def self.instance
+    @@instance ||= self.new
+  end
+
+  def initialize
+    @clients = {}
+  end
+
+  def get(id)
+    @clients[id] ||= Twitter::REST::Client.new(self.class.client_options id)
+  end
+end
--- a/app/models/tweet.rb	Thu May 27 01:53:53 2021 +0900
+++ b/app/models/tweet.rb	Thu May 27 02:28:18 2021 +0900
@@ -79,7 +79,7 @@
   end
 
   def client
-    @clients[client_config_id] ||= Twitter::REST::Client.new(self.class.client_options client_config_id)
+    Clients.instance.get client_config_id
   end
 
   def client_try(method, *args)
@@ -88,7 +88,7 @@
     begin
       data = client.public_send method, *args
     rescue Twitter::Error::TooManyRequests
-      @client_config_id += 1
+      @client_config_id = (1 + @client_config_id) % @client_config_count
 
       if initial_config_id == client_config_id
         raise
@@ -106,6 +106,6 @@
     @client_config_count ||= $cfg[:twitter].size
     @client_config_id ||= rand(@client_config_count)
 
-    @client_config_id %= @client_config_count
+    @client_config_id
   end
 end