Class: ActiveCypher::ConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/active_cypher/connection_pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(spec) ⇒ ConnectionPool

Returns a new instance of ConnectionPool.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/active_cypher/connection_pool.rb', line 9

def initialize(spec)
  @spec = spec.symbolize_keys

  # Set defaults for pool configuration
  @spec[:pool_size] ||= ENV.fetch('BOLT_POOL_SIZE', 10).to_i
  @spec[:pool_timeout] ||= ENV.fetch('BOLT_POOL_TIMEOUT', 5).to_i
  @spec[:max_retries] ||= ENV.fetch('BOLT_MAX_RETRIES', 3).to_i

  # Handle URL-based configuration if present
  if @spec[:url] && !@spec.key?(:adapter)
    resolver = ActiveCypher::ConnectionUrlResolver.new(@spec[:url])
    resolved_config = resolver.to_hash

    raise ArgumentError, "Invalid connection URL: #{@spec[:url]}" unless resolved_config

    # Merge the resolved config with any additional options
    @spec = resolved_config.merge(@spec.except(:url))
  end

  @conn_ref = nil # holds the adapter instance
  @creation_mutex = Mutex.new # prevents multiple threads from creating connections simultaneously
end

Instance Attribute Details

#connection_keyObject (readonly)

Returns the value of attribute connection_key.



7
8
9
# File 'lib/active_cypher/connection_pool.rb', line 7

def connection_key
  @connection_key
end

#specObject (readonly)

Returns the value of attribute spec.



7
8
9
# File 'lib/active_cypher/connection_pool.rb', line 7

def spec
  @spec
end

Instance Method Details

#connectionObject Also known as: checkout

Returns a live adapter, initializing it once in a thread‑safe way.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/active_cypher/connection_pool.rb', line 33

def connection
  # Fast path — already connected and alive
  conn = @conn_ref
  return conn if conn&.active?

  # Use mutex for the slow path to prevent thundering herd
  @creation_mutex.synchronize do
    # Check again inside the mutex in case another thread created it
    conn = @conn_ref
    return conn if conn&.active?

    # Create a new connection
    new_conn = build_connection
    @conn_ref = new_conn
    return new_conn
  end
end

#disconnectObject

Explicitly close and reset the connection



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/active_cypher/connection_pool.rb', line 58

def disconnect
  conn = @conn_ref
  return unless conn

  begin
    conn.disconnect
  rescue StandardError => e
    # Log but don't raise to ensure cleanup continues
    puts "Warning: Error disconnecting: #{e.message}" if ENV['DEBUG']
  ensure
    @conn_ref = nil
  end
end

#troubled?Boolean

Check if the pool has a persistent connection issue

Returns:

  • (Boolean)


53
54
55
# File 'lib/active_cypher/connection_pool.rb', line 53

def troubled?
  @retry_count >= @spec[:max_retries]
end