async_scheduler 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f6aa42c918acbc09fc86659737ee084809b5ce364e5052477598e15507531990
4
+ data.tar.gz: d9227670b7d089727630103dfe6d964663b0c407e5f34ae7e09f3e720937d6df
5
+ SHA512:
6
+ metadata.gz: '08331e26a7522de45cefedd85543ce2482ae875b2e31f9f270c9cb1c790f412fd988328a460a0e3bc08ec02931506e52eb9b01b90a1163758cc1be2a769408ac'
7
+ data.tar.gz: 4516d7b4da5b733008a3782216af11fd1d13400e2bb6170abc5ea53f4d8f30104986b08f45b04b73c4be1505c3417192f3cff21182627db4717cc3e57641864f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.1] - 2023-10-14
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at heyjudejudejude1968@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in async_scheduler.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+
14
+ # TODO: Remove gems below before releasing!
15
+ gem 'pry'
16
+ gem 'pry-doc'
17
+ gem 'pry-byebug'
18
+ gem 'pry-stack_explorer'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 kudojp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,71 @@
1
+ ⚠️ This project is still work in progress, and not published as a gem yet.
2
+
3
+ # AsyncScheduler
4
+
5
+ [![CI](https://github.com/kudojp/async_scheduler/actions/workflows/ci.yaml/badge.svg)](https://github.com/kudojp/async_scheduler/actions/workflows/ci.yaml)
6
+ [![codecov](https://codecov.io/gh/kudojp/async_scheduler/branch/main/graph/badge.svg?token=1JZU04RYFD)](https://codecov.io/gh/kudojp/async_scheduler)
7
+ [![License](https://img.shields.io/github/license/kudojp/async_scheduler)](./LICENSE)
8
+
9
+ This is a Fiber Schduler, which is a missing piece to do concurrent programming in Ruby language.
10
+ If you are not familiar with the concept of Fiber Schduler, please refer to my presentation: [Ruby の FiberScheduler を布教したい](https://speakerdeck.com/kudojp/ruby-false-fiberscheduler-wobu-jiao-sitai). (Sorry in Japanese.)
11
+
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'async_scheduler'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ ```
24
+ $ bundle install
25
+ ```
26
+
27
+ Or install it yourself as:
28
+
29
+ ```
30
+ $ gem install async_scheduler
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ Set this scheduler in the current thread.
36
+ Then, surround each of blocking oerations in `Fiber.schedule` block so that they are executed concurrently.
37
+
38
+ ```rb
39
+ Fiber.set_schduler AsyncScheduler::Scheduler.new
40
+
41
+ Fiber.schedule do
42
+ File.read("file1.txt") # some blocking operation
43
+ end
44
+
45
+ Fiber.schedule do
46
+ File.read("file2.txt") # some blocking operation
47
+ end
48
+
49
+ puts "Finished"
50
+ ```
51
+
52
+
53
+ ## Development
54
+
55
+ Add and run spec.
56
+
57
+ ```
58
+ bundle exec rspec
59
+ ```
60
+
61
+ ## Contributing
62
+
63
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kudojp/async_scheduler. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/kudojp/async_scheduler/blob/master/CODE_OF_CONDUCT.md).
64
+
65
+ ## License
66
+
67
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
68
+
69
+ ## Code of Conduct
70
+
71
+ Everyone interacting in the AsyncScheduler project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/async_scheduler/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/async_scheduler/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "async_scheduler"
7
+ spec.version = AsyncScheduler::VERSION
8
+ spec.authors = ["kudojp"]
9
+ spec.email = ["heyjudejudejude1968@gmail.com"]
10
+
11
+ spec.summary = "Asynchronous task scheduler in Ruby"
12
+ spec.description = "This is a task scheduler which implements the FiberScheduler interface"
13
+ spec.homepage = "https://github.com/kudojp/async_scheduler"
14
+ spec.license = "MIT"
15
+ # The interface of FiberScheduler#io_read had a breaking change from Ruby 3.0 to 3.1.
16
+ # - Ruby 3.0: #io_read takes 4 arguments.
17
+ # - Ruby 3.1: #io_read takes 3 arguments.
18
+ # The implementation of scheduler#io_read in this gem takes only 3 arguments.
19
+ spec.required_ruby_version = "~> 3.1.0"
20
+
21
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
22
+
23
+ spec.metadata["homepage_uri"] = spec.homepage
24
+ spec.metadata["source_code_uri"] = "https://github.com/kudojp/async_scheduler"
25
+ spec.metadata["changelog_uri"] = "https://github.com/kudojp/async_scheduler/blob/main/CHANGELOG.md"
26
+
27
+ # Specify which files should be added to the gem when it is released.
28
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
29
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
30
+ `git ls-files -z`.split("\x0").reject do |f|
31
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
32
+ end
33
+ end
34
+ spec.bindir = "exe"
35
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
36
+ spec.require_paths = ["lib"]
37
+
38
+ spec.add_dependency "resolv_fiber", "~>0.1"
39
+
40
+ spec.add_development_dependency "simplecov-cobertura"
41
+
42
+ # For more information and examples about making a new gem, check out our
43
+ # guide at: https://bundler.io/guides/creating_gem.html
44
+ end
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "async_scheduler"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ require "pry"
11
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/codecov.yaml ADDED
@@ -0,0 +1,6 @@
1
+ coverage:
2
+ status:
3
+ project:
4
+ default:
5
+ target: 30%
6
+ patch: false
@@ -0,0 +1,18 @@
1
+ module CrossThreadUsageDetector
2
+ class BelongingThreadAlreadySetError < StandardError; end
3
+ class CrossThreadUsageError < StandardError; end
4
+
5
+ def set_belonging_thread!
6
+ if defined? @belonging_thread_object_id
7
+ raise BelongingThreadAlreadySetError.new("@belonging_thread_object_id is already set with #{@belonging_thread_object_id}, but it is attempted to set again with #{Thread.current.object_id}.")
8
+ end
9
+
10
+ @belonging_thread_object_id = Thread.current.object_id
11
+ end
12
+
13
+ def validate_used_in_original_thread!
14
+ return if @belonging_thread_object_id == Thread.current.object_id
15
+
16
+ raise CrossThreadUsageError.new("Cross-thread usage detected. FiberScheduler was originally registered to a thread (#{@belonging_thread_object_id}), but it is attempted to be used in another thread (#{Thread.current.object_id}).")
17
+ end
18
+ end
@@ -0,0 +1,336 @@
1
+ require 'set'
2
+ require 'resolv_fiber'
3
+ require_relative './cross_thread_usage_detector'
4
+
5
+ module AsyncScheduler
6
+ # This class implements Fiber::SchedulerInterface.
7
+ # See https://ruby-doc.org/core-3.1.0/Fiber/SchedulerInterface.html for details.
8
+ class Scheduler
9
+ include CrossThreadUsageDetector
10
+
11
+ def initialize
12
+ set_belonging_thread!
13
+
14
+ # (key, value) = (Fiber object, timeout<not nil>)
15
+ @waitings = {}
16
+ # (key, value) = (blocking io, Fiber object)
17
+ @input_waitings = {}
18
+ @output_waitings = {}
19
+ # Fibers which are blocking and whose timeouts are not determined.
20
+ # e.g. Fiber which includes sleep()
21
+ @blockings = Set.new()
22
+ # (key, value) = (socket, Hash{:blocked_fiber => <Fiber object>, :timeout => <timeout>})
23
+ @blocking_sockets = {}
24
+ # NOTE: When either of the sockets(value) is ready, the fiber(key) can be resumed.
25
+ @fiber_to_all_blocker_sockets = Hash.new{|h, fiber| h[fiber] = Set.new}
26
+ end
27
+
28
+ # Implementation of the Fiber.schedule.
29
+ # The method is expected to immediately run the given block of code in a separate non-blocking fiber,
30
+ # and to return that Fiber.
31
+ def fiber(&block)
32
+ validate_used_in_original_thread!
33
+
34
+ fiber = Fiber.new(blocking: false, &block)
35
+ fiber.resume
36
+ fiber
37
+ end
38
+
39
+ # Invoked by methods like Thread.join, and by Mutex, to signify that current Fiber is blocked until further notice (e.g. unblock) or until timeout has elapsed.
40
+ # blocker is what we are waiting on, informational only (for debugging and logging). There are no guarantee about its value.
41
+ # Expected to return boolean, specifying whether the blocking operation was successful or not.
42
+ def block(blocker, timeout = nil)
43
+ validate_used_in_original_thread!
44
+
45
+ # TODO: Make use of blocker.
46
+ if timeout
47
+ @waitings[Fiber.current] = timeout
48
+ else
49
+ @blockings << Fiber.current
50
+ end
51
+
52
+ true
53
+ end
54
+
55
+ # Invoked to wake up Fiber previously blocked with block (for example, Mutex#lock calls block and Mutex#unlock calls unblock).
56
+ # The scheduler should use the fiber parameter to understand which fiber is unblocked.
57
+ # blocker is what was awaited for, but it is informational only (for debugging and logging),
58
+ # and it is not guaranteed to be the same value as the blocker for block.
59
+ def unblock(blocker, fiber)
60
+ validate_used_in_original_thread!
61
+
62
+ # TODO: Make use of blocker.
63
+ @blockings.delete fiber
64
+ fiber.resume
65
+ end
66
+
67
+ # Invoked by Kernel#sleep and Mutex#sleep and is expected to provide an implementation of sleeping in a non-blocking way.
68
+ # Implementation might register the current fiber in some list of “which fiber wait until what moment”,
69
+ # call Fiber.yield to pass control, and then in close resume the fibers whose wait period has elapsed.
70
+ def kernel_sleep(duration = nil)
71
+ validate_used_in_original_thread!
72
+
73
+ timeout = duration ? Process.clock_gettime(Process::CLOCK_MONOTONIC) + duration : nil
74
+ if block(:kernel_sleep, timeout)
75
+ Fiber.yield
76
+ else
77
+ raise RuntimeError.new("Failed to sleep")
78
+ end
79
+ end
80
+
81
+ # Invoked by Timeout.timeout to execute the given block within the given duration.
82
+ # It can also be invoked directly by the scheduler or user code.
83
+ #
84
+ # This implementation will only interrupt non-blocking operations.
85
+ # If the block is executed successfully, its result will be returned.
86
+ def timeout_after(duration, exception_class, *exception_arguments, &block) # → result of block
87
+ validate_used_in_original_thread!
88
+
89
+ current_fiber = Fiber.current
90
+
91
+ if duration
92
+ self.fiber() do
93
+ sleep(duration)
94
+ if current_fiber.alive?
95
+ current_fiber.raise(exception_class, *exception_arguments)
96
+ end
97
+ end
98
+ end
99
+
100
+ yield duration
101
+ end
102
+
103
+ # Called when the current thread exits. The scheduler is expected to implement this method in order to allow all waiting fibers to finalize their execution.
104
+ # The suggested pattern is to implement the main event loop in the close method.
105
+ def close
106
+ validate_used_in_original_thread!
107
+
108
+ while !@waitings.empty? || !@blockings.empty? || !@input_waitings.empty? || !@output_waitings.empty? || !@blocking_sockets.empty?
109
+ # For blocking I/Os...
110
+ while !@input_waitings.empty? || !@output_waitings.empty? || !@blocking_sockets.empty?
111
+ soonest_timeout_ = self.soonest_timeout
112
+ select_duration =
113
+ if soonest_timeout_.nil?
114
+ nil
115
+ else
116
+ duration = soonest_timeout_ - Process.clock_gettime(Process::CLOCK_MONOTONIC)
117
+ # duration here should be very close to 0 even if it is negative.
118
+ [duration, 0].max
119
+ end
120
+
121
+ # NOTE: IO.select will keep blocking until timeout even if any new event is added to @waitings.
122
+ # TODO: Don't wait for the input ready when the corresponding fiber gets terminated, and when it is the only one in @input_waitings.
123
+ # TODO: Don't wait for the output ready when the corresponding fiber gets terminated, and when it is the only one in @output_waitings.
124
+ inputs_ready, outputs_ready = IO.select(
125
+ @input_waitings.keys + @blocking_sockets.keys,
126
+ @output_waitings.keys,
127
+ [],
128
+ select_duration
129
+ )
130
+
131
+ inputs_ready&.each do |input|
132
+ if @input_waitings[input]
133
+ fiber_non_blocking = @input_waitings.delete(input)
134
+ fiber_non_blocking.resume if fiber_non_blocking.alive?
135
+ elsif @blocking_sockets[input]
136
+ fiber = @blocking_sockets.delete(input).fetch(:blocked_fiber)
137
+ # ref. comment in #address_resolve
138
+ @fiber_to_all_blocker_sockets.fetch(fiber).each do |socket|
139
+ @blocking_sockets.delete(socket)
140
+ end
141
+ fiber.resume
142
+ else
143
+ raise
144
+ end
145
+ end
146
+
147
+ current_clock_monotonic_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
148
+
149
+ timeout_sockets = @blocking_sockets.select{|socket, blocked| blocked.fetch(:timeout) && (blocked.fetch(:timeout) <= current_clock_monotonic_time)}.keys
150
+ # NOTE: timeout_sockets is nil when there is no rejected element.
151
+ @blocking_sockets.reject!{|socket| timeout_sockets&.include? socket}
152
+ timeout_sockets&.each do |socket|
153
+ @fiber_to_all_blocker_sockets.fetch(fiber).delete(socket)
154
+ fiber.resume if @fiber_to_all_blocker_sockets.fetch(fiber).empty? && fiber.alive?
155
+ end
156
+
157
+ outputs_ready&.each do |output|
158
+ fiber_non_blocking = @output_waitings.delete(output)
159
+ fiber_non_blocking.resume if fiber_non_blocking.alive?
160
+ end
161
+ end
162
+
163
+ unless @waitings.empty?
164
+ # TODO: Use a min heap for @waitings
165
+ resumable_fibers = @waitings.select{|_fiber, timeout| timeout <= Process.clock_gettime(Process::CLOCK_MONOTONIC)}
166
+ .map{|fiber, _timeout| fiber}
167
+ .to_set
168
+ resumable_fibers.each{|fiber| fiber.resume if fiber.alive?}
169
+ @waitings.reject!{|fiber, _timeout| resumable_fibers.include? fiber}
170
+ end
171
+
172
+ # Unfortunately, current scheduler is unfair to @blockings. Even if any of @blockings is ready, current scheduler has no way to notice it.
173
+ @blockings.select!{|fiber| fiber.alive?}
174
+ end
175
+ end
176
+
177
+ def soonest_timeout
178
+ waitings_earliest_timeout = @waitings.empty? ? nil : @waitings.min_by{|fiber, timeout| timeout}[1]
179
+ blocking_socket_earliest_timeout = @blocking_sockets.select{|_socket, blocked| blocked.fetch(:timeout)}.values.min_by{|blocked| blocked.fetch(:timeout)}[0]&.fetch(:timeout)
180
+
181
+ if waitings_earliest_timeout && blocking_socket_earliest_timeout
182
+ return [waitings_earliest_timeout, blocking_socket_earliest_timeout].min
183
+ end
184
+
185
+ waitings_earliest_timeout || blocking_socket_earliest_timeout
186
+ end
187
+ private_methods :soonest_timeout
188
+
189
+ # Invoked by IO#wait, IO#wait_readable, IO#wait_writable to ask whether the specified descriptor is ready for specified events within the specified timeout.
190
+ # events is a bit mask of IO::READABLE, IO::WRITABLE, and IO::PRIORITY.
191
+
192
+ # Suggested implementation should register which Fiber is waiting for which resources and immediately calling Fiber.yield to pass control to other fibers.
193
+ # Then, in the close method, the scheduler might dispatch all the I/O resources to fibers waiting for it.
194
+ # Expected to return the subset of events that are ready immediately.
195
+ def io_wait(io, events, _timeout)
196
+ validate_used_in_original_thread!
197
+
198
+ # TODO: use timeout parameter
199
+ # TODO?: Expected to return the subset of events that are ready immediately.
200
+
201
+ if events & IO::READABLE == IO::READABLE
202
+ @input_waitings[io] = Fiber.current
203
+ end
204
+
205
+ if events & IO::WRITABLE == IO::WRITABLE
206
+ @output_waitings[io] = Fiber.current
207
+ end
208
+
209
+ Fiber.yield
210
+ end
211
+
212
+ # Invoked by IO#read to read length bytes from io into a specified buffer (see IO::Buffer).
213
+ # The length argument is the “minimum length to be read”. If the IO buffer size is 8KiB, but the length is 1024 (1KiB), up to 8KiB might be read, but at least 1KiB will be.
214
+ # Generally, the only case where less data than length will be read is if there is an error reading the data.
215
+ # Specifying a length of 0 is valid and means try reading at least once and return any available data.
216
+
217
+ # Suggested implementation should try to read from io in a non-blocking manner and call io_wait if the io is not ready (which will yield control to other fibers).
218
+ # See IO::Buffer for an interface available to return data.
219
+ # Expected to return number of bytes read, or, in case of an error, -errno (negated number corresponding to system's error code).
220
+ def io_read(io, buffer, length) # return length or -errno
221
+ validate_used_in_original_thread!
222
+
223
+ read_string = ""
224
+ offset = 0
225
+ while offset < length || length == 0
226
+ read_nonblock = Fiber.new(blocking: true) do
227
+ # AsyncScheduler::Scheduler#io_read is hooked to IO#read_nonblock.
228
+ # To avoid an infinite call loop, IO#read_nonblock is called inside a Fiber whose blocking=true.
229
+ # ref. https://docs.ruby-lang.org/ja/latest/method/IO/i/read_nonblock.html
230
+ io.read_nonblock(buffer.size-offset, read_string, exception: false)
231
+ end
232
+
233
+ begin
234
+ # This fiber is resumed only here.
235
+ result = read_nonblock.resume
236
+ rescue SystemCallError => e
237
+ return -e.errno
238
+ end
239
+
240
+ case result
241
+ when :wait_readable
242
+ io_wait(io, IO::READABLE, nil)
243
+ when nil # when reaching EOF
244
+ # TODO: Investigate if it is expected to break here.
245
+ break
246
+ else
247
+ offset += buffer.set_string(read_string, offset) # this does not work with `#set_string(result)`
248
+ break if length == 0
249
+ end
250
+ end
251
+ return offset
252
+ end
253
+
254
+ # Invoked by IO#write to write length bytes to io from from a specified buffer (see IO::Buffer).
255
+ # The length argument is the “(minimum) length to be written”.
256
+ # If the IO buffer size is 8KiB, but the length specified is 1024 (1KiB), at most 8KiB will be written, but at least 1KiB will be.
257
+ # Generally, the only case where less data than length will be written is if there is an error writing the data.
258
+
259
+ # Specifying a length of 0 is valid and means try writing at least once, as much data as possible.
260
+ # Suggested implementation should try to write to io in a non-blocking manner and call io_wait if the io is not ready (which will yield control to other fibers).
261
+ # See IO::Buffer for an interface available to get data from buffer efficiently.
262
+ # Expected to return number of bytes written, or, in case of an error, -errno (negated number corresponding to system's error code).
263
+ def io_write(io, buffer, length) # returns: written length or -errnoclick to toggle source
264
+ validate_used_in_original_thread!
265
+
266
+ offset = 0
267
+
268
+ while offset < length || length == 0
269
+ write_nonblock = Fiber.new(blocking: true) do
270
+ # TODO: Investigate if this #write_nonblock method call should be in a non-blocking fiber.
271
+ # IO#read_nonblock is hooked to Scheduler#io_wait, so it has to be wrapped.
272
+ # If IO#read_nonblock is hooked to Scheduler#io_read, this method call has to be wrapped too.
273
+ # ref. https://docs.ruby-lang.org/ja/latest/class/IO.html#I_WRITE_NONBLOCK
274
+ io.write_nonblock(buffer.get_string(offset), exception: false)
275
+ end
276
+
277
+ begin
278
+ result = write_nonblock.resume
279
+ rescue SystemCallError => e
280
+ return -e.errno
281
+ end
282
+
283
+ case result
284
+ when :wait_writable
285
+ io_wait(io, IO::WRITABLE, nil)
286
+ else
287
+ offset += result
288
+ break if length == 0 # Specification says it tries writing at least once if length == 0
289
+ end
290
+ end
291
+ return offset
292
+ end
293
+
294
+ # Invoked by any method that performs a non-reverse DNS lookup. (e.g. Addrinfo.getaddrinfo)
295
+ # The method is expected to return an array of strings corresponding to ip addresses the hostname is resolved to, or nil if it can not be resolved.
296
+ def address_resolve(hostname)
297
+ # NOTE:
298
+ # Asynchronous DNS lookup is slower than sequential DNS lookup in a single thread in my experiment.
299
+ # Remove #address_resolve when this scheduler is used in a performance critical application.
300
+ # Run $ `bundle exec rspec spec/blockings/address_resolve_spec.rb` to confirm it.
301
+
302
+ validate_used_in_original_thread!
303
+ fiber = ::ResolvFiber.getaddresses_fiber(hostname)
304
+ # Fiber.yield inside of this fiber is located in the loop and may be called multiple times.
305
+ # So here in the caller, the fiber has to be resumed multiple times till the fiber becomes terminated.
306
+ loop do
307
+ result = fiber.resume
308
+ return result unless fiber.alive?
309
+
310
+ socks, timeout = result
311
+ # In my experiment, socks here are:
312
+ # - socket to connect to the DNS server which has IPv4 address
313
+ # - socket to connect to the DNS server which has IPv6 address
314
+ # When either of these is ready, DNS resolution is done.
315
+ socks.each do |sock|
316
+ # Fiber.current is blocked by multiple sockets in this way:
317
+ # @blocking_sockets = {
318
+ # first_socket: { blocked_fiber: Fiber.current, timeout: 1111 },
319
+ # second_socket: { blocked_fiber: Fiber.current, timeout: 1111 },
320
+ # }
321
+ # If first_socket is ready, both of `first_socket` and `second_socket` must be removed from @blocking_sockets before the fiber gets resumed.
322
+ # (@fiber_to_all_blocker_sockets is used to realize this.)
323
+ # Otherwise, when second_socket is ready, `Fiber.current` will be resumed again unexpectedly.
324
+ # Same thing can be said if second_socket is ready first.
325
+ @blocking_sockets[sock] = {
326
+ blocked_fiber: Fiber.current,
327
+ timeout: timeout,
328
+ }
329
+ @fiber_to_all_blocker_sockets[Fiber.current] << sock
330
+ end
331
+
332
+ Fiber.yield
333
+ end
334
+ end
335
+ end
336
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsyncScheduler
4
+ VERSION = "0.1.1"
5
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "async_scheduler/version"
4
+ require_relative "async_scheduler/scheduler"
5
+
6
+ module AsyncScheduler
7
+ end
@@ -0,0 +1,4 @@
1
+ module AsyncScheduler
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: async_scheduler
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - kudojp
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-10-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: resolv_fiber
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: simplecov-cobertura
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: This is a task scheduler which implements the FiberScheduler interface
42
+ email:
43
+ - heyjudejudejude1968@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".rspec"
49
+ - ".rubocop.yml"
50
+ - CHANGELOG.md
51
+ - CODE_OF_CONDUCT.md
52
+ - Gemfile
53
+ - LICENSE.txt
54
+ - README.md
55
+ - Rakefile
56
+ - async_scheduler.gemspec
57
+ - bin/console
58
+ - bin/setup
59
+ - codecov.yaml
60
+ - lib/async_scheduler.rb
61
+ - lib/async_scheduler/cross_thread_usage_detector.rb
62
+ - lib/async_scheduler/scheduler.rb
63
+ - lib/async_scheduler/version.rb
64
+ - sig/async_std_scheduler.rbs
65
+ homepage: https://github.com/kudojp/async_scheduler
66
+ licenses:
67
+ - MIT
68
+ metadata:
69
+ allowed_push_host: https://rubygems.org
70
+ homepage_uri: https://github.com/kudojp/async_scheduler
71
+ source_code_uri: https://github.com/kudojp/async_scheduler
72
+ changelog_uri: https://github.com/kudojp/async_scheduler/blob/main/CHANGELOG.md
73
+ post_install_message:
74
+ rdoc_options: []
75
+ require_paths:
76
+ - lib
77
+ required_ruby_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: 3.1.0
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ requirements: []
88
+ rubygems_version: 3.3.26
89
+ signing_key:
90
+ specification_version: 4
91
+ summary: Asynchronous task scheduler in Ruby
92
+ test_files: []