Skip to content

Commit

Permalink
Merge pull request #113 from UbiqueInnovation/bugfix/disable-slow-macros
Browse files Browse the repository at this point in the history
replace macros by logger file
  • Loading branch information
stmitt authored Nov 29, 2024
2 parents d412160 + 243aea7 commit 7edaf15
Show file tree
Hide file tree
Showing 20 changed files with 126 additions and 299 deletions.
8 changes: 0 additions & 8 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ let package = Package(
targets: [
.target(
name: "UBFoundation",
dependencies: ["UBMacros"],
swiftSettings: [
.swiftLanguageMode(.v6),
]
Expand Down Expand Up @@ -67,13 +66,6 @@ let package = Package(
.swiftLanguageMode(.v6),
]
),
.macro(name: "UBMacros", dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
],
swiftSettings: [
.swiftLanguageMode(.v6),
]),
.testTarget(name: "UBFoundationTests",
dependencies: ["UBFoundation", .product(name: "UBLocalNetworking", package: "ios-local-networking")],
resources: [
Expand Down
2 changes: 1 addition & 1 deletion Sources/UBFoundation/Cron/CronJob.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public final class UBCronJob: Sendable {
/// The state of the Job
public private(set) nonisolated(unsafe) var state: State = .initial {
willSet {
#assert(state != newValue)
assert(state != newValue)
}
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/UBFoundation/Cron/CronRule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public struct UBFireAtIntervalRule: UBCronRule {
/// - isRepeating: If the job should keep repeat afterwards
/// - tolerence: The accepted tolerence with the firing date
public init(_ interval: TimeInterval, repeat isRepeating: Bool = false, tolerence: DispatchTimeInterval? = nil) {
#assert((isRepeating && interval > 0) || !isRepeating)
assert((isRepeating && interval > 0) || !isRepeating)
repeatRule = isRepeating ? .after(interval.dispatchTimeInterval) : .never
self.tolerence = tolerence
self.interval = interval
Expand Down
11 changes: 0 additions & 11 deletions Sources/UBFoundation/Helpers/URL+Macro.swift

This file was deleted.

79 changes: 79 additions & 0 deletions Sources/UBFoundation/Logging/Logger.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//
// Logger.swift
// UBKit
//
// Created by Nicolas Märki on 12.09.2024.
//

// LOGGER TEMPLATE FILE
// Copy this file to your project, replace subsystem and category with your own values
// Copying ensures that methods shadow Swift originals

import Foundation
import os

public let Log = os.Logger(subsystem: "UBKit", category: "Default")

public extension Logger {
func reportError(
_ message: String, file: StaticString = #file, line: UInt = #line
) {
UBNonFatalErrorReporter.shared
.report(
NSError(
domain: (file.description as NSString).lastPathComponent,
code: Int(line),
userInfo: [NSDebugDescriptionErrorKey: message]
)
)
Log.error("\(message)")
}

func reportCritical(
_ message: String, file: StaticString = #file, line: UInt = #line
) {
UBNonFatalErrorReporter.shared
.report(
NSError(
domain: (file.description as NSString).lastPathComponent,
code: Int(line),
userInfo: [NSDebugDescriptionErrorKey: message]
)
)
Log.critical("\(message)")
}
}

@available(*, deprecated, message: "Use Logger instead", renamed: "Log.debug")
public func print(
_ items: Any..., separator: String = " ", terminator: String = "\n"
) {
Log.debug("(\(items.map { "\($0)" }.joined(separator: separator)))")
}

public func assert(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
swiftAssertionFailure: Bool = true,
file: StaticString = #file,
line: UInt = #line
) {
if !condition() {
Log.reportCritical(message(), file: file, line: line)
if swiftAssertionFailure {
Swift.assertionFailure()
}
}
}

public func assertionFailure(
_ message: @autoclosure () -> String = String(),
swiftAssertionFailure: Bool = true,
file: StaticString = #file,
line: UInt = #line
) {
Log.reportCritical("Assertion failed: \(message())")
if swiftAssertionFailure {
Swift.assertionFailure(message(), file: file, line: line)
}
}
46 changes: 0 additions & 46 deletions Sources/UBFoundation/Logging/PrintMacros+Implementation.swift

This file was deleted.

58 changes: 0 additions & 58 deletions Sources/UBFoundation/Logging/PrintMacros.swift

This file was deleted.

2 changes: 1 addition & 1 deletion Sources/UBFoundation/Logging/UBNonFatalErrorReporter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public actor UBNonFatalErrorReporter {
self.handler = handler
}

nonisolated func report(_ error: Error) {
public nonisolated func report(_ error: Error) {
Task {
await _report(error)
}
Expand Down
12 changes: 4 additions & 8 deletions Sources/UBFoundation/Networking/AutoRefreshCacheLogic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@
import Foundation
import OSLog

private enum Log {
static let logger = Logger(subsystem: "UBKit", category: "AutoRefreshCacheLogic")
}

/// A caching logic that will launch and refresh the data automatically when the data expires
open class UBAutoRefreshCacheLogic: UBBaseCachingLogic, @unchecked Sendable {
/// The refresh cron jobs
Expand All @@ -31,18 +27,18 @@ open class UBAutoRefreshCacheLogic: UBBaseCachingLogic, @unchecked Sendable {
cancelRefreshCronJob(for: task)

guard let nextRefreshDate = cachedResponseNextRefreshDate(headers, metrics: metrics, referenceDate: referenceDate) else {
Log.logger.trace("No refresh date for task \(task)")
Log.trace("No refresh date for task \(task)")
return
}

Log.logger.trace("Schedule refresh for \(task) at \(nextRefreshDate) (\(round(nextRefreshDate.timeIntervalSinceNow))s)")
Log.trace("Schedule refresh for \(task) at \(nextRefreshDate) (\(round(nextRefreshDate.timeIntervalSinceNow))s)")

// Schedule a new job
let job = UBCronJob(fireAt: nextRefreshDate, qos: qos) { [weak task] in
if let task {
Log.logger.trace("Start cron refresh for task \(task)")
Log.trace("Start cron refresh for task \(task)")
} else {
Log.logger.trace("Not start cron refresh, task doesn't exist anymore.")
Log.trace("Not start cron refresh, task doesn't exist anymore.")
}
task?.start(flags: [.systemTriggered, .refresh])
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/UBFoundation/Networking/UBURLDataTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ public final class UBURLDataTask: UBURLSessionTask, CustomStringConvertible, Cus
break
default:
let errorMessage = "Invalid state transition from \(_state) -> \(newValue)"
#assertionFailure(errorMessage)
assertionFailure(errorMessage)
UBNonFatalErrorReporter.shared.report(NSError(domain: "UBURLDataTask", code: 0, userInfo: [NSLocalizedDescriptionKey: errorMessage]))
}
}
Expand Down
14 changes: 7 additions & 7 deletions Sources/UBFoundation/Networking/UBURLSession+Delegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ final class UBURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDa
/// :nodoc:
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
urlSessionQueue.sync {
#assert(session == self._urlSession, "The sessions are not matching")
assert(session == self._urlSession, "The sessions are not matching")
}

var _ubDataTask: UBURLDataTask?
Expand Down Expand Up @@ -162,7 +162,7 @@ final class UBURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDa
/// :nodoc:
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
urlSessionQueue.sync {
#assert(session == self._urlSession, "The sessions are not matching")
assert(session == self._urlSession, "The sessions are not matching")
}

var _collectedData: UBURLSessionDelegate.DataHolder?
Expand All @@ -179,7 +179,7 @@ final class UBURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDa
/// :nodoc:
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
urlSessionQueue.sync {
#assert(session == self._urlSession, "The sessions are not matching")
assert(session == self._urlSession, "The sessions are not matching")
}

var _ubDataTask: UBURLDataTask?
Expand Down Expand Up @@ -214,7 +214,7 @@ final class UBURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDa
/// :nodoc:
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
urlSessionQueue.sync {
#assert(session == self._urlSession, "The sessions are not matching")
assert(session == self._urlSession, "The sessions are not matching")
}

var _ubDataTask: UBURLDataTask?
Expand All @@ -237,7 +237,7 @@ final class UBURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDa
/// :nodoc:
func urlSession(_ session: URLSession, dataTask _: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
urlSessionQueue.sync {
#assert(session == self._urlSession, "The sessions are not matching")
assert(session == self._urlSession, "The sessions are not matching")
}
guard cachingLogic == nil else {
// If we have a caching logic, we will skip the default caching implementation
Expand All @@ -251,7 +251,7 @@ final class UBURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDa
/// :nodoc:
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
urlSessionQueue.sync {
#assert(session == self._urlSession, "The sessions are not matching")
assert(session == self._urlSession, "The sessions are not matching")
}

var _ubDataTask: UBURLDataTask?
Expand Down Expand Up @@ -283,7 +283,7 @@ final class UBURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDa
/// :nodoc:
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
urlSessionQueue.sync {
#assert(session == self._urlSession, "The sessions are not matching")
assert(session == self._urlSession, "The sessions are not matching")
}

var _ubDataTask: UBURLDataTask?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public final class UBPinnedCertificatesTrustEvaluator: UBServerTrustEvaluator {

/// :nodoc:
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
#assert(certificates.isEmpty == false, "This should not have happened as we make sure to crash if there are no certificates found during initialization.")
assert(certificates.isEmpty == false, "This should not have happened as we make sure to crash if there are no certificates found during initialization.")

if acceptSelfSignedCertificates {
try trust.setAnchorCertificates(certificates)
Expand Down
2 changes: 1 addition & 1 deletion Sources/UBLocation/UBLocationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ public class UBLocationManager: NSObject {

self.startLocationMonitoringForAllDelegates()

#assert(!delegateWrappers.isEmpty || allUsages == [])
assert(!delegateWrappers.isEmpty || allUsages == [])
}

/// Stops monitoring all location service events
Expand Down
19 changes: 0 additions & 19 deletions Sources/UBMacros/CustomError.swift

This file was deleted.

Loading

0 comments on commit 7edaf15

Please sign in to comment.