mirror of
https://github.com/apple/swift-nio
synced 2026-11-24 04:37:54 +00:00
Add deadlines as an alternative to timeouts (#770)
Add deadlines as an alternative to timeouts Motivation: Address #603 Modifications: - Add NIODeadline type - Add func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> - Reduce the use of DispatchTime in favor of Time - Replace timeout calls with deadline calls where it makes sense Result: Tasks can be scheduled after an amount of time has passed, or at a certain time.
This commit is contained in:
1 parent
de8d3e260e
commit
0eb85a4478
13 files changed
+172
-76
No files matched your search
@@ -15,8 +15,6 @@
|
||||
//
|
||||
//
|
||||
|
||||
import struct Dispatch.DispatchTime
|
||||
|
||||
|
||||
/// A `ChannelHandler` that implements a backoff for a `ServerChannel` when accept produces an `IOError`.
|
||||
/// These errors are often recoverable by reducing the rate at which we call accept.
|
||||
@@ -24,7 +22,7 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler {
|
||||
public typealias InboundIn = Channel
|
||||
public typealias OutboundIn = Channel
|
||||
|
||||
private var nextReadDeadlineNS: TimeAmount.Value?
|
||||
private var nextReadDeadlineNS: NIODeadline?
|
||||
private let backoffProvider: (IOError) -> TimeAmount?
|
||||
private var scheduledRead: Scheduled<Void>?
|
||||
|
||||
@@ -46,13 +44,13 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler {
|
||||
guard scheduledRead == nil else { return }
|
||||
|
||||
if let deadline = self.nextReadDeadlineNS {
|
||||
let now = TimeAmount.Value(DispatchTime.now().uptimeNanoseconds)
|
||||
let now = NIODeadline.now()
|
||||
if now >= deadline {
|
||||
// The backoff already expired, just do a read.
|
||||
doRead(ctx)
|
||||
} else {
|
||||
// Schedule the read to be executed after the backoff time elapsed.
|
||||
scheduleRead(in: .nanoseconds(deadline - now), ctx: ctx)
|
||||
scheduleRead(at: deadline, ctx: ctx)
|
||||
}
|
||||
} else {
|
||||
ctx.read()
|
||||
@@ -62,10 +60,10 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler {
|
||||
public func errorCaught(ctx: ChannelHandlerContext, error: Error) {
|
||||
if let ioError = error as? IOError {
|
||||
if let amount = backoffProvider(ioError) {
|
||||
self.nextReadDeadlineNS = TimeAmount.Value(DispatchTime.now().uptimeNanoseconds) + amount.nanoseconds
|
||||
self.nextReadDeadlineNS = .now() + amount
|
||||
if let scheduled = self.scheduledRead {
|
||||
scheduled.cancel()
|
||||
scheduleRead(in: amount, ctx: ctx)
|
||||
scheduleRead(at: self.nextReadDeadlineNS!, ctx: ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,8 +89,8 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler {
|
||||
self.nextReadDeadlineNS = nil
|
||||
}
|
||||
|
||||
private func scheduleRead(in: TimeAmount, ctx: ChannelHandlerContext) {
|
||||
self.scheduledRead = ctx.eventLoop.scheduleTask(in: `in`) {
|
||||
private func scheduleRead(at: NIODeadline, ctx: ChannelHandlerContext) {
|
||||
self.scheduledRead = ctx.eventLoop.scheduleTask(deadline: at) {
|
||||
self.doRead(ctx)
|
||||
}
|
||||
}
|
||||
@@ -174,8 +172,8 @@ public class IdleStateHandler: ChannelDuplexHandler {
|
||||
public let allTimeout: TimeAmount?
|
||||
|
||||
private var reading = false
|
||||
private var lastReadTime: DispatchTime = DispatchTime(uptimeNanoseconds: 0)
|
||||
private var lastWriteCompleteTime: DispatchTime = DispatchTime(uptimeNanoseconds: 0)
|
||||
private var lastReadTime: NIODeadline = .distantPast
|
||||
private var lastWriteCompleteTime: NIODeadline = .distantPast
|
||||
private var scheduledReaderTask: Scheduled<Void>?
|
||||
private var scheduledWriterTask: Scheduled<Void>?
|
||||
private var scheduledAllTask: Scheduled<Void>?
|
||||
@@ -210,7 +208,7 @@ public class IdleStateHandler: ChannelDuplexHandler {
|
||||
|
||||
public func channelReadComplete(ctx: ChannelHandlerContext) {
|
||||
if (readTimeout != nil || allTimeout != nil) && reading {
|
||||
lastReadTime = DispatchTime.now()
|
||||
lastReadTime = .now()
|
||||
reading = false
|
||||
}
|
||||
ctx.fireChannelReadComplete()
|
||||
@@ -224,7 +222,7 @@ public class IdleStateHandler: ChannelDuplexHandler {
|
||||
|
||||
let writePromise = promise ?? ctx.eventLoop.makePromise()
|
||||
writePromise.futureResult.whenComplete { (_: Result<Void, Error>) in
|
||||
self.lastWriteCompleteTime = DispatchTime.now()
|
||||
self.lastWriteCompleteTime = .now()
|
||||
}
|
||||
ctx.write(data, promise: writePromise)
|
||||
}
|
||||
@@ -247,15 +245,15 @@ public class IdleStateHandler: ChannelDuplexHandler {
|
||||
return
|
||||
}
|
||||
|
||||
let diff = TimeAmount.Value(DispatchTime.now().uptimeNanoseconds) - TimeAmount.Value(self.lastReadTime.uptimeNanoseconds)
|
||||
if diff >= timeout.nanoseconds {
|
||||
let diff = .now() - self.lastReadTime
|
||||
if diff >= timeout {
|
||||
// Reader is idle - set a new timeout and trigger an event through the pipeline
|
||||
self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeReadTimeoutTask(ctx, timeout))
|
||||
|
||||
ctx.fireUserInboundEventTriggered(IdleStateEvent.read)
|
||||
} else {
|
||||
// Read occurred before the timeout - set a new timeout with shorter delay.
|
||||
self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: .nanoseconds(timeout.nanoseconds - diff), self.makeReadTimeoutTask(ctx, timeout))
|
||||
self.scheduledReaderTask = ctx.eventLoop.scheduleTask(deadline: self.lastReadTime + timeout, self.makeReadTimeoutTask(ctx, timeout))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -267,16 +265,16 @@ public class IdleStateHandler: ChannelDuplexHandler {
|
||||
}
|
||||
|
||||
let lastWriteTime = self.lastWriteCompleteTime
|
||||
let diff = DispatchTime.now().uptimeNanoseconds - lastWriteTime.uptimeNanoseconds
|
||||
let diff = .now() - lastWriteTime
|
||||
|
||||
if diff >= timeout.nanoseconds {
|
||||
if diff >= timeout {
|
||||
// Writer is idle - set a new timeout and notify the callback.
|
||||
self.scheduledWriterTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeWriteTimeoutTask(ctx, timeout))
|
||||
|
||||
ctx.fireUserInboundEventTriggered(IdleStateEvent.write)
|
||||
} else {
|
||||
// Write occurred before the timeout - set a new timeout with shorter delay.
|
||||
self.scheduledWriterTask = ctx.eventLoop.scheduleTask(in: .nanoseconds(TimeAmount.Value(timeout.nanoseconds) - TimeAmount.Value(diff)), self.makeWriteTimeoutTask(ctx, timeout))
|
||||
self.scheduledWriterTask = ctx.eventLoop.scheduleTask(deadline: self.lastWriteCompleteTime + timeout, self.makeWriteTimeoutTask(ctx, timeout))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,16 +291,17 @@ public class IdleStateHandler: ChannelDuplexHandler {
|
||||
}
|
||||
let lastRead = self.lastReadTime
|
||||
let lastWrite = self.lastWriteCompleteTime
|
||||
let latestLast = max(lastRead, lastWrite)
|
||||
|
||||
let diff = TimeAmount.Value(DispatchTime.now().uptimeNanoseconds) - TimeAmount.Value((lastRead > lastWrite ? lastRead : lastWrite).uptimeNanoseconds)
|
||||
if diff >= timeout.nanoseconds {
|
||||
let diff = .now() - latestLast
|
||||
if diff >= timeout {
|
||||
// Reader is idle - set a new timeout and trigger an event through the pipeline
|
||||
self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: timeout, self.makeAllTimeoutTask(ctx, timeout))
|
||||
|
||||
ctx.fireUserInboundEventTriggered(IdleStateEvent.all)
|
||||
} else {
|
||||
// Read occurred before the timeout - set a new timeout with shorter delay.
|
||||
self.scheduledReaderTask = ctx.eventLoop.scheduleTask(in: .nanoseconds(TimeAmount.Value(timeout.nanoseconds) - diff), self.makeAllTimeoutTask(ctx, timeout))
|
||||
self.scheduledReaderTask = ctx.eventLoop.scheduleTask(deadline: latestLast + timeout, self.makeAllTimeoutTask(ctx, timeout))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -315,7 +314,7 @@ public class IdleStateHandler: ChannelDuplexHandler {
|
||||
}
|
||||
|
||||
private func initIdleTasks(_ ctx: ChannelHandlerContext) {
|
||||
let now = DispatchTime.now()
|
||||
let now = NIODeadline.now()
|
||||
lastReadTime = now
|
||||
lastWriteCompleteTime = now
|
||||
scheduledReaderTask = schedule(ctx, readTimeout, makeReadTimeoutTask)
|
||||
|
||||
@@ -16,9 +16,9 @@ import Dispatch
|
||||
|
||||
private final class EmbeddedScheduledTask {
|
||||
let task: () -> Void
|
||||
let readyTime: UInt64
|
||||
let readyTime: NIODeadline
|
||||
|
||||
init(readyTime: UInt64, task: @escaping () -> Void) {
|
||||
init(readyTime: NIODeadline, task: @escaping () -> Void) {
|
||||
self.readyTime = readyTime
|
||||
self.task = task
|
||||
}
|
||||
@@ -48,7 +48,7 @@ extension EmbeddedScheduledTask: Comparable {
|
||||
/// unsynchronized fashion.
|
||||
public class EmbeddedEventLoop: EventLoop {
|
||||
/// The current "time" for this event loop. This is an amount in nanoseconds.
|
||||
private var now: UInt64 = 0
|
||||
private var now: NIODeadline = .uptimeNanoseconds(0)
|
||||
|
||||
private var scheduledTasks = PriorityQueue<EmbeddedScheduledTask>(ascending: true)
|
||||
|
||||
@@ -59,10 +59,9 @@ public class EmbeddedEventLoop: EventLoop {
|
||||
public init() { }
|
||||
|
||||
@discardableResult
|
||||
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
|
||||
public func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> {
|
||||
let promise: EventLoopPromise<T> = makePromise()
|
||||
let readyTime = now + UInt64(`in`.nanoseconds)
|
||||
let task = EmbeddedScheduledTask(readyTime: readyTime) {
|
||||
let task = EmbeddedScheduledTask(readyTime: deadline) {
|
||||
do {
|
||||
promise.succeed(try task())
|
||||
} catch let err {
|
||||
@@ -77,11 +76,16 @@ public class EmbeddedEventLoop: EventLoop {
|
||||
return scheduled
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
|
||||
return scheduleTask(deadline: self.now + `in`, task)
|
||||
}
|
||||
|
||||
// We're not really running a loop here. Tasks aren't run until run() is called,
|
||||
// at which point we run everything that's been submitted. Anything newly submitted
|
||||
// either gets on that train if it's still moving or waits until the next call to run().
|
||||
public func execute(_ task: @escaping () -> Void) {
|
||||
self.scheduleTask(in: .nanoseconds(0), task)
|
||||
self.scheduleTask(deadline: self.now, task)
|
||||
}
|
||||
|
||||
public func run() {
|
||||
@@ -92,7 +96,7 @@ public class EmbeddedEventLoop: EventLoop {
|
||||
/// Runs the event loop and moves "time" forward by the given amount, running any scheduled
|
||||
/// tasks that need to be run.
|
||||
public func advanceTime(by: TimeAmount) {
|
||||
let newTime = self.now + UInt64(by.nanoseconds)
|
||||
let newTime = self.now + by
|
||||
|
||||
while let nextTask = self.scheduledTasks.peek() {
|
||||
guard nextTask.readyTime <= newTime else {
|
||||
|
||||
+114
-11
@@ -208,6 +208,10 @@ public protocol EventLoop: EventLoopGroup {
|
||||
/// - returns: `EventLoopFuture` that is notified once the task was executed.
|
||||
func submit<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T>
|
||||
|
||||
/// Schedule a `task` that is executed by this `SelectableEventLoop` at the given time.
|
||||
@discardableResult
|
||||
func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T>
|
||||
|
||||
/// Schedule a `task` that is executed by this `SelectableEventLoop` after the given amount of time.
|
||||
@discardableResult
|
||||
func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T>
|
||||
@@ -291,6 +295,101 @@ extension TimeAmount: Comparable {
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeAmount {
|
||||
public static func + (lhs: TimeAmount, rhs: TimeAmount) -> TimeAmount {
|
||||
return TimeAmount(lhs.nanoseconds + rhs.nanoseconds)
|
||||
}
|
||||
|
||||
public static func - (lhs: TimeAmount, rhs: TimeAmount) -> TimeAmount {
|
||||
return TimeAmount(lhs.nanoseconds - rhs.nanoseconds)
|
||||
}
|
||||
|
||||
public static func * <T: BinaryInteger>(lhs: T, rhs: TimeAmount) -> TimeAmount {
|
||||
return TimeAmount(TimeAmount.Value(lhs) * rhs.nanoseconds)
|
||||
}
|
||||
|
||||
public static func * <T: BinaryInteger>(lhs: TimeAmount, rhs: T) -> TimeAmount {
|
||||
return TimeAmount(lhs.nanoseconds * TimeAmount.Value(rhs))
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a point in time.
|
||||
///
|
||||
/// Stores the time in nanoseconds as returned by `DispatchTime.now().uptimeNanoseconds`
|
||||
///
|
||||
/// `NIODeadline` allow chaining multiple tasks with the same deadline without needing to
|
||||
/// compute new timeouts for each step
|
||||
///
|
||||
/// ```
|
||||
/// func doSomething(deadline: NIODeadline) -> EventLoopFuture<Void> {
|
||||
/// return step1(deadline: deadline).then {
|
||||
/// step2(deadline: deadline)
|
||||
/// }
|
||||
/// }
|
||||
/// doSomething(deadline: .now() + .seconds(5))
|
||||
/// ```
|
||||
///
|
||||
/// - note: `NIODeadline` should not be used to represent a time interval
|
||||
public struct NIODeadline: Equatable, Hashable {
|
||||
public typealias Value = UInt64
|
||||
|
||||
/// The nanoseconds since boot representation of the `NIODeadline`.
|
||||
public let uptimeNanoseconds: Value
|
||||
|
||||
public static let distantPast = NIODeadline(0)
|
||||
public static let distantFuture = NIODeadline(DispatchTime.distantFuture.uptimeNanoseconds)
|
||||
|
||||
private init(_ nanoseconds: Value) {
|
||||
self.uptimeNanoseconds = nanoseconds
|
||||
}
|
||||
|
||||
public static func now() -> NIODeadline {
|
||||
return NIODeadline(DispatchTime.now().uptimeNanoseconds)
|
||||
}
|
||||
|
||||
public static func uptimeNanoseconds(_ nanoseconds: Value) -> NIODeadline {
|
||||
return NIODeadline(nanoseconds)
|
||||
}
|
||||
}
|
||||
|
||||
extension NIODeadline: Comparable {
|
||||
public static func < (lhs: NIODeadline, rhs: NIODeadline) -> Bool {
|
||||
return lhs.uptimeNanoseconds < rhs.uptimeNanoseconds
|
||||
}
|
||||
|
||||
public static func > (lhs: NIODeadline, rhs: NIODeadline) -> Bool {
|
||||
return lhs.uptimeNanoseconds > rhs.uptimeNanoseconds
|
||||
}
|
||||
}
|
||||
|
||||
extension NIODeadline: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return self.uptimeNanoseconds.description
|
||||
}
|
||||
}
|
||||
|
||||
extension NIODeadline {
|
||||
public static func - (lhs: NIODeadline, rhs: NIODeadline) -> TimeAmount {
|
||||
return .nanoseconds(TimeAmount.Value(lhs.uptimeNanoseconds - rhs.uptimeNanoseconds))
|
||||
}
|
||||
|
||||
public static func + (lhs: NIODeadline, rhs: TimeAmount) -> NIODeadline {
|
||||
if rhs.nanoseconds < 0 {
|
||||
return NIODeadline(lhs.uptimeNanoseconds - rhs.nanoseconds.magnitude)
|
||||
} else {
|
||||
return NIODeadline(lhs.uptimeNanoseconds + rhs.nanoseconds.magnitude)
|
||||
}
|
||||
}
|
||||
|
||||
public static func - (lhs: NIODeadline, rhs: TimeAmount) -> NIODeadline {
|
||||
if rhs.nanoseconds < 0 {
|
||||
return NIODeadline(lhs.uptimeNanoseconds + rhs.nanoseconds.magnitude)
|
||||
} else {
|
||||
return NIODeadline(lhs.uptimeNanoseconds - rhs.nanoseconds.magnitude)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EventLoop {
|
||||
public func submit<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T> {
|
||||
let promise: EventLoopPromise<T> = makePromise(file: #file, line: #line)
|
||||
@@ -569,7 +668,7 @@ internal final class SelectableEventLoop: EventLoop {
|
||||
return thread.isCurrent
|
||||
}
|
||||
|
||||
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
|
||||
public func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> {
|
||||
let promise: EventLoopPromise<T> = makePromise()
|
||||
let task = ScheduledTask({
|
||||
do {
|
||||
@@ -579,7 +678,7 @@ internal final class SelectableEventLoop: EventLoop {
|
||||
}
|
||||
}, { error in
|
||||
promise.fail(error)
|
||||
},`in`)
|
||||
}, deadline)
|
||||
|
||||
let scheduled = Scheduled(promise: promise, cancellationTask: {
|
||||
self.tasksLock.withLockVoid {
|
||||
@@ -592,10 +691,14 @@ internal final class SelectableEventLoop: EventLoop {
|
||||
return scheduled
|
||||
}
|
||||
|
||||
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
|
||||
return scheduleTask(deadline: .now() + `in`, task)
|
||||
}
|
||||
|
||||
public func execute(_ task: @escaping () -> Void) {
|
||||
schedule0(ScheduledTask(task, { error in
|
||||
// do nothing
|
||||
}, .nanoseconds(0)))
|
||||
}, .now()))
|
||||
}
|
||||
|
||||
/// Add the `ScheduledTask` to be executed.
|
||||
@@ -648,7 +751,7 @@ internal final class SelectableEventLoop: EventLoop {
|
||||
return .block
|
||||
}
|
||||
|
||||
let nextReady = sched.readyIn(DispatchTime.now())
|
||||
let nextReady = sched.readyIn(.now())
|
||||
if nextReady <= .nanoseconds(0) {
|
||||
// Something is ready to be processed just do a non-blocking select of events.
|
||||
return .now
|
||||
@@ -698,7 +801,7 @@ internal final class SelectableEventLoop: EventLoop {
|
||||
tasksLock.withLockVoid {
|
||||
if !scheduledTasks.isEmpty {
|
||||
// We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway.
|
||||
let now = DispatchTime.now()
|
||||
let now: NIODeadline = .now()
|
||||
|
||||
// Make a copy of the tasks so we can execute these while not holding the lock anymore
|
||||
while tasksCopy.count < tasksCopy.capacity, let task = scheduledTasks.peek() {
|
||||
@@ -989,19 +1092,19 @@ final public class MultiThreadedEventLoopGroup: EventLoopGroup {
|
||||
private final class ScheduledTask {
|
||||
let task: () -> Void
|
||||
private let failFn: (Error) ->()
|
||||
private let readyTime: TimeAmount.Value
|
||||
private let readyTime: NIODeadline
|
||||
|
||||
init(_ task: @escaping () -> Void, _ failFn: @escaping (Error) -> Void, _ time: TimeAmount) {
|
||||
init(_ task: @escaping () -> Void, _ failFn: @escaping (Error) -> Void, _ time: NIODeadline) {
|
||||
self.task = task
|
||||
self.failFn = failFn
|
||||
self.readyTime = time.nanoseconds + TimeAmount.Value(DispatchTime.now().uptimeNanoseconds)
|
||||
self.readyTime = time
|
||||
}
|
||||
|
||||
func readyIn(_ t: DispatchTime) -> TimeAmount {
|
||||
if readyTime < t.uptimeNanoseconds {
|
||||
func readyIn(_ t: NIODeadline) -> TimeAmount {
|
||||
if readyTime < t {
|
||||
return .nanoseconds(0)
|
||||
}
|
||||
return .nanoseconds(readyTime - TimeAmount.Value(t.uptimeNanoseconds))
|
||||
return readyTime - t
|
||||
}
|
||||
|
||||
func fail(_ error: Error) {
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOConcurrencyHelpers
|
||||
import Dispatch
|
||||
|
||||
/// `NonBlockingFileIO` is a helper that allows you to read files without blocking the calling thread.
|
||||
///
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Dispatch
|
||||
|
||||
private enum SelectorLifecycleState {
|
||||
case open
|
||||
case closing
|
||||
@@ -248,7 +246,7 @@ final class Selector<R: Registration> {
|
||||
private typealias EventType = Epoll.epoll_event
|
||||
private let eventfd: Int32
|
||||
private let timerfd: Int32
|
||||
private var earliestTimer: UInt64 = UInt64.max
|
||||
private var earliestTimer: NIODeadline = .distantFuture
|
||||
#else
|
||||
private typealias EventType = kevent
|
||||
#endif
|
||||
@@ -491,7 +489,7 @@ final class Selector<R: Registration> {
|
||||
// Only call timerfd_settime if we not already scheduled one that will cover it.
|
||||
// This guards against calling timerfd_settime if not needed as this is generally speaking
|
||||
// expensive.
|
||||
let next = DispatchTime.now().uptimeNanoseconds + UInt64(timeAmount.nanoseconds)
|
||||
let next = NIODeadline.now() + timeAmount
|
||||
if next < self.earliestTimer {
|
||||
self.earliestTimer = next
|
||||
|
||||
@@ -521,7 +519,7 @@ final class Selector<R: Registration> {
|
||||
_ = Glibc.read(timerfd, &val, MemoryLayout<UInt>.size)
|
||||
|
||||
// Processed the earliest set timer so reset it.
|
||||
self.earliestTimer = UInt64.max
|
||||
self.earliestTimer = .distantFuture
|
||||
default:
|
||||
// If the registration is not in the Map anymore we deregistered it during the processing of whenReady(...). In this case just skip it.
|
||||
if let registration = registrations[Int(ev.data.fd)] {
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Dispatch
|
||||
import NIO
|
||||
import NIOHTTP1
|
||||
import NIOWebSocket
|
||||
@@ -145,7 +144,7 @@ private final class WebSocketTimeHandler: ChannelInboundHandler {
|
||||
|
||||
// We can't really check for error here, but it's also not the purpose of the
|
||||
// example so let's not worry about it.
|
||||
let theTime = DispatchTime.now().uptimeNanoseconds
|
||||
let theTime = NIODeadline.now().uptimeNanoseconds
|
||||
var buffer = ctx.channel.allocator.buffer(capacity: 12)
|
||||
buffer.write(string: "\(theTime)")
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Dispatch
|
||||
import NIO
|
||||
import NIOHTTP1
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Dispatch
|
||||
import NIO
|
||||
import NIOHTTP1
|
||||
|
||||
|
||||
@@ -562,7 +562,7 @@ class HTTPUpgradeTestCase: XCTestCase {
|
||||
|
||||
// At this time we should have received one user event. We schedule this onto the
|
||||
// event loop to guarantee thread safety.
|
||||
XCTAssertNoThrow(try connectedServer.eventLoop.scheduleTask(in: .nanoseconds(0)) {
|
||||
XCTAssertNoThrow(try connectedServer.eventLoop.scheduleTask(deadline: .now()) {
|
||||
XCTAssertEqual(eventSaver.events.count, 1)
|
||||
if case .upgradeComplete(let proto, let req) = eventSaver.events[0] {
|
||||
XCTAssertEqual(proto, "myproto")
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
|
||||
import XCTest
|
||||
@testable import NIO
|
||||
import Dispatch
|
||||
import NIOConcurrencyHelpers
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import NIOConcurrencyHelpers
|
||||
public class EventLoopTest : XCTestCase {
|
||||
|
||||
public func testSchedule() throws {
|
||||
let nanos = DispatchTime.now().uptimeNanoseconds
|
||||
let nanos: NIODeadline = .now()
|
||||
let amount: TimeAmount = .seconds(1)
|
||||
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
@@ -29,7 +29,7 @@ public class EventLoopTest : XCTestCase {
|
||||
true
|
||||
}.futureResult.wait()
|
||||
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= amount.nanoseconds)
|
||||
XCTAssertTrue(NIODeadline.now() - nanos >= amount)
|
||||
XCTAssertTrue(value)
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ public class EventLoopTest : XCTestCase {
|
||||
let clientBootstrap = ClientBootstrap(group: eventLoopGroup)
|
||||
|
||||
// Now, schedule two tasks: one that takes a while, one that doesn't.
|
||||
let nanos = DispatchTime.now().uptimeNanoseconds
|
||||
let nanos: NIODeadline = .now()
|
||||
let longFuture = eventLoopGroup.next().scheduleTask(in: longAmount) {
|
||||
true
|
||||
}.futureResult
|
||||
@@ -60,12 +60,12 @@ public class EventLoopTest : XCTestCase {
|
||||
// Ok, the short one has happened. Now we should try connecting them. This connect should happen
|
||||
// faster than the final task firing.
|
||||
_ = try assertNoThrowWithValue(clientBootstrap.connect(to: serverChannel.localAddress!).wait()) as Channel
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos < longAmount.nanoseconds)
|
||||
XCTAssertTrue(NIODeadline.now() - nanos < longAmount)
|
||||
|
||||
// Now wait for the long-delayed task.
|
||||
XCTAssertTrue(try assertNoThrowWithValue(try longFuture.wait()))
|
||||
// Now we're ok.
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= longAmount.nanoseconds)
|
||||
XCTAssertTrue(NIODeadline.now() - nanos >= longAmount)
|
||||
}
|
||||
|
||||
public func testScheduleCancelled() throws {
|
||||
@@ -80,19 +80,19 @@ public class EventLoopTest : XCTestCase {
|
||||
|
||||
scheduled.cancel()
|
||||
|
||||
let nanos = DispatchTime.now().uptimeNanoseconds
|
||||
let nanos = NIODeadline.now()
|
||||
let amount: TimeAmount = .seconds(2)
|
||||
let value = try eventLoopGroup.next().scheduleTask(in: amount) {
|
||||
true
|
||||
}.futureResult.wait()
|
||||
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= amount.nanoseconds)
|
||||
XCTAssertTrue(NIODeadline.now() - nanos >= amount)
|
||||
XCTAssertTrue(value)
|
||||
XCTAssertFalse(ran.load())
|
||||
}
|
||||
|
||||
public func testScheduleRepeatedTask() throws {
|
||||
let nanos = DispatchTime.now().uptimeNanoseconds
|
||||
let nanos: NIODeadline = .now()
|
||||
let initialDelay: TimeAmount = .milliseconds(5)
|
||||
let delay: TimeAmount = .milliseconds(10)
|
||||
let count = 5
|
||||
@@ -109,7 +109,7 @@ public class EventLoopTest : XCTestCase {
|
||||
let initialValue = counter.load()
|
||||
_ = counter.add(1)
|
||||
if initialValue == 0 {
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= initialDelay.nanoseconds)
|
||||
XCTAssertTrue(NIODeadline.now() - nanos >= initialDelay)
|
||||
} else if initialValue == count {
|
||||
expect.fulfill()
|
||||
repeatedTask.cancel()
|
||||
@@ -119,7 +119,7 @@ public class EventLoopTest : XCTestCase {
|
||||
waitForExpectations(timeout: 1) { error in
|
||||
XCTAssertNil(error)
|
||||
XCTAssertEqual(counter.load(), count + 1)
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= initialDelay.nanoseconds + numericCast(count) * delay.nanoseconds)
|
||||
XCTAssertTrue(NIODeadline.now() - nanos >= initialDelay + TimeAmount.Value(count) * delay)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ public class EventLoopTest : XCTestCase {
|
||||
}
|
||||
|
||||
public func testScheduleRepeatedTaskCancelFromDifferentThread() throws {
|
||||
let nanos = DispatchTime.now().uptimeNanoseconds
|
||||
let nanos: NIODeadline = .now()
|
||||
let initialDelay: TimeAmount = .milliseconds(5)
|
||||
let delay: TimeAmount = .milliseconds(0) // this will actually force the race from issue #554 to happen frequently
|
||||
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
@@ -191,7 +191,7 @@ public class EventLoopTest : XCTestCase {
|
||||
|
||||
waitForExpectations(timeout: 1) { error in
|
||||
XCTAssertNil(error)
|
||||
XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= initialDelay.nanoseconds)
|
||||
XCTAssertTrue(NIODeadline.now() - nanos >= initialDelay)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,23 +530,23 @@ public class EventLoopTest : XCTestCase {
|
||||
}
|
||||
|
||||
public func testScheduleMultipleTasks() throws {
|
||||
let nanos = DispatchTime.now().uptimeNanoseconds
|
||||
let nanos: NIODeadline = .now()
|
||||
let amount: TimeAmount = .seconds(1)
|
||||
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
|
||||
}
|
||||
var array = Array<(Int, DispatchTime)>()
|
||||
var array = Array<(Int, NIODeadline)>()
|
||||
let scheduled1 = eventLoopGroup.next().scheduleTask(in: .milliseconds(500)) {
|
||||
array.append((1, DispatchTime.now()))
|
||||
array.append((1, .now()))
|
||||
}
|
||||
|
||||
let scheduled2 = eventLoopGroup.next().scheduleTask(in: .milliseconds(100)) {
|
||||
array.append((2, DispatchTime.now()))
|
||||
array.append((2, .now()))
|
||||
}
|
||||
|
||||
let scheduled3 = eventLoopGroup.next().scheduleTask(in: .milliseconds(1000)) {
|
||||
array.append((3, DispatchTime.now()))
|
||||
array.append((3, .now()))
|
||||
}
|
||||
|
||||
var result = try eventLoopGroup.next().scheduleTask(in: .milliseconds(1000)) {
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import XCTest
|
||||
@testable import NIO
|
||||
import Dispatch
|
||||
import NIOConcurrencyHelpers
|
||||
|
||||
private extension Array {
|
||||
|
||||
@@ -12,9 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Dispatch
|
||||
import XCTest
|
||||
|
||||
@testable import NIO
|
||||
|
||||
func withPipe(_ body: (NIO.FileHandle, NIO.FileHandle) -> [NIO.FileHandle]) throws {
|
||||
@@ -224,12 +222,12 @@ func resolverDebugInformation(eventLoop: EventLoop, host: String, previouslyRece
|
||||
|
||||
func assert(_ condition: @autoclosure () -> Bool, within time: TimeAmount, testInterval: TimeAmount? = nil, _ message: String = "condition not satisfied in time", file: StaticString = #file, line: UInt = #line) {
|
||||
let testInterval = testInterval ?? TimeAmount.nanoseconds(time.nanoseconds / 5)
|
||||
let endTime = DispatchTime.now().uptimeNanoseconds + UInt64(time.nanoseconds)
|
||||
let endTime = NIODeadline.now() + time
|
||||
|
||||
repeat {
|
||||
if condition() { return }
|
||||
usleep(UInt32(testInterval.nanoseconds / 1000))
|
||||
} while (DispatchTime.now().uptimeNanoseconds < endTime)
|
||||
} while (NIODeadline.now() < endTime)
|
||||
|
||||
if !condition() {
|
||||
XCTFail(message)
|
||||
|
||||
Reference in new issue
Block a user