aboutsummaryrefslogtreecommitdiffstats
path: root/lib/receiver/worker.rb
blob: 860d890f0fefcab58a0b0a746e57ac263dc370b8 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
require "time"

module EM
  class Connection
    def send_chunk(data)
      send_data(data + "\r\n")
    end
  end
end

class Receiver::Worker < DaemonSpawn::Base
  class DBProxyServer < EM::Connection
    $worker_count = nil
    @@wq = EM::WorkQueue::WorkQueue.new do |arg|
      begin
      begin
        json = ::Yajl::Parser.parse(arg.last, :symbolize_keys => true)
      rescue ::Yajl::ParseError
        # JSON parse error....??
        p $!
      end

      case arg.first
      when "USER"
        $logger.debug("Received User")
        rec = User.find_or_initialize_by(:id => json[:id])
        rec.screen_name = json[:screen_name]
        rec.name = json[:name]
        rec.profile_image_url = json[:profile_image_url]
        rec.save! if rec.changed?
      when "TWEET"
        $logger.debug("Received Tweet")
        begin
          Tweet.create!(:id => json[:id],
                        :text => json[:text],
                        :source => json[:source],
                        :tweeted_at => Time.parse(json[:tweeted_at]),
                        :user_id => json[:user_id])
          $logger.debug("Saved Tweet")
        rescue ActiveRecord::RecordNotUnique
          $logger.info("Can't Save Tweet: Duplicate")
        end
      when "FAVORITE"
        $logger.debug("Received Favorite")
        begin
          Favorite.create!(:tweet_id => json[:tweet_id],
                           :user_id => json[:user_id])
          $logger.debug("Saved Favorite")
        rescue ActiveRecord::RecordNotUnique
          $logger.info("Can't Save Tweet: Duplicate")
        end
      when "UNFAVORITE"
        Favorite
          .where("tweet_id = #{json[:tweet_id]} AND user_id = #{json[:user_id]}")
          .destroy_all
      when "RETWEET"
        $logger.debug("Received Retweet")
        begin
          Retweet.create!(:id => json[:id],
                          :tweet_id => json[:tweet_id],
                          :user_id => json[:user_id])
          $logger.debug("Saved Retweet")
        rescue ActiveRecord::RecordNotUnique
          $logger.info("Can't Save Retweet: Duplicate")
        end
      when "DELETE"
        tweet = Tweet.find_by(:id => json[:id]) || Retweet.find_by(:id => json[:id])
        if tweet
          tweet.destroy
        end
      else
        # ???
        puts "???????"
      end
      rescue
        $logger.error($!)
        $logger.error($@)
      end
    end
    @@wq.start

    def initialize
      @worker_number = nil
      @receive_buf = ""
    end

    def post_init
      # なにもしない。クライアントが
    end

    def unbind
      $connections.delete_if{|k, v| v == self}
      $logger.info("Connection closed")
    end

    def send_account_all
      Account.where("id % ? = ?", $worker_count, @worker_number).each do |account|
        puts "Sent #{account.id}/#{account.user_id}"
        send_account(account)
      end
    end

    def send_account(account)
      send_chunk("ACCOUNT #{Yajl::Encoder.encode(account.attributes)}")
    end

    def receive_data(data)
      @receive_buf << data
      while line = @receive_buf.slice!(/.+?\r\n/)
        line.chomp!
        next if line == ""
        arg = line.split(/ /, 2)
        case arg.first
        when "CONNECT"
          begin
            json = ::Yajl::Parser.parse(arg.last, :symbolize_keys => true)
          rescue ::Yajl::ParseError
            # JSON parse error....??
            p $!
          end
          secret_key = json[:secret_key]
          worker_number = json[:worker_number]
          worker_count = json[:worker_count]
          if secret_key == Settings.secret_key
            if $worker_count != worker_count && $connections.size > 0
              $logger.error("Error: Worker Count Difference: $worker_count=#{$worker_count}, worker_count=#{worker_count}")
              send_chunk("ERROR Invalid Worker Count")
              close_connection_after_writing
            else
              $worker_count = worker_count
              $connections[worker_number] = self
              @worker_number = worker_number
              @authorized = true
              $logger.info("Connected: #{worker_number}")
              send_chunk("OK Connected")
              send_account_all
            end
          else
            $logger.error("Error: Invalid Secret Key")
            send_chunk("ERROR Invalid Secret Key")
            close_connection_after_writing
          end
        when "UNAUTHORIZED"
          $logger.warn("Unauthorized: #{arg.last}")
          # unregister
        when "QUIT"
          $logger.info("Quit: #{@worker_number}")
          send_chunk("BYE")
          close_connection_after_writing
        else
          if @authorized
            @@wq.push arg
          end
        end
      end
    end
  end

  class RegisterServer < EM::Connection
    def initialize
      @receive_buf = ""
    end

    def post_init
    end

    def receive_data(data)
      @receive_buf << data
      while line = @receive_buf.slice!(/.+?\r\n/)
        line.chomp!
        next if line == ""
        p line
        sp = line.split(/ /, 2)
        if sp.first == "REGISTER"
          if sp.last =~ /^[0-9]+$/
            account = Account.find_by(:id => sp.last.to_i)
            if account
              if con = $connections[account.id % $worker_count]
                con.send_account(account)
                send_chunk("OK Registered")
              else
                send_chunk("OK Worker not found")
              end
            else
              $logger.error("Unknown account: #{sp.last}")
              send_chunk("ERROR Unknown Account")
            end
          else
            $logger.error("Invalid User ID")
            send_chunk("ERROR Invalid User ID")
          end
        else
          $logger.error("Unknown Command: #{sp})")
          send_chunk("ERROR Unknown command")
        end
        close_connection_after_writing
        return
      end
    end
  end

  def initialize(opts = {})
    super(opts)
    $logger = Receiver::Logger.new(:warn)
    $connections = {}
  end

  def start(args)
    $logger.info("Database Proxy Started")
    EM.run do
      stop = Proc.new do
        EM.stop
      end
      Signal.trap(:INT, &stop)
      Signal.trap(:QUIT, &stop)
      Signal.trap(:TERM, &stop)

      EM.start_server("0.0.0.0", Settings.db_proxy_port, DBProxyServer)
      EM.start_unix_domain_server(Settings.register_server_path, RegisterServer)
    end
  end

  def stop
  end
end