lib/activehook/hook.rb in activehook-0.1.0 vs lib/activehook/hook.rb in activehook-0.1.3
- old
+ new
@@ -1,56 +1,74 @@
require 'securerandom'
module ActiveHook
class Hook
- attr_accessor :uri, :payload, :id, :created_at, :retry_at, :fail_at
+ attr_accessor :uri, :payload, :id, :key, :retry_max, :retry_time, :created_at
def initialize(options = {})
options = defaults.merge(options)
options.each { |key, value| send("#{key}=", value) }
end
def perform
- valid?
+ validate!
ActiveHook.redis.with do |conn|
- conn.pipelined do
- conn.lpush('ah:queue', to_json)
- conn.incr('ah:total_queued')
- end
+ @id = conn.incr('ah:total_queued')
+ conn.lpush('ah:queue', to_json)
+ conn.zadd('ah:validation', @id, @key)
end
end
- def bump_retry
- @retry_at = Time.now.to_i + ActiveHook.config.retry_time
+ def retry?
+ fail_at > Time.now.to_i
end
- def retry?
- @fail_at.to_i > Time.now.to_i
+ def retry_at
+ Time.now.to_i + @retry_time.to_i
end
+ def fail_at
+ @created_at.to_i + retry_max_time
+ end
+
+ def retry_max_time
+ @retry_time.to_i * @retry_max.to_i
+ end
+
def to_json
{ id: @id,
+ key: @key,
created_at: @created_at,
- retry_at: @retry_at,
- fail_at: @fail_at,
+ retry_time: @retry_time,
+ retry_max: @retry_max,
uri: @uri,
payload: @payload }.to_json
end
+ def secure_payload
+ { hook_id: @id,
+ hook_key: @key,
+ payload: @payload }.to_json
+ end
+
+ def valid?
+ HookValidator.new(id: @id, key: @key).server_valid?
+ end
+
private
def defaults
- { id: SecureRandom.uuid,
+ { key: SecureRandom.uuid,
created_at: Time.now.to_i,
- retry_at: Time.now.to_i + ActiveHook.config.retry_time,
- fail_at: Time.now.to_i + ActiveHook.config.retry_max_time }
+ retry_time: 3600,
+ retry_max: 3 }
end
- def valid?
+ def validate!
raise Errors::Hook, 'Payload must be a Hash.' unless @payload.is_a?(Hash)
raise Errors::Hook, 'URI is not a valid format.' unless @uri =~ /\A#{URI::regexp}\z/
raise Errors::Hook, 'Created at must be an Integer.' unless @created_at.is_a?(Integer)
- raise Errors::Hook, 'Retry at must be an Integer.' unless @retry_at.is_a?(Integer)
- raise Errors::Hook, 'Fail at must be an Integer.' unless @fail_at.is_a?(Integer)
+ raise Errors::Hook, 'Retry time must be an Integer.' unless @retry_time.is_a?(Integer)
+ raise Errors::Hook, 'Retry max must be an Integer.' unless @retry_max.is_a?(Integer)
end
end
end