Class: BarnyardCcfeeder::CacheCow

Inherits:
Object
  • Object
show all
Defined in:
lib/barnyard_ccfeeder.rb

Constant Summary collapse

CACHE_TIME =
4
RETRY_INTERVAL =
10
MAX_RETRIES =

0 * 24 * 60 * 60 / RETRY_INTERVAL # retry for 30 days max.

3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ CacheCow

Returns a new instance of CacheCow.



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
# File 'lib/barnyard_ccfeeder.rb', line 22

def initialize(args)


  @debug = args.fetch(:debug) { false }
  @log = args.fetch(:logger) { Logger.new(STDOUT) }

  @secret_key = args.fetch(:secret_key) { "" }
  @url = args.fetch(:url) { raise "You must provide :url" }

  @max_retries = args.fetch(:max_retries) { MAX_RETRIES }
  @retry_interval = args.fetch(:retry_interval) { RETRY_INTERVAL }
  @cache_time = args.fetch(:cache_time) { CACHE_TIME }

  @resource = RestClient::Resource.new @url

  @crops_time = Time.now
  @subscribers_time = Time.now
  @subscriptions_time = Time.now

  @crops_by_crop_number_cache = Hash.new

  @connected = false
  @retries = 0

  while !@connected && (@retries < @max_retries)
    @retries += 1
    begin
      # Try and load the crops to make sure we have a connection
      #          YAML::ENGINE.yamler = 'syck'
      Crack::JSON.parse(@resource["crops.json"].get)
      @connected = true
    rescue
      @log.fatal "(#{@retries}/#{@max_retries}) Unable to obtain connection to #{@url}/crops.json"
      sleep 2
    end
  end

  load_crops
  load_subscribers
  load_subscriptions

end

Instance Attribute Details

#crops_by_crop_number_cacheObject (readonly)

Returns the value of attribute crops_by_crop_number_cache.



17
18
19
# File 'lib/barnyard_ccfeeder.rb', line 17

def crops_by_crop_number_cache
  @crops_by_crop_number_cache
end

#crops_cacheObject (readonly)

Returns the value of attribute crops_cache.



17
18
19
# File 'lib/barnyard_ccfeeder.rb', line 17

def crops_cache
  @crops_cache
end

#crops_timeObject (readonly)

Returns the value of attribute crops_time.



17
18
19
# File 'lib/barnyard_ccfeeder.rb', line 17

def crops_time
  @crops_time
end

#subscribers_cacheObject (readonly)

Returns the value of attribute subscribers_cache.



17
18
19
# File 'lib/barnyard_ccfeeder.rb', line 17

def subscribers_cache
  @subscribers_cache
end

#subscribers_timeObject (readonly)

Returns the value of attribute subscribers_time.



17
18
19
# File 'lib/barnyard_ccfeeder.rb', line 17

def subscribers_time
  @subscribers_time
end

#subscriptions_cacheObject (readonly)

Returns the value of attribute subscriptions_cache.



17
18
19
# File 'lib/barnyard_ccfeeder.rb', line 17

def subscriptions_cache
  @subscriptions_cache
end

#subscriptions_timeObject (readonly)

Returns the value of attribute subscriptions_time.



17
18
19
# File 'lib/barnyard_ccfeeder.rb', line 17

def subscriptions_time
  @subscriptions_time
end

Instance Method Details

#calc(secret_key, payload) ⇒ Object

private



295
296
297
298
299
300
301
302
303
# File 'lib/barnyard_ccfeeder.rb', line 295

def calc(secret_key, payload)

  digest = OpenSSL::Digest::Digest.new('sha1')

  sig = OpenSSL::HMAC.hexdigest(digest, secret_key, payload)

  return sig

end

#cropsObject



145
146
147
148
149
150
151
152
153
154
155
# File 'lib/barnyard_ccfeeder.rb', line 145

def crops

  if (@crops_time + CACHE_TIME) > Time.now
    @log.debug "Using cached #{@url}/crops.json"
    return @crops_cache
  end

  load_crops
  return @crops_cache

end

#crops_by_crop_numberObject



133
134
135
136
137
138
139
140
141
142
143
# File 'lib/barnyard_ccfeeder.rb', line 133

def crops_by_crop_number

  if (@crops_time + CACHE_TIME) > Time.now
    @log.debug "Using cached #{@url}/crops.json"
    return @crops_by_crop_number_cache
  end

  load_crops
  return @crops_by_crop_number_cache

end

#deliver(path, data) ⇒ Object



305
306
307
308
309
# File 'lib/barnyard_ccfeeder.rb', line 305

def deliver(path, data)

  raw_deliver "#{@url}/#{path}", data

end

#has_subscribers(crop_number) ⇒ Object



194
195
196
197
198
199
200
201
# File 'lib/barnyard_ccfeeder.rb', line 194

def has_subscribers(crop_number)
  subscribed = Array.new
  subscribers.each do |id,data|
    data["id"] = id
    subscribed << data if subscribed?(id, crop_number)
  end
  subscribed
end

#load_cropsObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/barnyard_ccfeeder.rb', line 65

def load_crops
  begin
#        YAML::ENGINE.yamler = 'syck'
    crops = Crack::JSON.parse(@resource["crops.json"].get)

    @log.debug "Getting #{@url}/crops.json"

    @crops_cache = Hash.new

    crops.each do |crop|
      @crops_cache[crop["id"]] = crop
      @crops_by_crop_number_cache[crop['crop_number']] = crop
    end

    @crops_time = Time.now

  rescue
    @log.warn "Unable to get crops.json, using cached copy"
  end

end

#load_subscribersObject



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/barnyard_ccfeeder.rb', line 87

def load_subscribers
  begin
#        YAML::ENGINE.yamler = 'syck'
    subscribers = Crack::JSON.parse(@resource["subscribers.json"].get)

    @log.debug "Getting #{@url}/subscribers.json"

    @subscribers_cache = Hash.new

    subscribers.each do |subscriber|
      @subscribers_cache[subscriber['id']] = subscriber
    end

    @subscribers_time = Time.now

  rescue
    @log.warn "Unable to get subscribers.json, using cached copy"
  end
end

#load_subscriptionsObject



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
# File 'lib/barnyard_ccfeeder.rb', line 107

def load_subscriptions
  begin
#        YAML::ENGINE.yamler = 'syck'
    subscriptions = Crack::JSON.parse(@resource["subscriptions.json"].get)

    @log.debug "Getting #{@url}/subscriptions.json"

    @subscriptions_cache = Hash.new

    self.crops if @crops_cache.empty?
    self.subscribers if @subscribers_cache.empty?

    subscriptions.each do |subscription|
      subscription['crop'] = @crops_cache[subscription['crop_id']]
      subscription['subscriber'] = @subscribers_cache[subscription['subscriber_id']]
      @subscriptions_cache[subscription['id']] = subscription
    end

    @subscriptions_time = Time.now

  rescue
    @log.warn "Unable to get subscriptions.json, using cached copy"
  end

end

#push_change(queued_at, harvester_uuid, change_uuid, crop_number, primary_key, transaction_type, value, old_value) ⇒ Object

a “change” is detected by the harvester



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
229
230
231
232
233
234
235
# File 'lib/barnyard_ccfeeder.rb', line 204

def push_change(queued_at, harvester_uuid, change_uuid, crop_number, primary_key, transaction_type, value, old_value)

  data = Hash.new

  data['harvester_uuid'] = harvester_uuid
  data['crop_number'] = crop_number
  data['queue_time'] = queued_at
  data['primary_key'] = primary_key

  begin
#        YAML::ENGINE.yamler = 'syck'
    data['previous_value'] = old_value
  rescue Exception => e
    data['previous_value'] = ""
  end

  begin
#        YAML::ENGINE.yamler = 'syck'
    data['current_value'] = value
  rescue Exception => e
    data['current_value'] = ""
  end

  data['uuid'] = change_uuid
  data['transaction_type'] = transaction_type

  change = Hash.new
  change["change"] = data

  return deliver("changes", change)

end

#push_delivery_status(queued_at, delivery_uuid, transaction_uuid, endpoint_response_code, endpoint_response_header, endpoint_response_data, endpoint_response_date) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/barnyard_ccfeeder.rb', line 254

def push_delivery_status(queued_at, delivery_uuid, transaction_uuid, endpoint_response_code, endpoint_response_header, endpoint_response_data, endpoint_response_date)

  data = Hash.new

  data['queue_time'] = queued_at
  data['uuid'] = delivery_uuid
  data['transaction_uuid'] = transaction_uuid
  data['endpoint_response_code'] = endpoint_response_code
  data['endpoint_response_header'] = endpoint_response_header
  data['endpoint_response_data'] = endpoint_response_data
  data['endpoint_response_date'] = endpoint_response_date

  delivery = Hash.new
  delivery["delivery"] = data

  return deliver("deliveries", delivery)

end

#push_harvester_stats(harvester_uuid, crop_number, began_at, ended_at, total_records, number_of_changes, number_of_adds, number_of_deletes) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/barnyard_ccfeeder.rb', line 273

def push_harvester_stats(harvester_uuid, crop_number, began_at, ended_at, total_records, number_of_changes, number_of_adds, number_of_deletes)

  data = Hash.new

  data['uuid'] = harvester_uuid
  data['crop_number'] = crop_number
  data['began_at'] = began_at
  data['ended_at'] = ended_at
  data['total_records'] = total_records
  data['number_of_changes'] = number_of_changes
  data['number_of_adds'] = number_of_adds
  data['number_of_deletes'] = number_of_deletes

  harvest = Hash.new
  harvest["harvest"] = data

  return deliver("harvests", harvest)

end

#push_transaction(subscription_id, queued_at, change_uuid, transaction_uuid) ⇒ Object

a “transaction” is sent to a subscriber by the farmer based on the “change”



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/barnyard_ccfeeder.rb', line 238

def push_transaction(subscription_id, queued_at, change_uuid, transaction_uuid)

  data = Hash.new

  data['subscription_id'] = subscription_id
  data['queue_time'] = queued_at
  data['change_uuid'] = change_uuid
  data['uuid'] = transaction_uuid

  transaction = Hash.new
  transaction["transaction"] = data

  return deliver("transactions", transaction)

end

#raw_deliver(path, data) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/barnyard_ccfeeder.rb', line 312

def raw_deliver(path, data)

  payload = data.to_json

  @delivered = false
  @retries = 0

  result = {:code => 0, :headers => String.new, :body => String.new}

  while !@delivered && (@retries < @max_retries)
    @retries += 1
    begin

      end_point = RestClient::Resource.new path

      sig = calc @secret_key, payload

      headers_to_send = {:content_type => :json, :accept => :json}
      headers_to_send["X_HUB_SIGNATURE"] = sig unless @secret_key.empty?
      response = end_point.post payload, headers_to_send

      @log.debug headers_to_send.inspect

      if (200..201) === response.code
        @delivered = true
        @log.info "Payload delivered to #{path} #{response.code}"

        result[:code] = response.code
        result[:headers] = response.headers
        result[:body] = response.body

        return result
      else
        @log.warn "#{response.code}"

        @log.warn "Retrying #{@retries}/#{@max_retries} in  #{@retry_interval} seconds..."

        sleep RETRY_INTERVAL
      end
    rescue Exception => e
      @log.fatal "ERROR: #{e}"

      @log.fatal "Retrying #{@retries}/#{@max_retries} in  #{@retry_interval} seconds..."
    end

  end # while

  return result

end

#subscribed?(subscriber_id, crop_number) ⇒ Boolean

Returns:

  • (Boolean)


181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/barnyard_ccfeeder.rb', line 181

def subscribed?(subscriber_id, crop_number)

  @subscriptions_cache.each do |id, subscription|

    if subscription["subscriber_id"] == subscriber_id && subscription["crop"]["crop_number"].to_i == crop_number.to_i
      return true
    end
  end

  false

end

#subscribersObject



157
158
159
160
161
162
163
164
165
166
167
# File 'lib/barnyard_ccfeeder.rb', line 157

def subscribers

  if (@subscribers_time + CACHE_TIME) > Time.now
    @log.debug "Using cached #{@url}/subscribers.json"
    return @subscribers_cache
  end

  load_subscribers
  return @subscribers_cache

end

#subscriptionsObject



169
170
171
172
173
174
175
176
177
178
179
# File 'lib/barnyard_ccfeeder.rb', line 169

def subscriptions

  if (@subscriptions_time + CACHE_TIME) > Time.now
    @log.debug "Using cached #{@url}/subscriptions.json"
    return @subscriptions_cache
  end

  load_subscriptions
  return @subscriptions_cache

end