Skip to content
This repository was archived by the owner on Jun 21, 2023. It is now read-only.

Commit

Permalink
Merge pull request #14 from github/avoid-openssl
Browse files Browse the repository at this point in the history
Avoid loading openssl + securerandom unless needed
  • Loading branch information
rtomayko committed Apr 1, 2015
2 parents c5151c0 + d3a7ccb commit b47de77
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions lib/statsd.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
require 'openssl'
require 'securerandom'
require 'socket'
require 'time'
require 'zlib'

# = Statsd: A Statsd client (https://github.com/etsy/statsd)
Expand Down Expand Up @@ -32,9 +29,6 @@ def initialize(host, port, key = nil)
#characters that will be replaced with _ in stat names
RESERVED_CHARS_REGEX = /[\:\|\@]/

# Digest object as a constant
SHA256 = OpenSSL::Digest::SHA256.new

class << self
# Set to any standard logger instance (including stdlib's Logger) to enable
# stat logging using logger.debug
Expand Down Expand Up @@ -150,11 +144,22 @@ def select_host(stat)
end

def signed_payload(key, message)
sha256 = Statsd.setup_openssl
payload = timestamp + nonce + message
signature = OpenSSL::HMAC.digest(SHA256, key, payload)
signature = OpenSSL::HMAC.digest(sha256, key, payload)
signature + payload
end

# defer loading openssl and securerandom unless needed. this shaves ~10ms off
# of baseline require load time for environments that don't require message signing.
def self.setup_openssl
@sha256 ||= begin
require 'securerandom'
require 'openssl'
OpenSSL::Digest::SHA256.new
end
end

def timestamp
[Time.now.to_i].pack("Q<")
end
Expand Down

0 comments on commit b47de77

Please sign in to comment.