Class: Lich::Common::DatabaseAdapter

Inherits:
Object
  • Object
show all
Defined in:
documented/common/settings/database_adapter.rb

Overview

Database adapter to separate database concerns

Constant Summary collapse

MIN_UPDATE_ATTEMPTS =

update_settings keeps reading a row and trying to store it, while other writers keep changing it in between, for as long as a write would wait for SQLite's lock (Lich.sqlite_busy_timeout_ms), and at least this many times. A writer whose row takes longer to rebuild than its rivals' does loses more often, so a fixed count would give up on it first.

3
MAX_RETRY_PAUSE =

Longest pause, in seconds, before trying again. Each pause is random, up to 4 ms before the second attempt and doubling from there, so that competing writers drift apart.

0.05

Instance Method Summary collapse

Constructor Details

#initialize(data_dir, table_name) ⇒ DatabaseAdapter

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Sets up a database adapter for persistent settings storage.

Creates or opens a SQLite database at data_dir/lich.db3 and initializes a table for the given script. Also opens a separate read-only connection for tracking database changes via PRAGMA data_version, avoiding GVL stalls when checking if other processes modified settings.

Parameters:

  • data_dir (String) —

    directory where lich.db3 is stored

  • table_name (String) —

    the name of the settings table to use or create



17
18
19
20
21
22
23
24
25
26
27
# File 'documented/common/settings/database_adapter.rb', line 17

def initialize(data_dir, table_name)
  @file = File.join(data_dir, "lich.db3")
  @db = Lich.open_sequel_sqlite(@file)
  @table_name = table_name
  @version_mutex = Mutex.new
  @version_db = nil
  @version_base = 0
  @version_epoch = -1
  @version_error_reported = false
  setup!
end

Instance Method Details

#data_version ⇒ Integer?

A number that changes whenever lich.db3 has had a commit since it was last read, or nil when that can't be told right now.

Every Lich session is a separate process, and Settings caches rows per process. SQLite's PRAGMA data_version changes when another connection commits, so a cache can compare it with the value seen when a row was read and re-read the row only when it may have changed. The pragma reports changes by other connections only, and Sequel may hand each thread a different connection, so it is read on a connection of its own that never writes: every commit, from another process or from this one, changes it.

The connection has no busy timeout. While another process holds the database's exclusive lock (a commit in progress, or a script holding it), the read fails at once and this returns nil, rather than waiting inside SQLite, which keeps the GVL and would stall every thread of this process. Callers then keep what they have; a read that overlaps a commit may see the database as it was before it. The read runs in one C call (sqlite3_exec), so no lock is held while Ruby code runs.

The pragma counts per connection, starting again from 1 on a new one, so after an error has closed the connection the reopened one could repeat a value already handed out while the database has since changed. Each connection therefore gets a range of its own: its values are offset by 240 times the number of connections opened before it. No value is handed out twice for different states of the database, and every value from a reopened connection is greater than every earlier one (a connection would need 240 commits to reach the next range).

No Ruby lock is held on the way, so a cache hit never waits for one. Ruby's Mutex is not fair: a thread calling this in a tight loop would take the lock back before a waiting thread got to run, and stall other threads' Settings reads (measured: up to seconds with the lock held around the pragma, about 100 ms now and then with it held only to record the value). The GVL already keeps two threads out of the C call at once. @version_mutex guards only opening and closing the connection; a value read on a connection that another thread has closed or replaced meanwhile is discarded (nil).

Returns:

  • (Integer, nil)


104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'documented/common/settings/database_adapter.rb', line 104

def data_version
  db = @version_db || open_version_connection
  # Read after db: a connection is published only after its offset is
  # set, and a connection replaced after this point fails the identity
  # check below.
  base = @version_base
  raw = Integer(db.execute_batch2('PRAGMA data_version').dig(0, 0))
  return nil unless @version_db.equal?(db)

  base + raw
rescue SQLite3::BusyException
  nil
rescue SQLite3::Exception, ArgumentError, TypeError => e
  if close_version_connection(db) && !@version_error_reported
    @version_error_reported = true
    Lich.log("--- Error: cannot tell whether settings changed in lich.db3 (#{e.class}: #{e.message}); settings may not show other sessions' changes ---")
  end
  nil
end

#get_settings(script_name, scope = ":") ⇒ Hash

Reads the stored settings for a script and scope, unmarshalling them from the database.

Examples:

settings = adapter.get_settings("my_script") #=> {"key" => "value"}

Parameters:

  • script_name (String) —

    the script namespace

  • scope (String) (defaults to: ":") —

    the settings scope (default: ":")

Returns:

  • (Hash) —

    the settings hash, or {} if no row exists for this script and scope

Raises:

  • (TypeError) —

    if the stored blob cannot be unmarshalled (corrupted or class mismatch)



58
59
60
61
# File 'documented/common/settings/database_adapter.rb', line 58

def get_settings(script_name, scope = ":")
  entry = @table.first(script: script_name, scope: scope)
  entry.nil? ? {} : Marshal.load(entry[:hash])
end

#get_settings_by_scope_prefix(script_name, scope_prefix) ⇒ Hash{String => Object}

Reads every row for script_name whose scope starts with scope_prefix, straight from the database (no cache).

A row whose stored value can't be loaded is skipped and logged, so one bad row doesn't hide the others.

Parameters:

  • script_name (String)
  • scope_prefix (String) —

    matched literally (not as a LIKE pattern)

Returns:

  • (Hash{String => Object}) —

    scope => stored settings



284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'documented/common/settings/database_adapter.rb', line 284

def get_settings_by_scope_prefix(script_name, scope_prefix)
  prefix = scope_prefix.to_s
  @table.where(script: script_name).select(:scope, :hash).each_with_object({}) do |row, result|
    scope = row[:scope].to_s
    next unless scope.start_with?(prefix)

    begin
      result[scope] = Marshal.load(row[:hash])
    rescue StandardError => e
      Lich.log("--- Error: skipping unreadable settings row script=#{script_name} scope=#{scope}: #{e.class}: #{e.message} ---")
    end
  end
end

#save_settings(script_name, settings, scope = ":") ⇒ Boolean

Writes settings to the database, creating or replacing the row for this script and scope.

Serializes the hash to binary and stores it in one write transaction. If serialization fails or the database is locked, logs the error and returns false without writing.

Examples:

adapter.save_settings("my_script", {"key" => "value"}) #=> true

Parameters:

  • script_name (String) —

    the script namespace

  • settings (Hash) —

    the settings to store

  • scope (String) (defaults to: ":") —

    the settings scope (default: ":")

Returns:

  • (Boolean) —

    true if saved successfully, false if serialization or the write failed



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'documented/common/settings/database_adapter.rb', line 135

def save_settings(script_name, settings, scope = ":")
  blob = serialize_settings(script_name, settings)
  return false unless blob

  begin
    statement { upsert_settings(script_name, scope, blob) }
    return true
  rescue StatementFailed => e
    report_database_error(e.cause)
  rescue => e
    Lich::Messaging.msg("error", "--- Unexpected error while saving settings ---")
    Lich.log("--- Unexpected error while saving settings ---")
    Lich.log("#{e.message}\n#{e.backtrace.join("\n")}")
  end

  false
end

#save_settings!(script_name, settings, scope) ⇒ Hash

Writes one settings row without reading it first.

Unlike #save_settings, which reports errors and returns false, this raises, so a caller inside #transaction gets the whole transaction rolled back and can tell that nothing was written.

Parameters:

Returns:

  • (Hash) —

    settings

Raises:

  • (TypeError) —

    if settings is not a Hash or can't be serialized

  • (Sequel::DatabaseError) —

    if the database is locked or the write fails



310
311
312
313
314
315
# File 'documented/common/settings/database_adapter.rb', line 310

def save_settings!(script_name, settings, scope)
  raise TypeError, "settings must be a Hash, got #{settings.class}" unless settings.is_a?(Hash)

  upsert_settings(script_name, scope, Sequel::SQL::Blob.new(Marshal.dump(settings)))
  settings
end

#scopes_by_prefix(script_name, scope_prefix) ⇒ Array<String>

Lists the scopes of every row for script_name whose scope starts with scope_prefix, without loading the stored values (so a row that can't be loaded is still listed).

Parameters:

  • script_name (String)
  • scope_prefix (String) —

    matched literally (not as a LIKE pattern)

Returns:



270
271
272
273
# File 'documented/common/settings/database_adapter.rb', line 270

def scopes_by_prefix(script_name, scope_prefix)
  prefix = scope_prefix.to_s
  @table.where(script: script_name).select_map(:scope).map(&:to_s).select { |scope| scope.start_with?(prefix) }
end

#setup! ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates the settings table if it does not exist and caches the table reference.

The table has three columns: script (text), scope (text), and hash (blob).



34
35
36
37
38
39
40
41
# File 'documented/common/settings/database_adapter.rb', line 34

def setup!
  @db.create_table?(@table_name) do
    text :script
    text :scope
    blob :hash
  end
  @table = @db[@table_name]
end

#table ⇒ Sequel::Dataset

Returns the Sequel dataset for the settings table.

Returns:

  • (Sequel::Dataset) —

    the settings table



46
47
48
# File 'documented/common/settings/database_adapter.rb', line 46

def table
  @table
end

#transaction(&block) ⇒ Object

Runs the block inside one SQLite write transaction (BEGIN IMMEDIATE). The write lock is taken before the first read, so a read-modify-write inside the block cannot interleave with another process's write. A nested call joins the outer transaction. If the block raises, nothing it wrote is kept. (Sequel's SQLite adapter re-raises an ArgumentError from the block as Sequel::DatabaseError.)

Raises:

  • (Sequel::DatabaseError) —

    if the database stays locked past the busy timeout.



259
260
261
# File 'documented/common/settings/database_adapter.rb', line 259

def transaction(&block)
  @db.transaction(mode: :immediate, &block)
end

#update_settings(script_name, scope = ":", on_stored: nil) {|fresh| ... } ⇒ Hash?

Changes one row without losing what other writers saved in the meantime.

Every Lich session is a separate process with its own settings cache, and all of them share lich.db3. Writing a cached copy of the row back erases whatever other sessions saved in between. This method reads the row as it is now, lets the block change it, and stores the result only if the row still holds exactly the bytes it read: one conditional UPDATE (or, for a new row, an INSERT that does nothing on conflict). If another writer got in first, it pauses briefly, reads the row again and calls the block again, until the busy timeout has passed (see MIN_UPDATE_ATTEMPTS).

Each statement takes and releases SQLite's write lock by itself, so the lock is never held while Ruby code (the block, Marshal) runs. Holding it there would make every other writer in this process wait out its busy timeout inside SQLite, which keeps the GVL and stalls every thread.

on_stored, when given, is called with the stored row right after the store succeeds, with Thread#kill and Thread#raise held back from the store until on_stored returns. A caller that caches the row passes its cache update here: a script killed (Script#kill) just after the row was committed still leaves its cache holding what the database holds. Only the store is covered, not the block or the pauses between attempts, so a kill waits at most for that one statement (which SQLite already runs without letting other Ruby code in).

A stored row that cannot be read (NULL, truncated, or holding a class this process does not have) is never overwritten: another session may still be able to read it. The error is reported and raised, as a read of that row (get_settings) raises it.

Parameters:

  • script_name (String) —

    the script namespace

  • scope (String) (defaults to: ":") —

    the settings scope

  • on_stored (#call, nil) (defaults to: nil) —

    called with the stored row (see above)

Yield Parameters:

  • fresh (Object) —

    the stored row ({} when there is none). The block may be called more than once and must only build the new row.

Yield Returns:

  • (Hash, nil) —

    the row to store, or nil to store nothing

Returns:

  • (Hash, nil) —

    the block's row as stored, or nil when the block returned nil or nothing could be stored (reported, nothing written)

Raises:

  • whatever the block raises, and what get_settings raises for a stored row it cannot read (such as TypeError or ArgumentError)



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'documented/common/settings/database_adapter.rb', line 214

def update_settings(script_name, scope = ":", on_stored: nil)
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  budget = Lich.sqlite_busy_timeout_ms.to_f / 1000
  attempts = 0
  loop do
    sleep(rand * [0.002 * (2**[attempts, 5].min), MAX_RETRY_PAUSE].min) if attempts.positive?
    attempts += 1
    row = statement { read_row_in_one_call(script_name, scope) }
    old_blob = row && row[:hash]
    updated = yield(row.nil? ? {} : load_stored_row(script_name, scope, old_blob))
    return nil if updated.nil?

    new_blob = serialize_settings(script_name, updated)
    return nil unless new_blob

    stored = Thread.handle_interrupt(Object => :never) do
      next false unless statement { store_if_unchanged(script_name, scope, old_blob, row.nil?, new_blob) }

      on_stored&.call(updated)
      true
    end
    return updated if stored

    elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
    break if attempts >= MIN_UPDATE_ATTEMPTS && elapsed >= budget
  end

  message = "--- Error while saving settings: #{script_name} (#{scope}) kept changing, gave up after #{attempts} attempts ---"
  Lich::Messaging.msg("error", message)
  Lich.log(message)
  nil
rescue StatementFailed => e
  report_database_error(e.cause)
  nil
end

#update_settings!(script_name, scope) ⇒ Hash?

Atomically reads, changes and writes one settings row.

Yields a fresh copy of the stored hash ({} when there is no row) inside #transaction. If the block returns a Hash, that Hash is written to the row; if it returns nil, the row is left as it was.

Raises on every failure, like #save_settings!, so the caller can tell that nothing was written.

Returns:

  • (Hash, nil) —

    what the block returned

Raises:

  • (Sequel::DatabaseError) —

    if the database is locked or the write fails, or if loading the stored row raises ArgumentError (truncated Marshal data, for example; Sequel re-raises an ArgumentError from the block as Sequel::DatabaseError, with the ArgumentError as cause)

  • (StandardError) —

    whatever else Marshal.load raises on a stored row that can't be loaded (usually TypeError), without yielding

  • (TypeError) —

    if the block returns something other than a Hash or nil



334
335
336
337
338
339
340
341
342
343
344
# File 'documented/common/settings/database_adapter.rb', line 334

def update_settings!(script_name, scope)
  transaction do
    updated = yield(get_settings(script_name, scope))
    unless updated.nil? || updated.is_a?(Hash)
      raise TypeError, "update_settings! block must return a Hash or nil, got #{updated.class}"
    end

    save_settings!(script_name, updated, scope) if updated
    updated
  end
end