Skip to content

Commit

Permalink
Fix: prefer System::Time.monotonic over Time.monotonic
Browse files Browse the repository at this point in the history
Avoids an issue with the timecop shard that overrides Time.monotonic.
  • Loading branch information
ysbaddaden committed Oct 22, 2024
1 parent f2a1efe commit b14fa3c
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 5 deletions.
6 changes: 5 additions & 1 deletion src/crystal/system/unix/evented/event.cr
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ struct Crystal::Evented::Event
include PointerLinkedList::Node

def initialize(@type : Type, @fiber, @index = nil, timeout : Time::Span? = nil)
@wake_at = Time.monotonic + timeout if timeout
if timeout
seconds, nanoseconds = System::Time.monotonic
now = Time::Span.new(seconds: seconds, nanoseconds: nanoseconds)
@wake_at = now + timeout
end
end

# Mark the IO event as timed out.
Expand Down
4 changes: 3 additions & 1 deletion src/crystal/system/unix/evented/fiber_event.cr
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ class Crystal::Evented::FiberEvent

# sleep or select timeout
def add(timeout : Time::Span) : Nil
@event.wake_at = Time.monotonic + timeout
seconds, nanoseconds = System::Time.monotonic
now = Time::Span.new(seconds: seconds, nanoseconds: nanoseconds)
@event.wake_at = now + timeout
@event_loop.add_timer(pointerof(@event))
end

Expand Down
6 changes: 4 additions & 2 deletions src/crystal/system/unix/evented/timers.cr
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ struct Crystal::Evented::Timers
end

# Dequeues and yields each ready timer (their `#wake_at` is lower than
# `Time.monotonic`) from the oldest to the most recent (i.e. time ascending).
# `System::Time.monotonic`) from the oldest to the most recent (i.e. time
# ascending).
def dequeue_ready(& : Evented::Event* -> Nil) : Nil
return if @list.empty?

now = Time.monotonic
seconds, nanoseconds = System::Time.monotonic
now = Time::Span.new(seconds: seconds, nanoseconds: nanoseconds)
n = 0

@list.each do |event|
Expand Down
6 changes: 5 additions & 1 deletion src/crystal/system/unix/kqueue/event_loop.cr
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,11 @@ class Crystal::Kqueue::EventLoop < Crystal::Evented::EventLoop
private def system_set_timer(time : Time::Span?) : Nil
if time
flags = LibC::EV_ADD | LibC::EV_ONESHOT | LibC::EV_CLEAR
t = time - Time.monotonic

seconds, nanoseconds = System::Time.monotonic
now = Time::Span.new(seconds: seconds, nanoseconds: nanoseconds)
t = time - now

data =
{% if LibC.has_constant?(:NOTE_NSECONDS) %}
t.total_nanoseconds.to_i64!.clamp(0..)
Expand Down

0 comments on commit b14fa3c

Please sign in to comment.