From 9b94ec1cbec6184d261a678fb54ae4c9d1a9109f Mon Sep 17 00:00:00 2001 From: Patrik Wenger Date: Tue, 29 Oct 2024 20:44:19 +0100 Subject: [PATCH] Add support for `Sync(annotation:)`. (#348) --- gems.rb | 2 +- lib/kernel/sync.rb | 10 +++++++--- test/kernel/async.rb | 4 ++++ test/kernel/sync.rb | 32 +++++++++++++++++++++++++++++--- 4 files changed, 41 insertions(+), 7 deletions(-) diff --git a/gems.rb b/gems.rb index 120e8af7..d5badfd3 100644 --- a/gems.rb +++ b/gems.rb @@ -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" diff --git a/lib/kernel/sync.rb b/lib/kernel/sync.rb index df384439..40ac242f 100644 --- a/lib/kernel/sync.rb +++ b/lib/kernel/sync.rb @@ -15,9 +15,13 @@ 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 @@ -25,7 +29,7 @@ def Sync(&block) 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 diff --git a/test/kernel/async.rb b/test/kernel/async.rb index 52f78d22..c59b9c50 100644 --- a/test/kernel/async.rb +++ b/test/kernel/async.rb @@ -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 diff --git a/test/kernel/sync.rb b/test/kernel/sync.rb index a7b477f8..249fee4f 100644 --- a/test/kernel/sync.rb +++ b/test/kernel/sync.rb @@ -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)