aboutsummaryrefslogtreecommitdiffstats
path: root/core/plugin/streaming/perma_streamer.rb
blob: d80fe8a9fc83e5237bb52e7adf1271851fd25152 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding: utf-8 -*-
# 自動でコネクションを貼り直すStreamer
require_relative 'streamer'

module ::Plugin::Streaming
  class PermaStreamer

    # ==== Args
    # [service] 接続するService
    def initialize(service)
      @service = service
      @thread = Thread.new(&method(:mainloop))
      @fail = MikuTwitter::StreamingFailedActions.new('UserStream', Plugin.create(:streaming)) end

    def mainloop
      loop do
        begin
          streamer = Plugin::Streaming::Streamer.new(@service){
            @fail.success
          }
          result = streamer.thread.value
        rescue Net::ReadTimeout => exception
          @fail.notify(exception)
        rescue Net::HTTPError => exception
          warn "PermaStreamer caught exception"
          warn exception
          @fail.notify(exception)
        rescue Exception => exception
          warn "PermaStreamer caught exception"
          warn exception
          @fail.notify(exception)
        else
          notice "PermaStreamer exit"
          notice result
          @fail.notify(result)
        ensure
          streamer.kill if streamer
        end
        notice "retry wait #{@fail.wait_time}, fail_count #{@fail.fail_count}"
        sleep @fail.wait_time
      end
    end

    def kill
      @thread.kill
    end

  end
end