Skip to content

Commit

Permalink
Shared: add #server? method
Browse files Browse the repository at this point in the history
This method returns true when the wrapper is running in server mode
  • Loading branch information
asppsa committed Sep 8, 2019
1 parent e3a0c00 commit 31e0950
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
18 changes: 13 additions & 5 deletions lib/moneta/shared.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def initialize(options = {}, &block)

# (see Proxy#close)
def close
if @server
if server?
@server.stop
@thread.join
@server = @thread = nil
Expand All @@ -34,13 +34,20 @@ def close
end
end

# Returns true if this wrapper is running as the server
#
# @return [Boolean] wrapper is a server
def server?
@server != nil
end

protected

def wrap(*args)
connect
yield
rescue Errno::ECONNRESET, Errno::EPIPE, IOError, SystemCallError
@connect_lock.synchronize { close unless @server }
@connect_lock.synchronize { close unless server? }
tries ||= 0
(tries += 1) < 3 ? retry : raise
end
Expand All @@ -50,21 +57,22 @@ def connect
@connect_lock.synchronize do
@adapter ||= Adapters::Client.new(@options)
end
rescue Errno::ECONNREFUSED, Errno::ENOENT => ex
rescue Errno::ECONNREFUSED, Errno::ENOENT, IOError => ex
start_server
tries ||= 0
warn "Moneta::Shared - Failed to connect: #{ex.message}" if tries > 0
(tries += 1) < 3 ? retry : raise
(tries += 1) < 10 ? retry : raise
end

# TODO: Implement this using forking (MRI) and threading (JRuby)
# to get maximal performance
def start_server
@connect_lock.synchronize do
return if server?
begin
raise "Adapter already set" if @adapter
@adapter = Lock.new(@builder.build.last)
raise "Server already set" if @server
raise "Server already set" if server?
@server = Server.new(@adapter, @options)
@thread = Thread.new { @server.run }
sleep 0.1 until @server.running?
Expand Down
10 changes: 10 additions & 0 deletions spec/moneta/proxies/shared/shared_tcp_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@

# The first store initialised will be running the server
context "running as the server" do
before do
store.load('dummy')
expect(store.server?).to be true
end

include_examples :shared_tcp

it 'has the underlying adapter' do
Expand All @@ -35,6 +40,11 @@
new_store.tap { |store| store.load('dummy') } # Makes a connection
end

before do
store.load('dummy')
expect(store.server?).to be false
end

after do
server_store.close
end
Expand Down

0 comments on commit 31e0950

Please sign in to comment.