easypost-ruby icon indicating copy to clipboard operation
easypost-ruby copied to clipboard

[Bug]: Easypost.api_key is not threadsafe

Open andychongyz opened this issue 3 years ago • 3 comments

Software Version

4.0.3

Language Version

3.0.3

Operating System

mac os monterey

What happened?

The Easypost.api_key attribute is not threadsafe.

Running the code below in a rails console can easily show that the attribute is not threadsafe.

EasyPost.api_key = "EASYPOST_MAIN_API_KEY"

def with_account(account_api_key)
  old_api_key = EasyPost.api_key
  puts "old_api_key: #{old_api_key}"
  EasyPost.api_key = account_api_key
  yield
  puts "done"
ensure
  EasyPost.api_key = old_api_key
end

(1..5).each do |i|
  Thread.new do
    puts "Thread #{i} started"
    with_account("test_api_key_#{i}") do
      sleep(rand(2..5))
    end
  end
end

What was expected?

EasyPost.api_key should be threadsafe since I believe that a lot of Rails app is running on puma with a multi-thread setup.

Sample Code

No response

Relevant logs

No response

andychongyz avatar Jun 20 '22 07:06 andychongyz

Here is how ActiveResource deals with threadsafe class attributes. https://github.com/rails/activeresource/blob/main/lib/active_resource/threadsafe_attributes.rb

andychongyz avatar Jun 20 '22 08:06 andychongyz

Thank you for opening this issue and providing the documentation link.

We are aware about the lack of thread-safety in our client libraries, and are actively working to rectify this.

nwithan8 avatar Jun 20 '22 14:06 nwithan8

Here's how I patch the code, for now, to make it threadsafe. Hope it helps.

EasyPost.module_eval do
  class << self
    include ThreadsafeAttributes

    threadsafe_attribute :api_key
  end
end

andychongyz avatar Jun 21 '22 04:06 andychongyz

Wanted to provide an update, we're beginning the work for a new major release (v5) of this library that will contain a new client object which will enable this library to be thread safe. The work will happen over the coming weeks. We'll update everyone here when v5 is released and ultimately, when this library is thread safe which is the primary concern of the new major version.

Justintime50 avatar Apr 04 '23 20:04 Justintime50

We will be releasing v5.0.0 which is a thread-safe rewrite of this library within the next couple hours. We'd encourage anyone who needs thread-safety to upgrade.

Justintime50 avatar Jun 06 '23 20:06 Justintime50