Module: Legion::Extensions

Defined in:
lib/legion/extensions.rb,
lib/legion/extensions/core.rb,
lib/legion/extensions/data.rb,
lib/legion/extensions/transport.rb,
lib/legion/extensions/data/model.rb,
lib/legion/extensions/actors/base.rb,
lib/legion/extensions/actors/loop.rb,
lib/legion/extensions/actors/once.rb,
lib/legion/extensions/actors/poll.rb,
lib/legion/extensions/helpers/lex.rb,
lib/legion/extensions/actors/every.rb,
lib/legion/extensions/helpers/base.rb,
lib/legion/extensions/helpers/core.rb,
lib/legion/extensions/helpers/data.rb,
lib/legion/extensions/helpers/task.rb,
lib/legion/extensions/builders/base.rb,
lib/legion/extensions/data/migrator.rb,
lib/legion/extensions/helpers/cache.rb,
lib/legion/extensions/actors/nothing.rb,
lib/legion/extensions/helpers/logger.rb,
lib/legion/extensions/actors/defaults.rb,
lib/legion/extensions/builders/actors.rb,
lib/legion/extensions/builders/helpers.rb,
lib/legion/extensions/builders/runners.rb,
lib/legion/extensions/helpers/transport.rb,
lib/legion/extensions/actors/subscription.rb

Defined Under Namespace

Modules: Actors, Builder, Core, Data, Helpers, Transport

Class Method Summary collapse

Class Method Details

.find_extensionsObject



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/legion/extensions.rb', line 176

def find_extensions
  @extensions ||= {}
  Gem::Specification.all_names.each do |gem|
    next unless gem[0..3] == 'lex-'

    lex = gem.split('-')
    @extensions[lex[1]] = { full_gem_name:   gem,
                            gem_name:        "lex-#{lex[1]}",
                            extension_name:  lex[1],
                            version:         lex[2],
                            extension_class: "Legion::Extensions::#{lex[1].split('_').collect(&:capitalize).join}" }
  end

  enabled = 0
  requested = 0

  Legion::Settings[:extensions].each do |extension, values|
    next if @extensions.key? extension.to_s
    next if values[:enabled] == false

    requested += 1
    next if values[:auto_install] == false
    next if ENV['_'].include? 'bundle'

    Legion::Logging.warn "#{extension} is missing, attempting to install automatically.."
    install = Gem.install("lex-#{extension}", values[:version])
    Legion::Logging.debug(install)
    lex = Gem::Specification.find_by_name("lex-#{extension}")

    @extensions[extension.to_s] = {
      full_gem_name:   "lex-#{extension}-#{lex.version}",
      gem_name:        "lex-#{extension}",
      extension_name:  extension.to_s,
      version:         lex.version,
      extension_class: "Legion::Extensions::#{extension.to_s.split('_').collect(&:capitalize).join}"
    }

    enabled += 1

  rescue StandardError, Gem::MissingSpecError => e
    Legion::Logging.error "Failed to auto install #{extension}, e: #{e.message}"
  end
  return true if requested == enabled

  Legion::Logging.warn "A total of #{requested - enabled} where skipped"
  if ENV.key?('_') && ENV['_'].include?('bundle')
    Legion::Logging.warn 'Please add them to your Gemfile since you are using bundler'
  else
    Legion::Logging.warn 'You must have auto_install_missing_lex set to true to auto install missing extensions'
  end
end

.gem_load(gem_name, name) ⇒ Object



166
167
168
169
170
171
172
173
174
# File 'lib/legion/extensions.rb', line 166

def gem_load(gem_name, name)
  require "#{Gem::Specification.find_by_name(gem_name).gem_dir}/lib/legion/extensions/#{name}"
  true
rescue LoadError => e
  Legion::Logging.error e.message
  Legion::Logging.error e.backtrace
  Legion::Logging.error "gem_path: #{gem_path}" unless gem_path.nil?
  false
end

.hook_actor(extension:, extension_name:, actor_class:, size: 1, **opts) ⇒ Object



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
159
160
161
162
163
164
# File 'lib/legion/extensions.rb', line 115

def hook_actor(extension:, extension_name:, actor_class:, size: 1, **opts)
  size = if Legion::Settings[:extensions].key?(extension_name.to_sym) && Legion::Settings[:extensions][extension_name.to_sym].key?(:workers)
           Legion::Settings[:extensions][extension_name.to_sym][:workers]
         elsif size.is_a? Integer
           size
         else
           1
         end

  extension_hash = {
    extension:       extension,
    extension_name:  extension_name,
    actor_class:     actor_class,
    size:            size,
    fallback_policy: :abort,
    **opts
  }
  extension_hash[:running_class] = if actor_class.ancestors.include? Legion::Extensions::Actors::Subscription
                                     actor_class
                                   else
                                     actor_class.new
                                   end

  return if extension_hash[:running_class].respond_to?(:enabled?) && !extension_hash[:running_class].enabled?

  if actor_class.ancestors.include? Legion::Extensions::Actors::Every
    @timer_tasks.push(extension_hash)
  elsif actor_class.ancestors.include? Legion::Extensions::Actors::Once
    @once_tasks.push(extension_hash)
  elsif actor_class.ancestors.include? Legion::Extensions::Actors::Loop
    @loop_tasks.push(extension_hash)
  elsif actor_class.ancestors.include? Legion::Extensions::Actors::Poll
    @poll_tasks.push(extension_hash)
  elsif actor_class.ancestors.include? Legion::Extensions::Actors::Subscription
    extension_hash[:threadpool] = Concurrent::FixedThreadPool.new(size)
    size.times do
      extension_hash[:threadpool].post do
        klass = actor_class.new
        if klass.respond_to?(:async)
          klass.async.subscribe
        else
          klass.subscribe
        end
      end
    end
    @subscription_tasks.push(extension_hash)
  else
    Legion::Logging.fatal 'did not match any actor classes'
  end
end

.hook_extensionsObject



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/legion/extensions.rb', line 11

def hook_extensions
  @timer_tasks = []
  @loop_tasks = []
  @once_tasks = []
  @poll_tasks = []
  @subscription_tasks = []
  @actors = []

  find_extensions
  load_extensions
end

.load_extension(extension, values) ⇒ Object

rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity, Metrics/AbcSize



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
113
# File 'lib/legion/extensions.rb', line 62

def load_extension(extension, values) # rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity, Metrics/AbcSize
  return unless gem_load(values[:gem_name], extension)

  extension = Kernel.const_get(values[:extension_class])
  extension.extend Legion::Extensions::Core unless extension.singleton_class.included_modules.include? Legion::Extensions::Core

  min_version = Legion::Settings[:extensions][values[:extension_name]][:min_version] || nil
  Legion::Logging.fatal values if min_version.is_a?(String) && Gem::Version.new(values[:version]) >= Gem::Version.new(min_version)

  if extension.data_required? && Legion::Settings[:data][:connected] == false
    Legion::Logging.warn "#{values[:extension_name]} requires Legion::Data but isn't enabled, skipping"
    return false
  end

  if extension.cache_required? && Legion::Settings[:cache][:connected] == false
    Legion::Logging.warn "#{values[:extension_name]} requires Legion::Cache but isn't enabled, skipping"
    return false
  end

  if extension.crypt_required? && Legion::Settings[:crypt][:cs].nil?
    Legion::Logging.warn "#{values[:extension_name]} requires Legion::Crypt but isn't ready, skipping"
    return false
  end

  if extension.vault_required? && Legion::Settings[:crypt][:vault][:connected] == false
    Legion::Logging.warn "#{values[:extension_name]} requires Legion::Crypt::Vault but isn't enabled, skipping"
    return false
  end

  has_logger = extension.respond_to?(:log)
  extension.autobuild

  require 'legion/transport/messages/lex_register'
  Legion::Transport::Messages::LexRegister.new(function: 'save', opts: extension.runners).publish

  if extension.respond_to?(:meta_actors) && extension.meta_actors.is_a?(Array)
    extension.meta_actors.each do |_key, actor|
      extension.log.debug("hooking meta actor: #{actor}") if has_logger
      hook_actor(**actor)
    end
  end

  extension.actors.each do |_key, actor|
    extension.log.debug("hooking literal actor: #{actor}") if has_logger
    hook_actor(**actor)
  end
  extension.log.info "Loaded v#{extension::VERSION}"
rescue StandardError => e
  Legion::Logging.error e.message
  Legion::Logging.error e.backtrace
  false
end

.load_extensionsObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/legion/extensions.rb', line 39

def load_extensions
  @extensions ||= {}
  @loaded_extensions ||= []
  @extensions.each do |extension, values|
    if values.key(:enabled) && !values[:enabled]
      Legion::Logging.info "Skipping #{extension} because it's disabled"
      next
    end

    if Legion::Settings[:extensions].key?(extension.to_sym) && Legion::Settings[:extensions][extension.to_sym].key?(:enabled) && !Legion::Settings[:extensions][extension.to_sym][:enabled] # rubocop:disable Layout/LineLength
      next
    end

    unless load_extension(extension, values)
      Legion::Logging.warn("#{extension} failed to load")
      next
    end
    @loaded_extensions.push(extension)
    sleep(0.1)
  end
  Legion::Logging.info "#{@extensions.count} extensions loaded with subscription:#{@subscription_tasks.count},every:#{@timer_tasks.count},poll:#{@poll_tasks.count},once:#{@once_tasks.count},loop:#{@loop_tasks.count}"
end

.setupObject



7
8
9
# File 'lib/legion/extensions.rb', line 7

def setup
  hook_extensions
end

.shutdownObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/legion/extensions.rb', line 23

def shutdown
  return nil if @loaded_extensions.nil?

  @subscription_tasks.each do |task|
    task[:threadpool].shutdown
    task[:threadpool].kill unless task[:threadpool].wait_for_termination(5)
  end

  @loop_tasks.each { |task| task[:running_class].cancel if task[:running_class].respond_to?(:cancel) }
  @once_tasks.each { |task| task[:running_class].cancel if task[:running_class].respond_to?(:cancel) }
  @timer_tasks.each { |task| task[:running_class].cancel if task[:running_class].respond_to?(:cancel) }
  @poll_tasks.each { |task| task[:running_class].cancel if task[:running_class].respond_to?(:cancel) }

  Legion::Logging.info 'Successfully shut down all actors'
end