Skip to content

Commit

Permalink
Add Async::Pool::Controller#as_json and related methods. (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix authored Apr 22, 2024
1 parent 1f634c8 commit ee098ef
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 10 deletions.
33 changes: 23 additions & 10 deletions lib/async/pool/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@ def initialize(constructor, limit: nil, concurrency: (limit || 1), policy: nil)
# @attribute [Integer] The maximum number of resources that this pool can have at any given time.
attr_accessor :limit

def to_s
if @resources.empty?
"\#<#{self.class}(#{usage_string})>"
else
"\#<#{self.class}(#{usage_string}) #{availability_summary.join(';')}>"
end
end

def as_json(...)
{
limit: @limit,
concurrency: @guard.limit,
usage: @resources.size,
availability_summary: self.availability_summary,
}
end

def to_json(...)
as_json.to_json(...)
end

# @attribute [Integer] The maximum number of concurrent tasks that can be creating a new resource.
def concurrency
@guard.limit
Expand Down Expand Up @@ -133,14 +154,6 @@ def close
@gardener&.stop
end

def to_s
if @resources.empty?
"\#<#{self.class}(#{usage_string})>"
else
"\#<#{self.class}(#{usage_string}) #{availability_string}>"
end
end

# Retire (and close) all unused resources. If a block is provided, it should implement the desired functionality for unused resources.
# @param retain [Integer] the minimum number of resources to retain.
# @yield resource [Resource] unused resources.
Expand Down Expand Up @@ -215,10 +228,10 @@ def usage_string
"#{@resources.size}/#{@limit || '∞'}"
end

def availability_string
def availability_summary
@resources.collect do |resource, usage|
"#{usage}/#{resource.concurrency}#{resource.viable? ? nil : '*'}/#{resource.count}"
end.join(";")
end
end

# def usage
Expand Down
15 changes: 15 additions & 0 deletions test/async/pool/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@
it 'is empty?' do
expect(pool).to be(:empty?)
end

with '#as_json' do
it 'generates a JSON representation' do
expect(pool.as_json).to be == {
limit: nil,
concurrency: 1,
usage: 0,
availability_summary: []
}
end

it "generates a JSON string" do
expect(JSON.dump(pool)).to be == pool.to_json
end
end
end

with 'a limited pool' do
Expand Down

0 comments on commit ee098ef

Please sign in to comment.