Class: Legion::Settings::Loader

Inherits:
Object
  • Object
show all
Includes:
Logging::Helper, OS
Defined in:
lib/legion/settings/loader.rb

Defined Under Namespace

Classes: Error

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from OS

linux?, mac?, #os, unix?, windows?

Constructor Details

#initializeLoader

Returns a new instance of Loader.



37
38
39
40
41
42
43
44
45
# File 'lib/legion/settings/loader.rb', line 37

def initialize
  @warnings = []
  @errors = []
  @settings = default_settings
  @indifferent_access = false
  @loaded_files = []
  @merged_modules = {}
  log.debug('Initialized Legion::Settings::Loader with default settings')
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



18
19
20
# File 'lib/legion/settings/loader.rb', line 18

def errors
  @errors
end

#loaded_filesObject (readonly)

Returns the value of attribute loaded_files.



18
19
20
# File 'lib/legion/settings/loader.rb', line 18

def loaded_files
  @loaded_files
end

#merged_modulesObject (readonly)

Returns the value of attribute merged_modules.



18
19
20
# File 'lib/legion/settings/loader.rb', line 18

def merged_modules
  @merged_modules
end

#settingsObject (readonly)

Returns the value of attribute settings.



18
19
20
# File 'lib/legion/settings/loader.rb', line 18

def settings
  @settings
end

#warningsObject (readonly)

Returns the value of attribute warnings.



18
19
20
# File 'lib/legion/settings/loader.rb', line 18

def warnings
  @warnings
end

Class Method Details

.default_directoriesObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/legion/settings/loader.rb', line 20

def self.default_directories
  env_dirs = ENV.fetch('LEGION_SETTINGS_DIRS', nil)
  if env_dirs && !env_dirs.strip.empty?
    env_dirs_list = env_dirs.split(File::PATH_SEPARATOR).map(&:strip).reject(&:empty?).map { |p| File.expand_path(p) }
    return env_dirs_list unless env_dirs_list.empty?
  end

  dirs = [File.expand_path('~/.legionio/settings')]
  if OS.windows?
    appdata = ENV.fetch('APPDATA', nil)
    dirs << File.join(appdata, 'legionio', 'settings') if appdata && !appdata.strip.empty?
  else
    dirs << '/etc/legionio/settings'
  end
  dirs
end

Instance Method Details

#[](key) ⇒ Object



168
169
170
# File 'lib/legion/settings/loader.rb', line 168

def [](key)
  to_hash[key]
end

#[]=(key, value) ⇒ Object



176
177
178
179
# File 'lib/legion/settings/loader.rb', line 176

def []=(key, value)
  @settings[key] = value
  mark_dirty!
end

#absorbers_defaultsObject



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/legion/settings/loader.rb', line 84

def absorbers_defaults
  {
    enabled:   true,
    max_depth: 5,
    sources:   {
      meetings:    {
        enabled:          true,
        include_chat:     true,
        include_files:    true,
        retention_days:   90,
        min_duration_min: 5
      },
      email_inbox: {
        enabled:      false,
        folder:       'inbox',
        max_age_days: 30
      },
      github:      {
        enabled: true,
        events:  %w[pull_request issues]
      },
      files:       {
        enabled:    true,
        watch_dirs: [],
        extensions: %w[pdf docx txt md pptx rtf]
      }
    }
  }
end

#client_defaultsObject



58
59
60
61
62
63
64
65
# File 'lib/legion/settings/loader.rb', line 58

def client_defaults
  {
    hostname: system_hostname,
    address:  system_address,
    name:     "#{::Socket.gethostname.tr('.', '_')}.#{::Process.pid}",
    ready:    false
  }
end

#default_settingsObject



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/legion/settings/loader.rb', line 114

def default_settings
  {
    client:                     client_defaults,
    cluster:                    { public_keys: {} },
    crypt:                      {
      cluster_secret:         nil,
      cluster_secret_timeout: 5,
      vault:                  { connected: false }
    },
    cache:                      { enabled: true, connected: false, driver: 'dalli' },
    extensions:                 {
      core:               %w[
        lex-node lex-tasker lex-scheduler lex-health lex-ping
        lex-telemetry lex-metering lex-log lex-audit
        lex-conditioner lex-transformer lex-exec lex-lex lex-codegen
      ],
      ai:                 %w[lex-claude lex-openai lex-gemini],
      gaia:               %w[lex-tick lex-mesh lex-apollo],
      categories:         {
        core:    { type: :list, tier: 1 },
        ai:      { type: :list, tier: 2 },
        gaia:    { type: :list, tier: 3 },
        agentic: { type: :prefix, tier: 4 }
      },
      blocked:            [],
      reserved_prefixes:  %w[core ai agentic gaia],
      reserved_words:     %w[transport cache crypt data settings json logging llm rbac legion],
      agentic:            { allowed: nil, blocked: [] },
      parallel_pool_size: 24
    },
    reload:                     false,
    reloading:                  false,
    auto_install_missing_lex:   true,
    default_extension_settings: {},
    logging:                    logging_defaults,
    absorbers:                  absorbers_defaults,
    transport:                  { connected: false },
    data:                       { connected: false },
    role:                       { profile: nil, extensions: [] },
    region:                     { current: nil, primary: nil, failover: nil, peers: [],
                                  default_affinity: 'any', data_residency: {} },
    process:                    { role: 'full' },
    dns:                        dns_defaults
  }
end

#dig(*keys) ⇒ Object



172
173
174
# File 'lib/legion/settings/loader.rb', line 172

def dig(*keys)
  to_hash.dig(*keys)
end

#dns_defaultsObject



47
48
49
50
51
52
53
54
55
56
# File 'lib/legion/settings/loader.rb', line 47

def dns_defaults
  resolv_config = read_resolv_config
  {
    fqdn:           detect_fqdn,
    default_domain: resolv_config[:search_domains]&.first,
    search_domains: resolv_config[:search_domains] || [],
    nameservers:    resolv_config[:nameservers] || [],
    bootstrap:      { enabled: true }
  }
end

#hexdigestObject



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/legion/settings/loader.rb', line 181

def hexdigest
  if @hexdigest && @indifferent_access
    @hexdigest
  else
    hash = case legion_service_name
           when 'client', 'rspec'
             to_hash
           else
             to_hash.reject do |key, _value|
               key.to_s == 'client'
             end
           end
    @hexdigest = Digest::SHA256.hexdigest(hash.to_s)
  end
end

#load_client_overridesObject



268
269
270
271
272
273
274
275
276
277
# File 'lib/legion/settings/loader.rb', line 268

def load_client_overrides
  @settings[:client][:subscriptions] ||= []
  if @settings[:client][:subscriptions].is_a?(Array)
    @settings[:client][:subscriptions] << "client:#{@settings[:client][:name]}"
    @settings[:client][:subscriptions].uniq!
    mark_dirty!
  else
    log.warn('unable to apply legion client overrides, reason: client subscriptions is not an array')
  end
end

#load_directory(directory) ⇒ Object



257
258
259
260
261
262
263
264
265
266
# File 'lib/legion/settings/loader.rb', line 257

def load_directory(directory)
  path = directory.gsub(/\\(?=\S)/, '/')
  if File.readable?(path) && File.executable?(path)
    files = Dir.glob(File.join(path, '**', '*.json'))
    files.each { |file| load_file(file) }
    log.info("Settings: loaded directory #{path} (#{files.size} files)")
  else
    load_error('insufficient permissions for loading', directory: directory)
  end
end

#load_dns_bootstrap(cache_dir: nil) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/legion/settings/loader.rb', line 202

def load_dns_bootstrap(cache_dir: nil)
  return if ENV['LEGION_DNS_BOOTSTRAP'] == 'false'

  domain = @settings.dig(:dns, :default_domain)
  return unless domain
  return unless @settings.dig(:dns, :bootstrap, :enabled)

  dir = cache_dir || File.expand_path('~/.legionio/settings')
  bootstrap = DnsBootstrap.new(default_domain: domain, cache_dir: dir)

  config = if bootstrap.cache_exists?
             load_dns_from_cache(bootstrap)
           else
             load_dns_first_boot(bootstrap)
           end

  return unless config

  merge_dns_config(config, bootstrap)
end

#load_envObject



197
198
199
200
# File 'lib/legion/settings/loader.rb', line 197

def load_env
  load_api_env
  load_privacy_env
end

#load_file(file) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/legion/settings/loader.rb', line 238

def load_file(file)
  log.debug("Trying to load file #{file}")
  if File.file?(file) && File.readable?(file)
    begin
      contents = read_config_file(file)
      config = contents.empty? ? {} : Legion::JSON.load(contents)
      @settings = deep_merge(@settings, config)
      mark_dirty!
      @loaded_files << file
      log.debug("Loaded settings file #{file}")
    rescue Legion::JSON::ParseError => e
      log.error("config file must be valid json: #{file}")
      log.error("  parse error: #{e.message}")
    end
  else
    log.warn("Config file does not exist or is not readable file:#{file}")
  end
end

#load_module_default(config) ⇒ Object



231
232
233
234
235
236
# File 'lib/legion/settings/loader.rb', line 231

def load_module_default(config)
  mod_name = config.keys.first
  log.debug("Loading module defaults: #{mod_name}")
  @settings = deep_merge(config, @settings)
  mark_dirty!
end

#load_module_settings(config) ⇒ Object



223
224
225
226
227
228
229
# File 'lib/legion/settings/loader.rb', line 223

def load_module_settings(config)
  mod_name = config.keys.first
  log.debug("Loading module settings: #{mod_name}")
  @merged_modules = deep_merge(@merged_modules, config)
  @settings = deep_merge(config, @settings)
  mark_dirty!
end

#load_overrides!Object



279
280
281
# File 'lib/legion/settings/loader.rb', line 279

def load_overrides!
  load_client_overrides if %w[client rspec].include?(legion_service_name)
end

#logging_defaultsObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/legion/settings/loader.rb', line 67

def logging_defaults
  {
    level:       'info',
    format:      'text',
    log_file:    './legionio/logs/legion.log',
    log_stdout:  true,
    trace:       true,
    async:       true,
    include_pid: false,
    transport:   {
      enabled:            true,
      forward_logs:       true,
      forward_exceptions: true
    }
  }
end

#mark_dirty!Object



414
415
416
417
# File 'lib/legion/settings/loader.rb', line 414

def mark_dirty!
  @indifferent_access = false
  @hexdigest = nil
end

#set_env!Object



283
284
285
# File 'lib/legion/settings/loader.rb', line 283

def set_env!
  ENV['LEGION_LOADED_TEMPFILE'] = create_loaded_tempfile!
end

#to_hashObject



160
161
162
163
164
165
166
# File 'lib/legion/settings/loader.rb', line 160

def to_hash
  unless @indifferent_access
    indifferent_access!
    @hexdigest = nil
  end
  @settings
end

#validateObject



287
288
289
290
291
# File 'lib/legion/settings/loader.rb', line 287

def validate
  Legion::Settings.validate!
rescue Legion::Settings::ValidationError
  # errors are already collected in @errors
end