-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Add Crystal::FdLock
+ integration
#16128
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
ysbaddaden
wants to merge
16
commits into
crystal-lang:master
Choose a base branch
from
ysbaddaden:feature/add-crystal-fd-lock
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+480
−116
Draft
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
5c38b65
Add `system_fcntl` to `System::FileDescriptor` and `System::Socket`
ysbaddaden 149287c
Fix: don't pass fd to system_[gs]etsockopt
ysbaddaden d3fecb7
Add system_tc[gs]etattr instead of class methods
ysbaddaden d0b69c8
Fix: bug
ysbaddaden 848b720
Revert an unrelated change
ysbaddaden 6731e29
Add Crystal::FdLock (simple reference counter)
ysbaddaden 3eb62c6
Initial integration of FdLock into System::FileDescriptor and System:…
ysbaddaden 44509cf
Fix: must reset fdlock in TCPSocket#initialize
ysbaddaden ae7cb21
Fix: decrement
ysbaddaden e4c1c46
Add simple specs for FdLock
ysbaddaden 7ee7eef
Fix: GC finalization cycle warning
ysbaddaden 2fe6738
Don't measure elapsed time in specs, use synchronization instead
ysbaddaden 264c520
Try improve handle_last_ref readability
ysbaddaden 8f2ecfa
NOOP unless the preview_mt flag is passed
ysbaddaden aa0dd33
Drop relative require
ysbaddaden 9301e5b
Update spec/std/crystal/fd_lock_spec.cr
ysbaddaden File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
require "spec" | ||
require "crystal/fd_lock" | ||
require "wait_group" | ||
|
||
describe Crystal::FdLock do | ||
describe "#reference" do | ||
it "acquires" do | ||
lock = Crystal::FdLock.new | ||
called = 0 | ||
|
||
lock.reference { called += 1 } | ||
lock.reference { called += 1 } | ||
|
||
called.should eq(2) | ||
end | ||
|
||
it "allows reentrancy (side effect)" do | ||
lock = Crystal::FdLock.new | ||
called = 0 | ||
|
||
lock.reference { called += 1 } | ||
lock.reference do | ||
lock.reference { called += 1 } | ||
end | ||
|
||
called.should eq(2) | ||
end | ||
|
||
it "acquires shared reference" do | ||
lock = Crystal::FdLock.new | ||
|
||
ready = WaitGroup.new(1) | ||
release = Channel(String).new | ||
|
||
spawn do | ||
lock.reference do | ||
ready.done | ||
|
||
select | ||
when release.send("ok") | ||
when timeout(1.second) | ||
release.send("timeout") | ||
end | ||
end | ||
end | ||
|
||
ready.wait | ||
lock.reference { } | ||
|
||
release.receive.should eq("ok") | ||
end | ||
|
||
it "raises when closed" do | ||
lock = Crystal::FdLock.new | ||
lock.try_close? { } | ||
|
||
called = false | ||
expect_raises(IO::Error, "Closed") do | ||
lock.reference { called = true } | ||
end | ||
|
||
called.should be_false | ||
end | ||
end | ||
|
||
describe "#try_close?" do | ||
it "closes" do | ||
lock = Crystal::FdLock.new | ||
lock.closed?.should be_false | ||
|
||
called = false | ||
lock.try_close? { called = true }.should be_true | ||
lock.closed?.should be_true | ||
called.should be_true | ||
end | ||
|
||
it "closes once" do | ||
lock = Crystal::FdLock.new | ||
|
||
called = 0 | ||
|
||
WaitGroup.wait do |wg| | ||
10.times do | ||
wg.spawn do | ||
lock.try_close? { called += 1 } | ||
lock.try_close? { called += 1 } | ||
end | ||
end | ||
end | ||
|
||
called.should eq(1) | ||
end | ||
|
||
it "waits for all references to return" do | ||
lock = Crystal::FdLock.new | ||
|
||
ready = WaitGroup.new(10) | ||
exceptions = Channel(Exception).new(10) | ||
|
||
WaitGroup.wait do |wg| | ||
10.times do | ||
wg.spawn do | ||
begin | ||
lock.reference do | ||
ready.done | ||
Fiber.yield | ||
end | ||
rescue ex | ||
exceptions.send(ex) | ||
end | ||
end | ||
end | ||
|
||
ready.wait | ||
|
||
called = false | ||
lock.try_close? { called = true }.should eq(true) | ||
lock.closed?.should be_true | ||
end | ||
exceptions.close | ||
|
||
if ex = exceptions.receive? | ||
raise ex | ||
end | ||
end | ||
end | ||
|
||
it "#reset" do | ||
lock = Crystal::FdLock.new | ||
lock.try_close? { } | ||
lock.reset | ||
lock.try_close? { }.should eq(true) | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
# :nodoc: | ||
# | ||
# Tracks active references over a system file descriptor (fd). | ||
# | ||
# The fdlock can be closed at any time, but the actual system close will wait | ||
# until there are no more references left. This avoids potential races when a | ||
# thread might try to read a fd that has been closed and has been reused by the | ||
# OS. | ||
struct Crystal::FdLock | ||
CLOSED = 1_u32 # the fdlock has been closed | ||
REF = 2_u32 # the ref counter increment | ||
MASK = ~(REF - 1) # mask for the ref counter | ||
|
||
{% if flag?(:preview_mt) %} | ||
@m = Atomic(UInt32).new(0_u32) | ||
@closing : Fiber? | ||
{% else %} | ||
@closed = false | ||
{% end %} | ||
|
||
# Borrows a reference for the duration of the block. Raises if the fdlock is | ||
# closed while trying to borrow. | ||
def reference(& : -> F) : F forall F | ||
{% if flag?(:preview_mt) %} | ||
m, success = @m.compare_and_set(0_u32, REF, :acquire, :relaxed) | ||
increment_slow(m) unless success | ||
|
||
begin | ||
yield | ||
ensure | ||
m = @m.sub(REF, :release) | ||
handle_last_ref(m) | ||
end | ||
{% else %} | ||
raise IO::Error.new("Closed") if @closed | ||
yield | ||
{% end %} | ||
end | ||
|
||
private def increment_slow(m) | ||
while true | ||
if (m & CLOSED) == CLOSED | ||
raise IO::Error.new("Closed") | ||
end | ||
m, success = @m.compare_and_set(m, m + REF, :acquire, :relaxed) | ||
break if success | ||
end | ||
end | ||
|
||
private def handle_last_ref(m) | ||
return unless (m & CLOSED) == CLOSED # is closed? | ||
return unless (m & MASK) == REF # was the last ref? | ||
|
||
# the last ref after close is responsible to resume the closing fiber | ||
@closing.not_nil!("BUG: expected a closing fiber to resume.").enqueue | ||
end | ||
|
||
# Closes the fdlock. Blocks for as long as there are references. | ||
# | ||
# Returns true if the fdlock has been closed: no fiber can acquire a reference | ||
# anymore, the calling fiber fully owns the fd and can safely close it. | ||
# | ||
# Returns false if the fdlock has already been closed: the calling fiber | ||
# doesn't own the fd and musn't close it (there might still be active | ||
# references). | ||
def try_close?(&before_close : ->) : Bool | ||
{% if flag?(:preview_mt) %} | ||
m = @m.get(:relaxed) | ||
|
||
# increment ref and close (abort if already closed) | ||
while true | ||
if (m & CLOSED) == CLOSED | ||
return false | ||
end | ||
m, success = @m.compare_and_set(m, (m + REF) | CLOSED, :acquire, :relaxed) | ||
break if success | ||
end | ||
|
||
# set the current fiber as the closing fiber (to be resumed by the last ref) | ||
# then decrement ref | ||
@closing = Fiber.current | ||
m = @m.sub(REF, :release) | ||
|
||
begin | ||
# before close callback | ||
yield | ||
ensure | ||
# wait for the last ref... unless we're the last ref! | ||
Fiber.suspend unless (m & MASK) == REF | ||
end | ||
|
||
@closing = nil | ||
true | ||
{% else %} | ||
if @closed | ||
false | ||
else | ||
@closed = true | ||
yield | ||
true | ||
end | ||
{% end %} | ||
end | ||
|
||
# Resets the fdlock back to its pristine state so it can be used again. | ||
# Assumes the caller owns the fdlock. This is required by | ||
# `TCPSocket#initialize`. | ||
def reset : Nil | ||
{% if flag?(:preview_mt) %} | ||
@m.lazy_set(0_u32) | ||
@closing = nil | ||
{% else %} | ||
@closed = false | ||
{% end %} | ||
end | ||
|
||
def closed? : Bool | ||
{% if flag?(:preview_mt) %} | ||
(@m.get(:relaxed) & CLOSED) == CLOSED | ||
{% else %} | ||
@closed | ||
{% end %} | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
thought: The names
before_close
andclose
are not very descriptive about their actual purpose. Maybe we can find more explicit names?before_close
closes the wrapper object, whileclose
closes the system resource. Maybeclose_wrapper
andclose_system_fd
? Not entirely convinced these are the best choices, but they seem better than the current ones...Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure what you mean with "wrapper object". Maybe
#before_close
could be#resume_all
but it becomes a directive (do this) rather than a broader "we're about to close, do whatever you need to"But
#close
becomes more to the point: close this fd/sock (and only useful forio_uring
that can close async).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe "wrapper object" is not a good term. I was thinking about
FileDescriptor
as being a wrapper of the system API. Andbefore_close
takes care of closing the aspects specific to the runtime, whileclose
closes the actual file descriptor resource for the OS.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note that the behavior of
#before_close
here is identical to the#reopened
hook called after we reopen a file descriptor: resume any pending waiter for the givenIO::FileDescriptor
orSocket
. We might as well have a single#resume_all
, maybe?