Skip to content

Commit

Permalink
MONGOID-5820 Fix the session object leak when using transactions (#5878
Browse files Browse the repository at this point in the history
…) (#5893)

Co-authored-by: Valerii Goncharenko <virusx777@gmail.com>
  • Loading branch information
comandeo-mongo and Virus-X authored Oct 23, 2024
1 parent 7fcafa7 commit 361e92b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
1 change: 1 addition & 0 deletions lib/mongoid/clients/sessions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def with_session(options = {})
rescue *transactions_not_supported_exceptions
raise Mongoid::Errors::TransactionsNotSupported
ensure
Threaded.clear_modified_documents(session)
Threaded.clear_session(client: persistence_context.client)
end

Expand Down
5 changes: 2 additions & 3 deletions lib/mongoid/threaded.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ module Threaded
CURRENT_SCOPE_KEY = '[mongoid]:current-scope'

AUTOSAVES_KEY = '[mongoid]:autosaves'

VALIDATIONS_KEY = '[mongoid]:validations'

STACK_KEYS = Hash.new do |hash, key|
Expand Down Expand Up @@ -376,9 +377,7 @@ def add_modified_document(session, document)
# @return [ Set<Mongoid::Document> ] Collection of modified documents before
# it was cleared.
def clear_modified_documents(session)
modified_documents[session].dup
ensure
modified_documents[session].clear
modified_documents.delete(session) || []
end

# Queries whether document callbacks should be executed by default for the
Expand Down
19 changes: 19 additions & 0 deletions spec/mongoid/threaded_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,23 @@
end
end
end

describe '#clear_modified_documents' do
let(:session) do
double(Mongo::Session).tap do |session|
allow(session).to receive(:in_transaction?).and_return(true)
end
end

context 'when there are modified documents' do
before do
described_class.add_modified_document(session, Minim.new)
described_class.clear_modified_documents(session)
end

it 'removes the documents and keys' do
expect(described_class.modified_documents).to be_empty
end
end
end
end

0 comments on commit 361e92b

Please sign in to comment.