Module: Lich::Gemstone::Infomon

Extended by:
Common::Watchable
Defined in:
documented/gemstone/infomon.rb,
documented/gemstone/infomon/cli.rb,
documented/gemstone/infomon/cache.rb,
documented/gemstone/infomon/parser.rb,
documented/gemstone/infomon/xmlparser.rb

Overview

Namespace for the Infomon module, which parses and tracks character, item, and combat state from the game server's XML stream.

Defined Under Namespace

Modules: Parser, XMLParser Classes: Cache

Constant Summary collapse

AllowedTypes =
[Integer, String, NilClass, FalseClass, TrueClass]

Class Method Summary collapse

Methods included from Common::Watchable

watch!

Class Method Details

._key(key) ⇒ String

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.

Normalizes a key to lowercase with underscores instead of spaces or hyphens.

Multiple consecutive underscores are collapsed to one.

Examples:

Infomon._key("Tactics Trained Ranks") #=> "tactics_trained_ranks"
Infomon._key("death-count") #=> "death_count"

Parameters:

  • key (String, Symbol) —

    the key to normalize

Returns:

  • (String) —

    the normalized key



230
231
232
# File 'documented/gemstone/infomon.rb', line 230

def self._key(key)
  key.to_s.downcase.tr(' -', '_').gsub(/_+/, '_')
end

._validate!(key, value) ⇒ Integer, ...

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.

Validates that the value is an allowed type and converts it.

Allowed types are Integer, String, nil, true, and false.

Parameters:

  • key (String) —

    the key being set (used only in error messages)

  • value (Integer, String, Boolean, nil) —

    the value to validate

Returns:

  • (Integer, String, Boolean, nil) —

    the converted value

Raises:

  • (RuntimeError) —

    if value is not an allowed type



259
260
261
262
# File 'documented/gemstone/infomon.rb', line 259

def self._validate!(key, value)
  return self._value(value) if AllowedTypes.include?(value.class)
  raise "infomon:insert(%s) was called with %s\nmust be %s\nvalue=%s" % [key, value.class, AllowedTypes.map(&:name).join("|"), value]
end

._value(val) ⇒ Boolean, ...

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.

Converts string boolean literals to their boolean type; passes through other values.

Examples:

Infomon._value("true") #=> true
Infomon._value("false") #=> false
Infomon._value(42) #=> 42

Parameters:

  • val (String, Integer, Boolean, nil) —

    the value to convert

Returns:

  • (Boolean, String, Integer, nil) —

    the converted value



243
244
245
246
247
# File 'documented/gemstone/infomon.rb', line 243

def self._value(val)
  return true if val.to_s == "true"
  return false if val.to_s == "false"
  return val
end

.cache ⇒ Infomon::Cache

Returns the in-memory cache of all persisted key-value pairs for the character.

Returns:



58
59
60
# File 'documented/gemstone/infomon.rb', line 58

def self.cache
  @cache
end

.cache_load ⇒ void

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.

This method returns an undefined value.

Populates the cache from the database, once per character session.

Sleeps briefly if the character name has not yet loaded. Sets @cache_loaded to true.



212
213
214
215
216
217
218
# File 'documented/gemstone/infomon.rb', line 212

def self.cache_load
  sleep(0.01) if XMLData.name.empty?
  dataset = Infomon.table
  h = dataset.map(:key).zip(dataset.map(:value)).to_h
  self.cache.merge!(h)
  @cache_loaded = true
end

.context! ⇒ void

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.

This method returns an undefined value.

Raises an error if the character name has not yet loaded from XMLData.

Raises:

  • (RuntimeError) —

    if XMLData.name is empty or nil



135
136
137
138
139
# File 'documented/gemstone/infomon.rb', line 135

def self.context!
  return unless XMLData.name.empty? or XMLData.name.nil?
  puts Exception.new.backtrace
  fail "cannot access Infomon before XMLData.name is loaded"
end

.current_timestamp ⇒ Float

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.

Returns the current UTC time as a float (seconds since epoch).

Returns:

  • (Float) —

    current time in UTC



126
127
128
# File 'documented/gemstone/infomon.rb', line 126

def self.current_timestamp
  Time.now.utc.to_f
end

.db ⇒ Sequel::Database

Returns the Sequel database connection.

Returns:

  • (Sequel::Database) —

    the SQLite database instance



72
73
74
# File 'documented/gemstone/infomon.rb', line 72

def self.db
  @db
end

.db_refresh_needed? ⇒ Boolean

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.

Checks if a refresh of the infomon database is needed.

This method determines if the database structure has changed or if the version of the infomon data is outdated.

Returns:

  • (Boolean) —

    true if a refresh is needed, false otherwise



98
99
100
101
102
103
104
105
# File 'documented/gemstone/infomon/cli.rb', line 98

def self.db_refresh_needed?
  # Change date below to the last date of infomon.db structure change to allow for a forced reset of data.
  # Change Lich version below to also force a refresh of DB as well due to new API/methods used by infomon (introduction of CHE and account subscription status for example).
  return true if Infomon.get("infomon.last_sync_date").nil?
  return true if Infomon.get("infomon.last_sync_date") < Time.new(2025, 6, 26, 20, 0, 0).to_i
  return true if Gem::Version.new("5.12.2") > Gem::Version.new(Infomon.get("infomon.last_sync_version"))
  return false
end

.delete!(key) ⇒ void

This method returns an undefined value.

Deletes a key from the cache and queues a database DELETE on the background thread.

Examples:

Infomon.delete!("old_config_key")

Parameters:

  • key (String, Symbol) —

    the key to delete



393
394
395
396
397
# File 'documented/gemstone/infomon.rb', line 393

def self.delete!(key)
  key = self._key(key)
  self.cache.delete(key)
  self.queue << ["DELETE FROM %s WHERE key = (%s);" % [self.db.literal(self.table_name), self.db.literal(key)], [key]]
end

.file ⇒ String

Returns the file path to the SQLite database.

Returns:

  • (String) —

    absolute path to infomon.db



65
66
67
# File 'documented/gemstone/infomon.rb', line 65

def self.file
  @file
end

.flush(timeout_seconds: 5) ⇒ Object

Flush all pending SQL operations and wait for completion. This is a barrier that ensures all queued writes have been executed. Returns true on success, false on timeout.



402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'documented/gemstone/infomon.rb', line 402

def self.flush(timeout_seconds: 5)
  return true if self.queue.empty?

  # Create a barrier token - a Queue that the worker will signal when reached
  barrier = ::Queue.new
  self.queue << barrier

  # Wait for the worker to signal completion (with timeout)
  begin
    ::Timeout.timeout(timeout_seconds) { barrier.pop }
    true
  rescue ::Timeout::Error
    Lich.log "warning: Infomon.flush timed out after #{timeout_seconds}s"
    false
  end
end

.get(key) ⇒ Integer, ...

Retrieves the value for a key, loading the cache if needed and flushing pending writes.

Returns nil if the key does not exist. The cache is consulted first; if the key is not cached, the database is queried after flushing the write queue. On database error, logs and responds to the game, then returns nil.

Examples:

Infomon.set("level", 85)
Infomon.get("level") #=> 85

Parameters:

  • key (String, Symbol) —

    the key to retrieve

Returns:

  • (Integer, String, Boolean, nil) —

    the stored value, or nil if not found



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'documented/gemstone/infomon.rb', line 275

def self.get(key)
  self.cache_load if !@cache_loaded
  key = self._key(key)
  val = self.cache.get(key) {
    # Flush queue before reading from DB to ensure we see latest writes
    self.flush
    begin
      self.mutex.synchronize do
        begin
          db_result = self.table[key: key]
          if db_result
            db_result[:value]
          else
            nil
          end
        rescue => exception
          pp(exception)
          nil
        end
      end
    rescue StandardError
      respond "--- Lich: error: Infomon.get(#{key}): #{$!}"
      Lich.log "error: Infomon.get(#{key}): #{$!}\n\t#{$!.backtrace.join("\n\t")}"
    end
  }
  return self._value(val)
end

.get_bool(key) ⇒ Boolean

Retrieves the value for a key and coerces it to a boolean.

True and false values are returned as-is. Integer 1 is treated as true; all other values (including 0) are treated as false. Nil is treated as false.

Examples:

Infomon.set("in_combat", true)
Infomon.get_bool("in_combat") #=> true

Parameters:

  • key (String, Symbol) —

    the key to retrieve

Returns:

  • (Boolean) —

    true or false



313
314
315
316
317
318
319
320
321
322
# File 'documented/gemstone/infomon.rb', line 313

def self.get_bool(key)
  value = Infomon.get(key)
  if value.is_a?(TrueClass) || value.is_a?(FalseClass)
    return value
  elsif value == 1
    return true
  else
    return false
  end
end

.get_updated_at(key) ⇒ Float?

Retrieves the timestamp (in seconds since epoch) when the key was last written.

Returns nil if the key does not exist or on database error. On error, logs and responds to the game.

Examples:

Infomon.get_updated_at("level") #=> 1704067200.5

Parameters:

  • key (String, Symbol) —

    the key to check

Returns:

  • (Float, nil) —

    the last update time in UTC seconds, or nil if not found



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'documented/gemstone/infomon.rb', line 333

def self.get_updated_at(key)
  key = self._key(key)
  begin
    self.mutex.synchronize do
      db_result = self.table[key: key]
      if db_result
        db_result[:updated_at]
      else
        nil
      end
    end
  rescue StandardError
    respond "--- Lich: error: Infomon.get_updated_at(#{key}): #{$!}"
    Lich.log "error: Infomon.get_updated_at(#{key}): #{$!}\n\t#{$!.backtrace.join("\n\t")}"
    nil
  end
end

.mutex ⇒ Mutex

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.

Returns the mutex guarding all database and cache operations.

Returns:

  • (Mutex) —

    the synchronization lock



80
81
82
# File 'documented/gemstone/infomon.rb', line 80

def self.mutex
  @sql_mutex
end

.mutex_lock ⇒ void

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.

This method returns an undefined value.

Acquires the database mutex if not already held by this thread.

On error, logs and responds to the game.



90
91
92
93
94
95
96
97
# File 'documented/gemstone/infomon.rb', line 90

def self.mutex_lock
  begin
    self.mutex.lock unless self.mutex.owned?
  rescue StandardError
    respond "--- Lich: error: Infomon.mutex_lock: #{$!}"
    Lich.log "error: Infomon.mutex_lock: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  end
end

.mutex_unlock ⇒ void

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.

This method returns an undefined value.

Releases the database mutex if held by this thread.

On error, logs and responds to the game.



105
106
107
108
109
110
111
112
# File 'documented/gemstone/infomon.rb', line 105

def self.mutex_unlock
  begin
    self.mutex.unlock if self.mutex.owned?
  rescue StandardError
    respond "--- Lich: error: Infomon.mutex_unlock: #{$!}"
    Lich.log "error: Infomon.mutex_unlock: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  end
end

.queue ⇒ Queue

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.

Returns the thread-safe queue of pending SQL write operations.

Returns:

  • (Queue) —

    the work queue



118
119
120
# File 'documented/gemstone/infomon.rb', line 118

def self.queue
  @sql_queue
end

.redo! ⇒ void

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.

This method returns an undefined value.

Resets the infomon data and repopulates it.

This method deletes the character table, recreates it, and then syncs the data.



57
58
59
60
61
62
63
# File 'documented/gemstone/infomon/cli.rb', line 57

def self.redo!
  # Destructive - deletes char table, recreates it, then repopulates it
  respond 'Infomon complete reset reqeusted.'
  Infomon.reset!
  Infomon.sync
  respond 'Infomon reset is now complete.'
end

.reset! ⇒ void

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.

This method returns an undefined value.

Drops the character's database table, clears the cache, and re-initializes.

All persisted data for this character is lost. The table is recreated on next access.



157
158
159
160
161
162
163
164
165
# File 'documented/gemstone/infomon.rb', line 157

def self.reset!
  self.mutex_lock
  Infomon.db.drop_table?(self.table_name)
  self.cache.clear
  @unpersisted.clear
  @failure_reported = false
  @cache_loaded = false
  Infomon.setup!
end

.set(key, value) ⇒ void, Symbol

Sets a key-value pair, queueing the write to the database asynchronously.

The value is cached immediately; the write is performed on a background thread. If the key already exists in the cache with the same value and has no pending failed write, returns :noop (no operation queued). Allowed value types are Integer, String, nil, true, and false.

Examples:

Infomon.set("level", 85)
Infomon.set("status", "hunting")
Infomon.set("resting", true)

Parameters:

  • key (String, Symbol) —

    the key to set

  • value (Integer, String, Boolean, nil) —

    the value to store

Returns:

  • (void, Symbol) —

    void if queued, or :noop if no change needed

Raises:

  • (RuntimeError) —

    if value is not an allowed type



377
378
379
380
381
382
383
384
385
# File 'documented/gemstone/infomon.rb', line 377

def self.set(key, value)
  key = self._key(key)
  value = self._validate!(key, value)
  return :noop if !@unpersisted.key?(key) && self.cache.include?(key) && self.cache.get(key) == value
  self.cache.put(key, value)
  # queue items are [sql, keys] so a failed write can mark its keys unpersisted
  self.queue << ["INSERT OR REPLACE INTO %s (`key`, `value`, `updated_at`) VALUES (%s, %s, %s)
on conflict(`key`) do update set value = excluded.value, updated_at = excluded.updated_at;" % [self.db.literal(self.table_name), self.db.literal(key), self.db.literal(value), current_timestamp], [key]]
end

.setup! ⇒ Sequel::Dataset

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 or validates the character's database table, checking for schema compatibility.

If the table exists but lacks the updated_at column (old schema), drops and recreates it. Acquires and releases the database mutex during operation.

Returns:

  • (Sequel::Dataset) —

    the dataset for the table



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'documented/gemstone/infomon.rb', line 184

def self.setup!
  self.mutex_lock

  # Check if table exists but missing updated_at column
  if @db.table_exists?(self.table_name)
    columns = @db.schema(self.table_name).map { |col| col[0] }
    unless columns.include?(:updated_at)
      self.mutex_unlock
      self.reset!
      return
    end
  end

  @db.create_table?(self.table_name) do
    text :key, primary_key: true
    any :value
    float :updated_at
  end
  self.mutex_unlock
  @_table = @db[self.table_name]
end

.show(full = false) ⇒ void

This method returns an undefined value.

Displays stored information for the character.

If the full parameter is set to true, all stored values are displayed. Otherwise, only non-zero values are shown.

Parameters:

  • full (Boolean) (defaults to: false) —

    whether to display all values or only non-zero ones



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'documented/gemstone/infomon/cli.rb', line 72

def self.show(full = false)
  response = []
  # display all stored db values
  respond "Displaying stored information for #{XMLData.name}"
  # Flush async SQL queue before reading from DB to ensure consistency
  Infomon.flush
  Infomon.table.map([:key, :value]).each { |k, v|
    response << "#{k} : #{v.inspect}\n"
  }
  unless full
    response.each { |_line|
      response.reject! do |line|
        line.match?(/\s:\s0$/)
      end
    }
  end
  respond response
end

.sync ⇒ void

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.

This method returns an undefined value.

Synchronizes the character's infomon settings with the server.

This method checks for active spells that may interfere with the sync process, such as the Shroud of Deception, and handles them accordingly.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'documented/gemstone/infomon/cli.rb', line 12

def self.sync
  # since none of this information is 3rd party displayed, silence is golden.
  shroud_detected = false
  respond 'Infomon sync requested.'
  if Effects::Spells.active?(1212)
    respond 'ATTENTION:  SHROUD DETECTED - disabling Shroud of Deception to sync character\'s infomon setting'
    while Effects::Spells.active?(1212)
      dothistimeout('STOP 1212', 3, /^With a moment's concentration, you terminate the Shroud of Deception spell\.$|^Stop what\?$/)
      sleep(0.5)
    end
    shroud_detected = true
  end
  request = { 'info full'          => /<a exist=.+#{XMLData.name}/,
              'skill'              => /<a exist=.+#{XMLData.name}/,
              'spell'              => %r{<output class="mono"/>},
              'experience'         => %r{<output class="mono"/>},
              'society'            => %r{<pushBold/>},
              'citizenship'        => /^You don't seem|^You currently have .+ in/,
              'armor list all'     => /<a exist=.+#{XMLData.name}/,
              'cman list all'      => /<a exist=.+#{XMLData.name}/,
              'feat list all'      => /<a exist=.+#{XMLData.name}/,
              'shield list all'    => /<a exist=.+#{XMLData.name}/,
              'weapon list all'    => /<a exist=.+#{XMLData.name}/,
              'ascension list all' => /<a exist=.+#{XMLData.name}/,
              'resource'           => /^Health: \d+\/(?:<pushBold\/>)?\d+(?:<popBold\/>)?\s+Mana: \d+\/(?:<pushBold\/>)?\d+(?:<popBold\/>)?\s+Stamina: \d+\/(?:<pushBold\/>)?\d+(?:<popBold\/>)?\s+Spirit: \d+\/(?:<pushBold\/>)?\d+/,
              'warcry'             => /^You have learned the following War Cries:|^You must be an active member of the Warrior Guild to use this skill/,
              'profile full'       => %r{<output class="mono"/>} }

  request.each do |command, start_capture|
    respond "Retrieving character #{command}." if $infomon_debug
    Lich::Util.issue_command(command.to_s, start_capture, /<prompt/, include_end: true, timeout: 5, silent: false, usexml: true, quiet: true)
    respond "Did #{command}." if $infomon_debug
  end
  respond 'Requested Infomon sync complete.'
  respond 'ATTENTION:  TEND TO YOUR SHROUD!' if shroud_detected
  Infomon.set('infomon.last_sync_date', Time.now.to_i)
  Infomon.set('infomon.last_sync_version', LICH_VERSION)
end

.table ⇒ Sequel::Dataset

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.

Returns the Sequel dataset for the character's key-value table.

Calls .setup! on first access to initialize the table schema.

Returns:

  • (Sequel::Dataset) —

    the dataset for INSERT, SELECT, and DELETE operations



173
174
175
# File 'documented/gemstone/infomon.rb', line 173

def self.table
  @_table ||= self.setup!
end

.table_name ⇒ Symbol

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.

Returns the database table name for the current character, derived from game and name.

Returns:

  • (Symbol) —

    table name in the form :gamecode_charactername

Raises:

  • (RuntimeError) —

    if character name is not yet loaded



146
147
148
149
# File 'documented/gemstone/infomon.rb', line 146

def self.table_name
  self.context!
  ("%s_%s" % [XMLData.game, XMLData.name]).to_sym
end

.upsert(*args) ⇒ Integer

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.

Inserts or updates rows in the table using Sequel's INSERT OR REPLACE conflict handling.

Parameters:

  • args (Array) —

    arguments passed to Sequel's insert method

Returns:

  • (Integer) —

    the number of rows affected



356
357
358
359
360
# File 'documented/gemstone/infomon.rb', line 356

def self.upsert(*args)
  self.table
      .insert_conflict(:replace)
      .insert(*args)
end

.upsert_batch(*blob) ⇒ void, Symbol

Batch inserts or updates multiple key-value pairs in a single SQL statement.

Accepts a hash (or multiple hashes) where only keys not already in the cache (or with pending failed writes) are inserted. Values are cached immediately; the write is queued asynchronously. Returns :noop if no new keys are found. Only Integer and String values are supported in batch mode.

Examples:

Infomon.upsert_batch({"exp_pool" => 500, "death_count" => 2})

Parameters:

  • blob (Hash) —

    one or more hashes of key => value pairs

Returns:

  • (void, Symbol) —

    void if queued, or :noop if all keys are cached

Raises:

  • (RuntimeError) —

    if any value is not Integer or String



431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'documented/gemstone/infomon.rb', line 431

def self.upsert_batch(*blob)
  updated = (blob.first.map { |k, v| [self._key(k), self._validate!(k, v)] } - self.cache.to_a.reject { |k, _| @unpersisted.key?(k) })
  return :noop if updated.empty?
  now = current_timestamp
  pairs = updated.map { |key, value|
    (value.is_a?(Integer) or value.is_a?(String)) or fail "upsert_batch only works with Integer or String types"
    # add the value to the cache
    self.cache.put(key, value)
    %[(%s, %s, %s)] % [self.db.literal(key), self.db.literal(value), now]
  }.join(", ")
  # queue sql statement to run async
  self.queue << ["INSERT OR REPLACE INTO %s (`key`, `value`, `updated_at`) VALUES %s
on conflict(`key`) do update set value = excluded.value, updated_at = excluded.updated_at;" % [self.db.literal(self.table_name), pairs], updated.map(&:first)]
end

.watch! ⇒ Object

Self-watching thread that triggers initialization when ready Follows the ActiveSpell.watch! pattern for lifecycle management



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'documented/gemstone/infomon.rb', line 496

def self.watch!
  @init_thread ||= Thread.new do
    begin
      # Wait for character to be ready and dialogs to load
      sleep 0.1 until GameBase::Game.autostarted? && XMLData.name && !XMLData.name.empty? &&
                      !XMLData.dialogs.empty?

      # Run initial setup if needed (GS-specific only, skip for DR)
      if XMLData.game !~ /^DR/ && db_refresh_needed?
        ExecScript.start("Infomon.redo!", { quiet: true, name: "infomon_reset" })
      end

      PostLoad.game_loaded! if defined?(PostLoad)
    rescue StandardError => e
      respond 'Error in Infomon initialization thread'
      respond e.inspect
    end
  end
end