Skip to content

Commit

Permalink
convert TimeAmount to Duration
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuawright11 committed Jul 27, 2024
1 parent 2a0c2a5 commit e3e1861
Show file tree
Hide file tree
Showing 17 changed files with 25 additions and 43 deletions.
2 changes: 1 addition & 1 deletion Alchemy/Cache/Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public final class Cache: IdentifiedService {
/// - Parameter value: The value to set.
/// - Parameter time: How long the cache record should live.
/// Defaults to nil, indicating the record has no expiry.
public func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: TimeAmount? = nil) async throws {
public func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: Duration? = nil) async throws {
try await provider.set(key, value: value, for: time)
}

Expand Down
2 changes: 1 addition & 1 deletion Alchemy/Cache/Providers/CacheProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public protocol CacheProvider {
/// - Parameter value: The value to set.
/// - Parameter time: How long the cache record should live.
/// Defaults to nil, indicating the record has no expiry.
func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: TimeAmount?) async throws
func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: Duration?) async throws

/// Determine if a record for the given key exists.
///
Expand Down
2 changes: 1 addition & 1 deletion Alchemy/Cache/Providers/DatabaseCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ final class DatabaseCache: CacheProvider {
try await getItem(key: key)?.cast()
}

func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: TimeAmount?) async throws {
func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: Duration?) async throws {
let item = try await getItem(key: key)
let expiration = time.map { Date().adding(time: $0) }
if var item = item {
Expand Down
2 changes: 1 addition & 1 deletion Alchemy/Cache/Providers/MemoryCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public final class MemoryCache: CacheProvider {
try getItem(key)?.cast()
}

public func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: TimeAmount?) {
public func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: Duration?) {
data[key] = MemoryCacheItem(value: value.description, expiration: time.map { Date().adding(time: $0) })
}

Expand Down
2 changes: 1 addition & 1 deletion Alchemy/Cache/Providers/RedisCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ final class RedisCache: CacheProvider {
return value
}

func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: TimeAmount?) async throws {
func set<L: LosslessStringConvertible>(_ key: String, value: L, for time: Duration?) async throws {
if let time = time {
_ = try await redis.transaction { conn in
try await conn.set(RedisKey(key), to: value.description).get()
Expand Down
4 changes: 2 additions & 2 deletions Alchemy/Database/Rune/Model/SoftDeletes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,11 @@ extension Array where Element: Model & SoftDeletes {
}

public func forceDeleteAll(on db: Database = Element.database) async throws {
try await Element.willDelete(self)
Element.willDelete(self)
try await db.table(Element.self)
.where("id", in: map(\.id))
.forceDelete()
try await Element.didDelete(self)
Element.didDelete(self)
}
}

Expand Down
1 change: 0 additions & 1 deletion Alchemy/Exports.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,3 @@
@_exported import struct NIO.ByteBuffer
@_exported import protocol NIO.EventLoop
@_exported import protocol NIO.EventLoopGroup
@_exported import struct NIO.TimeAmount
2 changes: 1 addition & 1 deletion Alchemy/Filesystem/File.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public struct File: Codable, ResponseConvertible, ModelProperty {
}

/// Get a temporary url for this resource.
public func temporaryUrl(expires: TimeAmount, headers: HTTPFields = [:]) async throws -> URL {
public func temporaryUrl(expires: Duration, headers: HTTPFields = [:]) async throws -> URL {
switch source {
case .filesystem(let filesystem, let path):
return try await (filesystem ?? Storage).temporaryURL(path, expires: expires, headers: headers)
Expand Down
2 changes: 1 addition & 1 deletion Alchemy/Filesystem/Filesystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public final class Filesystem: IdentifiedService {
return try await create(directoryUrl.appendingPathComponent(name).path, content: content)
}

public func temporaryURL(_ filepath: String, expires: TimeAmount, headers: HTTPFields = [:]) async throws -> URL {
public func temporaryURL(_ filepath: String, expires: Duration, headers: HTTPFields = [:]) async throws -> URL {
try await provider.temporaryURL(filepath, expires: expires, headers: headers)
}

Expand Down
2 changes: 1 addition & 1 deletion Alchemy/Filesystem/FilesystemProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public protocol FilesystemProvider {
func delete(_ filepath: String) async throws

/// Create a temporary URL to a file at the given path.
func temporaryURL(_ filepath: String, expires: TimeAmount, headers: HTTPFields) async throws -> URL
func temporaryURL(_ filepath: String, expires: Duration, headers: HTTPFields) async throws -> URL

/// Get a URL for the file at the given path.
func url(_ filepath: String) throws -> URL
Expand Down
2 changes: 1 addition & 1 deletion Alchemy/Filesystem/Providers/LocalFilesystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ private struct LocalFilesystem: FilesystemProvider {
return url
}

func temporaryURL(_ filepath: String, expires: TimeAmount, headers: HTTPFields = [:]) async throws -> URL {
func temporaryURL(_ filepath: String, expires: Duration, headers: HTTPFields = [:]) async throws -> URL {
throw FileError.temporaryUrlNotAvailable
}

Expand Down
8 changes: 4 additions & 4 deletions Alchemy/HTTP/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ public final class Client: IdentifiedService {
/// The path of this request.
public var path: String { urlComponents.path }
/// How long until this request times out.
public var timeout: TimeAmount? = nil
public var timeout: Duration? = nil
/// Whether to stream the response. If false, the response body will be
/// fully accumulated before returning.
public var streamResponse: Bool = false
/// Custom config override when making this request.
public var config: HTTPClient.Configuration? = nil

public init(url: String = "", method: HTTPRequest.Method = .get, headers: HTTPFields = [:], body: Bytes? = nil, timeout: TimeAmount? = nil) {
public init(url: String = "", method: HTTPRequest.Method = .get, headers: HTTPFields = [:], body: Bytes? = nil, timeout: Duration? = nil) {
self.urlComponents = URLComponents(string: url) ?? URLComponents()
self.method = method
self.headers = headers
Expand Down Expand Up @@ -169,7 +169,7 @@ public final class Client: IdentifiedService {
}

/// Timeout if the request doesn't finish in the given time amount.
public func withTimeout(_ timeout: TimeAmount) -> Builder {
public func withTimeout(_ timeout: Duration) -> Builder {
with { $0.clientRequest.timeout = timeout }
}

Expand Down Expand Up @@ -294,7 +294,7 @@ public final class Client: IdentifiedService {
if let stubs = stubs {
return stubs.response(for: req)
} else {
let deadline: NIODeadline? = req.timeout.map { .now() + $0 }
let deadline: NIODeadline? = req.timeout.map { .now() + .seconds(Int64($0.seconds)) }
let httpClientOverride = req.config.map { HTTPClient(eventLoopGroupProvider: .shared(httpClient.eventLoopGroup), configuration: $0) }

do {
Expand Down
4 changes: 2 additions & 2 deletions Alchemy/Queue/Job.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public protocol Job {

/// The time that should be waited before retrying this job if it fails.
/// Sub-second precision is ignored. Defaults to 0.
var retryBackoff: TimeAmount { get }
var retryBackoff: Duration { get }

// MARK: Handling

Expand Down Expand Up @@ -91,7 +91,7 @@ public struct JobContext {
extension Job {
public static var name: String { "\(Self.self)" }
public var recoveryStrategy: RecoveryStrategy { .none }
public var retryBackoff: TimeAmount { .zero }
public var retryBackoff: Duration { .zero }

public func finished(result: Result<Void, Error>) {
switch result {
Expand Down
15 changes: 2 additions & 13 deletions Alchemy/Queue/JobData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public struct JobData: Codable, Equatable {
public let recoveryStrategy: Job.RecoveryStrategy
/// How long should be waited before retrying a Job after a
/// failure.
public let backoff: TimeAmount
public let backoff: Duration
/// Don't run this again until this time.
public var backoffUntil: Date?
/// The number of attempts this Job has been attempted.
Expand Down Expand Up @@ -55,7 +55,7 @@ public struct JobData: Codable, Equatable {
channel: String,
attempts: Int = 0,
recoveryStrategy: Job.RecoveryStrategy,
backoff: TimeAmount,
backoff: Duration,
backoffUntil: Date? = nil
) {
self.id = id
Expand All @@ -68,14 +68,3 @@ public struct JobData: Codable, Equatable {
self.attempts = attempts
}
}

extension TimeAmount: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(nanoseconds)
}

public init(from decoder: Decoder) throws {
self = .nanoseconds(try decoder.singleValueContainer().decode(Int64.self))
}
}
6 changes: 0 additions & 6 deletions Alchemy/Scheduler/Scheduler.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
import AsyncAlgorithms
import NIOCore
import NIOConcurrencyHelpers
import Foundation
import ServiceLifecycle

/// A service for scheduling recurring work, in lieu of a separate cron task
/// running apart from your server.
public final class Scheduler {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import Foundation

extension TimeAmount {
extension Duration {
/// This time amount in seconds.
var seconds: Int {
Int(self.nanoseconds / 1000000000)
Int(components.seconds)
}
}

Expand All @@ -12,7 +12,7 @@ extension Date {
///
/// - Parameter time: The time amount to add.
/// - Returns: The epoch seconds from adding `time` to this date.
func adding(time: TimeAmount) -> Int {
Int(self.timeIntervalSince1970) + time.seconds
func adding(time: Duration) -> Int {
Int(timeIntervalSince1970) + time.seconds
}
}
4 changes: 2 additions & 2 deletions Tests/Queues/QueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ private struct RetryJob: Job, Codable {

let foo: String
var recoveryStrategy: RecoveryStrategy = .retry(3)
var retryBackoff: TimeAmount = .seconds(0)
var retryBackoff: Duration = .seconds(0)

func handle(context: JobContext) async throws {
throw JobError(foo)
}
Expand Down

0 comments on commit e3e1861

Please sign in to comment.