Skip to content

Commit

Permalink
Make sure Digest loading is thread-safe
Browse files Browse the repository at this point in the history
I'm defining the hashers in constants to avoid any performance overhead
by the mutex since we hash a lot of URLs

Digest() is only thread safe in Ruby 2.2.0 and newer. Patch:
ruby/ruby@c02fa39

I tried creating a test for this, but it's hard to provoke the error
with the old code to verify the test.

Closes #20
  • Loading branch information
jage committed Jun 4, 2015
1 parent 1a60d80 commit e755340
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions lib/twingly/url/hasher.rb
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
require 'digest/md5'
require 'digest/sha2'
require 'digest'

module Twingly
module URL
module Hasher
module_function

# Instantiate digest classes in a thread-safe manner
# This is important since we don't know how people will
# use this gem (if they require it in a thread safe way)
MD5_DIGEST = Digest(:MD5)
SHA256_DIGEST = Digest(:SHA256)

def taskdb_hash(url)
Digest::MD5.hexdigest(url)[0..29].upcase
MD5_DIGEST.hexdigest(url)[0..29].upcase
end

def blogstream_hash(url)
Digest::MD5.hexdigest(url)[0..29].upcase
MD5_DIGEST.hexdigest(url)[0..29].upcase
end

def documentdb_hash(url)
Digest::SHA256.digest(url).unpack("L!")[0]
SHA256_DIGEST.digest(url).unpack("L!")[0]
end

def autopingdb_hash(url)
Digest::SHA256.digest(url).unpack("q")[0]
SHA256_DIGEST.digest(url).unpack("q")[0]
end

def pingloggerdb_hash(url)
Digest::SHA256.digest(url).unpack("Q")[0]
SHA256_DIGEST.digest(url).unpack("Q")[0]
end
end
end
Expand Down

0 comments on commit e755340

Please sign in to comment.