Module: Legion::Data::Connection
Defined Under Namespace
Classes: QueryFileLogger, SegmentedTaggedLogger, SlowQueryLogger
Constant Summary
collapse
- ADAPTERS =
%i[sqlite mysql2 postgres].freeze
- GENERIC_KEYS =
%i[max_connections pool_timeout preconnect single_threaded test name].freeze
- ADAPTER_KEYS =
{
sqlite: %i[timeout readonly disable_dqs],
postgres: %i[connect_timeout sslmode sslrootcert search_path],
mysql2: %i[connect_timeout read_timeout write_timeout encoding sql_mode]
}.freeze
- ADAPTER_DEFAULTS =
{
sqlite: { timeout: 5000, readonly: false, disable_dqs: true },
postgres: { connect_timeout: 20, sslmode: 'disable' },
mysql2: { connect_timeout: 120, encoding: 'utf8mb4' }
}.freeze
- QUERY_LOG_DIR =
File.expand_path('~/.legionio/logs').freeze
Class Attribute Summary collapse
Class Method Summary
collapse
handle_exception
Class Attribute Details
.sequel ⇒ Object
Returns the value of attribute sequel.
157
158
159
|
# File 'lib/legion/data/connection.rb', line 157
def sequel
@sequel
end
|
Class Method Details
.adapter ⇒ Object
159
160
161
|
# File 'lib/legion/data/connection.rb', line 159
def adapter
@adapter ||= Legion::Settings[:data][:adapter]&.to_sym || :sqlite
end
|
.connect_with_replicas ⇒ Object
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
# File 'lib/legion/data/connection.rb', line 300
def connect_with_replicas
return unless adapter == :postgres
replica_url = Legion::Settings[:data][:read_replica_url]
replica_list = Array(Legion::Settings[:data][:replicas]).dup
replica_list.prepend(replica_url) if replica_url && !replica_url.empty?
replica_list.uniq!
replica_list.compact!
return if replica_list.empty?
@sequel.extension(:server_block)
replica_list.each_with_index do |url, idx|
@sequel.add_servers("read_#{idx}": url)
end
@replica_servers = replica_list.each_with_index.map { |_, idx| :"read_#{idx}" }
log.debug "Registered #{@replica_servers.size} read replica(s)"
end
|
.connection_info ⇒ Object
Returns connection metadata for health checks and diagnostics. Apollo and other services can use this to detect silent fallback.
195
196
197
198
199
200
201
202
203
|
# File 'lib/legion/data/connection.rb', line 195
def connection_info
{
adapter: adapter,
connected: Legion::Settings[:data][:connected],
fallback_active: @fallback_active || false,
configured_adapter: Legion::Settings[:data][:adapter]&.to_sym || :sqlite,
sequel_alive: (begin; !@sequel&.test_connection.nil?; rescue StandardError; false; end)
}
end
|
.creds_builder(final_creds = {}) ⇒ Object
358
359
360
361
362
363
364
365
366
|
# File 'lib/legion/data/connection.rb', line 358
def creds_builder(final_creds = {})
final_creds.merge! Legion::Data::Settings.creds(adapter)
final_creds.merge! Legion::Settings[:data][:creds] if Legion::Settings[:data][:creds].is_a? Hash
port = final_creds[:port]
merge_tls_creds(final_creds, adapter: adapter, port: port)
final_creds
end
|
.fallback_active? ⇒ Boolean
Returns true if the data layer fell back to SQLite from a configured network database (PostgreSQL/MySQL). Services should check this and log warnings when operating in degraded mode.
208
209
210
|
# File 'lib/legion/data/connection.rb', line 208
def fallback_active?
@fallback_active == true
end
|
.merge_tls_creds(creds, adapter:, port:) ⇒ Object
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
|
# File 'lib/legion/data/connection.rb', line 332
def merge_tls_creds(creds, adapter:, port:)
return creds if adapter == :sqlite
return creds unless defined?(Legion::Crypt::TLS)
tls_settings = data_tls_settings
return creds unless tls_settings[:enabled] == true
tls = Legion::Crypt::TLS.resolve(tls_settings, port: port)
return creds unless tls[:enabled]
case adapter
when :postgres
creds[:sslmode] = tls[:verify] == :none ? 'require' : 'verify-full'
creds[:sslrootcert] = tls[:ca] if tls[:ca]
creds[:sslcert] = tls[:cert] if tls[:cert]
creds[:sslkey] = tls[:key] if tls[:key]
when :mysql2
creds[:ssl_mode] = tls[:verify] == :none ? 'required' : 'verify_identity'
creds[:sslca] = tls[:ca] if tls[:ca]
creds[:sslcert] = tls[:cert] if tls[:cert]
creds[:sslkey] = tls[:key] if tls[:key]
end
creds
end
|
.pool_stats ⇒ Object
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
# File 'lib/legion/data/connection.rb', line 228
def pool_stats
return {} unless @sequel
pool = @sequel.pool
stats = {
type: pool.pool_type,
size: pool.size,
max_size: pool.respond_to?(:max_size) ? pool.max_size : nil
}
case pool.pool_type
when :timed_queue, :sharded_timed_queue
queue_size = pool.instance_variable_get(:@queue)&.size || 0
stats[:available] = queue_size
stats[:in_use] = stats[:size] - queue_size
stats[:waiting] = pool.num_waiting
when :threaded, :sharded_threaded
avail = pool.instance_variable_get(:@available_connections)
stats[:available] = avail&.size || 0
stats[:in_use] = stats[:size] - stats[:available]
stats[:waiting] = pool.num_waiting
when :single, :sharded_single
stats[:available] = pool.size
stats[:in_use] = 0
stats[:waiting] = 0
end
stats.compact
rescue StandardError => e
handle_exception(e, level: :warn, handled: true, operation: :data_pool_stats, adapter: adapter)
{}
end
|
.read_server ⇒ Object
322
323
324
325
326
|
# File 'lib/legion/data/connection.rb', line 322
def read_server
return :default if @replica_servers.nil? || @replica_servers.empty?
:read_0
end
|
.reconnect_with_fresh_creds ⇒ Object
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
|
# File 'lib/legion/data/connection.rb', line 270
def reconnect_with_fresh_creds
return false unless @sequel
return false if adapter == :sqlite
fresh_creds = Legion::Settings[:data][:creds]
return false unless fresh_creds.is_a?(Hash)
new_user = fresh_creds[:user] || fresh_creds[:username]
new_pass = fresh_creds[:password]
unless new_user && new_pass
log.error('reconnect_with_fresh_creds: no user/password in Settings[:data][:creds]')
return false
end
old_user = @sequel.opts[:user]
@sequel.opts[:user] = new_user
@sequel.opts[:password] = new_pass
@sequel.disconnect
@sequel.test_connection
log.info("reconnect_with_fresh_creds: rotated credentials (#{old_user} → #{new_user})")
true
rescue StandardError => e
handle_exception(e, level: :error, handled: true, operation: :reconnect_with_fresh_creds,
old_user: old_user, new_user: new_user)
false
end
|
.replica_servers ⇒ Object
328
329
330
|
# File 'lib/legion/data/connection.rb', line 328
def replica_servers
@replica_servers || []
end
|
.setup ⇒ Object
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
|
# File 'lib/legion/data/connection.rb', line 163
def setup
@adapter = Legion::Settings[:data][:adapter]&.to_sym || :sqlite
opts = sequel_opts
log.info("Legion::Data::Connection setup adapter=#{adapter}")
@fallback_active = false
@sequel = if adapter == :sqlite
::Sequel.connect(opts.merge(adapter: :sqlite, database: sqlite_path))
else
attempted_adapter = adapter
begin
::Sequel.connect(connection_opts_for(adapter: attempted_adapter, opts: opts))
rescue StandardError => e
raise unless dev_fallback?
log.error("Legion::Data FALLING BACK TO SQLITE — #{attempted_adapter} network DB connection failed: #{e.message}")
log.error("Legion::Data WARNING: Data written to SQLite will NOT be visible when #{attempted_adapter} reconnects. " \
'Apollo knowledge, audit logs, and other DB-backed services will use a local-only store.')
handle_exception(e, level: :error, handled: true, operation: :shared_connect, fallback: :sqlite)
@adapter = :sqlite
@fallback_active = true
sqlite_opts = sequel_opts
::Sequel.connect(sqlite_opts.merge(adapter: :sqlite, database: sqlite_path))
end
end
Legion::Settings[:data][:connected] = true
log_connection_info
configure_extensions
connect_with_replicas
end
|
.shutdown ⇒ Object
261
262
263
264
265
266
267
268
|
# File 'lib/legion/data/connection.rb', line 261
def shutdown
@sequel&.disconnect
@query_file_logger&.close
@query_file_logger = nil
@fallback_active = false
Legion::Settings[:data][:connected] = false
log.info 'Legion::Data connection closed'
end
|
.stats ⇒ Object
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
|
# File 'lib/legion/data/connection.rb', line 212
def stats
return { connected: false } unless @sequel
data = Legion::Settings[:data]
{
connected: data[:connected],
adapter: adapter,
pool: pool_stats,
tuning: tuning_stats(data),
database: database_stats
}
rescue StandardError => e
handle_exception(e, level: :warn, handled: true, operation: :data_connection_stats, adapter: adapter)
{ connected: (data[:connected] if data.is_a?(Hash)), adapter: adapter, error: e.message }
end
|