Skip to content
Kward Search API index

Class: Kward::PluginResources

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/plugins/resources.rb

Overview

Owns cleanup callbacks and cooperative background tasks for a plugin or tab.

Constant Summary collapse

DEFAULT_SHUTDOWN_TIMEOUT =
1.0

Instance Method Summary collapse

Constructor Details

#initialize(name:, warning_sink: nil) ⇒ PluginResources

Returns a new instance of PluginResources.



112
113
114
115
116
117
118
119
120
# File 'lib/kward/plugins/resources.rb', line 112

def initialize(name:, warning_sink: nil)
  @name = name.to_s
  @warning_sink = warning_sink
  @mutex = Mutex.new
  @state = :initialized
  @tasks = []
  @disposables = []
  @next_task_id = 0
end

Instance Method Details

#activate! ⇒ Object



122
123
124
125
126
127
128
129
# File 'lib/kward/plugins/resources.rb', line 122

def activate!
  @mutex.synchronize do
    raise "#{@name} resources have already been stopped" if @state == :stopped

    @state = :active
  end
  self
end

#background(name: nil, cancellation: nil, &work) ⇒ Object

Raises:

  • (ArgumentError)


131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/kward/plugins/resources.rb', line 131

def background(name: nil, cancellation: nil, &work)
  raise ArgumentError, "plugin background task requires a block" unless work

  task = @mutex.synchronize do
    raise "#{@name} background work cannot start before plugin activation" unless @state == :active

    @next_task_id += 1
    task_name = name.to_s.empty? ? "task-#{@next_task_id}" : name.to_s
    task_cancellation = Cancellation.new
    cancellation&.on_cancel { task_cancellation.cancel! }
    PluginTask.new(name: task_name, cancellation: task_cancellation, &work).tap do |created|
      @tasks << created
      created.start { |finished| finish_task(finished) }
    end
  end
  task
end

#on_cleanup(resource = nil, &cleanup) ⇒ Object Also known as: manage



149
150
151
152
153
154
155
156
157
# File 'lib/kward/plugins/resources.rb', line 149

def on_cleanup(resource = nil, &cleanup)
  disposable = PluginDisposable.new(resource, &cleanup)
  @mutex.synchronize do
    raise "#{@name} resources have already been stopped" if @state == :stopped

    @disposables << disposable
  end
  disposable
end

#shutdown(timeout: DEFAULT_SHUTDOWN_TIMEOUT) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/kward/plugins/resources.rb', line 161

def shutdown(timeout: DEFAULT_SHUTDOWN_TIMEOUT)
  tasks, disposables = @mutex.synchronize do
    return self if @state == :stopped

    @state = :stopped
    [@tasks.dup, @disposables.reverse]
  end

  tasks.each(&:cancel!)
  disposables.each { |disposable| dispose(disposable) }
  join_tasks(tasks, timeout)
  self
end