rely on Mongo::Client to deal with connections, no more thread.current (fix issue locomotivecms/engine#1120)

did committed Feb 15, 2016
commit 8f56d0ebb74f45f477113660f7ff4a814241d071
Showing 2 changed files with 65 additions and 1 deletions
locomotive/steam/adapters/mongodb.rb b/lib/locomotive/steam/adapters/mongodb.rb +16 -1
@@ @@ -59,6 +59,21 @@ module Locomotive::Steam
end
end
+ class << self
+
+ attr_reader :session
+
+ def build_session(uri_or_hosts, client_options)
+ @session ||= Mongo::Client.new(uri_or_hosts, client_options)
+ end
+
+ def disconnect_session
+ @session.try(:close)
+ @session = nil
+ end
+
+ end
+
private
def query_klass
@@ @@ -86,7 +101,7 @@ module Locomotive::Steam
end
def session
- Thread.current[:mongo_session] ||= Mongo::Client.new(uri_or_hosts, client_options)
+ self.class.build_session(uri_or_hosts, client_options)
end
def uri_or_hosts
spec/integration/adapters/mongodb_spec.rb +49 -0
@@ @@ -0,0 +1,49 @@
+ require 'spec_helper'
+
+ require_relative '../../../lib/locomotive/steam/adapters/mongodb.rb'
+
+ describe Locomotive::Steam::MongoDBAdapter do
+
+ let(:adapter) { Locomotive::Steam::MongoDBAdapter.new(database: 'steam_test', hosts: ['127.0.0.1:27017'], min_pool_size: 2, max_pool_size: 5) }
+
+ before(:all) do
+ described_class.disconnect_session
+ @before_connections = current_connections
+ end
+
+ describe '#session' do
+
+ subject { adapter.send(:session) }
+
+ it { is_expected.not_to eq nil }
+
+ it "don't create more Mongo sessions than the max pool" do
+ 10.times { subject['locomotive_sites'].find.count }
+ _after = current_connections
+ expect(_after).to be >= (@before_connections + 2) # min_pool_size
+ expect(_after).to be <= (@before_connections + 5) # max_pool_size
+ end
+
+ end
+
+ describe '.disconnect_session' do
+
+ let(:connection) { adapter.send(:session) }
+
+ subject { described_class.disconnect_session }
+
+ it { is_expected.to eq nil }
+
+ it 'closes clients' do
+ 10.times { connection['locomotive_sites'].find.count }
+ subject
+ expect(current_connections).to eq @before_connections
+ end
+
+ end
+
+ def current_connections
+ `mongo --eval "db.serverStatus().connections.current"`.split("\n").last.to_i
+ end
+
+ end