Evaluate compiled blocks in an isolated Binding

Re-using the Binding of the XPath::Compiler#compile method would lead to
race conditions, and possibly a memory leak due to the Binding sticking
around for compiled Proc's lifetime.

By using a dedicated class (and its corresponding Binding) we can work
around this. Access to this class is not synchronized as compiled Procs
don't mutate their enclosing environment.

The race condition can be demonstrated using code such as the
following:

    xml = <<-EOF
    <people>
      <person>
        <name>Alice</name>
      </person>

      <person>
        <name>Bob</name>
      </person>

      <person>
        <name>Eve</name>
      </person>
    </people>
    EOF

    4.times.map do
      Thread.new do
        10_000.times do
          document = Oga.parse_xml(xml)

          document.at_xpath('people/person/name').text
        end
      end
    end.each(&:join)

Running this code would result in NoMethodErrors due to "at_xpath"
returning a NilClass opposed to an Oga::XML::Element.
This commit is contained in:
Yorick Peterse committed 2015-09-07 14:02:31 +02:00
1 parent b07c75e964
commit bd48dc15cc
5 files changed
+69 -1

No files matched your search

+22
View File
@@ -49,5 +49,27 @@ describe Oga::XPath::Compiler do
block.call(doc).should be_an_instance_of(Oga::XML::NodeSet)
end
end
# This test relies on Binding#receiver (Binding#self on Rubinius), which
# sadly isn't available on all tested Ruby versions.
#
# Procs should have their own Binding as otherwise concurrent usage could
# lead to race conditions due to variable scopes and such being re-used.
[:receiver, :self].each do |binding_method|
if Binding.method_defined?(binding_method)
describe 'the returned Proc' do
it 'uses an isolated Binding' do
ast = parse_xpath('foo')
block = @compiler.compile(ast)
binding_context = block.binding.send(binding_method)
binding_context.should be_an_instance_of(Oga::XPath::Context)
end
end
break
end
end
end
end
+23
View File
@@ -0,0 +1,23 @@
require 'spec_helper'
describe Oga::XPath::Context do
describe '#evaluate' do
it 'returns the result of eval()' do
context = described_class.new
context.evaluate('10').should == 10
end
describe 'assigning a variable in a lambda' do
it 'assigns the variable locally to the lambda' do
context = described_class.new
block = context.evaluate('lambda { number = 10 }')
block.call
expect { context.evaluate('number') }.to raise_error(NameError)
end
end
end
end