Skip to content

Commit

Permalink
Add support for Sync(annotation:). (#348)
Browse files Browse the repository at this point in the history
  • Loading branch information
paddor authored Oct 29, 2024
1 parent 72fae62 commit 9b94ec1
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 7 deletions.
2 changes: 1 addition & 1 deletion gems.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
end

group :test do
gem "sus", "~> 0.29", ">= 0.29.1"
gem "sus", "~> 0.31"
gem "covered"
gem "decode"
gem "rubocop"
Expand Down
10 changes: 7 additions & 3 deletions lib/kernel/sync.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,21 @@ module Kernel
#
# @public Since `stable-v1`.
# @asynchronous Will block until given block completes executing.
def Sync(&block)
def Sync(annotation: nil, &block)
if task = ::Async::Task.current?
yield task
if annotation
task.annotate(annotation) {yield task}
else
yield task
end
elsif scheduler = Fiber.scheduler
::Async::Task.run(scheduler, &block).wait
else
# This calls Fiber.set_scheduler(self):
reactor = Async::Reactor.new

begin
return reactor.run(finished: ::Async::Condition.new, &block).wait
return reactor.run(annotation: annotation, finished: ::Async::Condition.new, &block).wait
ensure
Fiber.set_scheduler(nil)
end
Expand Down
4 changes: 4 additions & 0 deletions test/kernel/async.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
Async(transient: true) do |task|
expect(task).to be(:transient?)
end

Async(annotation: 'foobar') do |task|
expect(task.annotation).to be == 'foobar'
end
end
end
end
32 changes: 29 additions & 3 deletions test/kernel/sync.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,45 @@

expect(result).to be == value
end


it "passes annotation through to initial task" do
Sync(annotation: 'foobar') do |task|
expect(task.annotation).to be == 'foobar'
end
end

it "can run inside reactor" do
Async do |task|
result = Sync do |sync_task|
expect(Async::Task.current).to be == task
expect(sync_task).to be == task

next value
end

expect(result).to be == value
end
end

with "parent task" do
it "replaces and restores existing task's annotation" do
annotations = []

Async(annotation: "foo") do |t1|
annotations << t1.annotation

Sync(annotation: "bar") do |t2|
expect(t2).to be_equal(t1)
annotations << t1.annotation
end

annotations << t1.annotation
end.wait

expect(annotations).to be == %w[foo bar foo]
end
end


it "can propagate error without logging them" do
expect(Console).not.to receive(:error)
Expand Down

0 comments on commit 9b94ec1

Please sign in to comment.