Skip to content
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

Lint all code #179

Merged
merged 1 commit into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions Sources/Auth/Login/LoginRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class LoginRepository {
private let tokensStore: TokensStore
private let exponentialBackoffPolicy: RetryPolicy
private let logger: TidalLogger?

private var codeVerifier: String?

init(
Expand Down Expand Up @@ -74,7 +74,7 @@ final class LoginRepository {
case let .success(successData):
try saveTokens(response: successData)
case let .failure(error):
self.logger?.log(loggable: AuthLoggable.finalizeLoginNetworkError(error: error))
logger?.log(loggable: AuthLoggable.finalizeLoginNetworkError(error: error))
}

return response
Expand Down Expand Up @@ -113,9 +113,9 @@ final class LoginRepository {
deviceLoginPollHelper.prepareForPoll(interval: response.interval, maxDuration: response.expiresIn)
return response
}

if case let .failure(error) = result {
self.logger?.log(loggable: AuthLoggable.initializeDeviceLoginNetworkError(error: error))
logger?.log(loggable: AuthLoggable.initializeDeviceLoginNetworkError(error: error))
}

return result
Expand All @@ -133,8 +133,9 @@ final class LoginRepository {
case let .success(successData):
try saveTokens(response: successData)
case let .failure(error):
let loggable = error.subStatus?.description.isSubStatus(status: .expiredAccessToken) == true ? AuthLoggable.finalizeDevicePollingLimitReached : AuthLoggable.finalizeDeviceLoginNetworkError(error: error)
self.logger?.log(loggable: loggable)
let loggable = error.subStatus?.description.isSubStatus(status: .expiredAccessToken) == true ? AuthLoggable
.finalizeDevicePollingLimitReached : AuthLoggable.finalizeDeviceLoginNetworkError(error: error)
logger?.log(loggable: loggable)
}

return response
Expand Down
20 changes: 10 additions & 10 deletions Sources/Auth/Model/AuthLoggable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,25 +63,25 @@ extension AuthLoggable {

switch self {
case let .initializeDeviceLoginNetworkError(error),
let .finalizeLoginNetworkError(error),
let .finalizeDeviceLoginNetworkError(error),
let .getCredentialsUpgradeTokenNetworkError(error),
let .loadTokensFromStoreError(error):
let .finalizeLoginNetworkError(error),
let .finalizeDeviceLoginNetworkError(error),
let .getCredentialsUpgradeTokenNetworkError(error),
let .loadTokensFromStoreError(error):
metadata[Logger.Metadata.errorKey] = .string(.init(describing: error))
case let .getCredentialsRefreshTokenNetworkError(error, previousSubstatus),
let .getCredentialsRefreshTokenWithClientCredentialsNetworkError(error, previousSubstatus):
let .getCredentialsRefreshTokenWithClientCredentialsNetworkError(error, previousSubstatus):
metadata[Logger.Metadata.errorKey] = .string(.init(describing: error))
metadata[Self.metadataPreviousSubstatusKey] = "\(previousSubstatus ?? "nil")"
case let .authLogout(reason, error, previousSubstatus):
metadata[Logger.Metadata.reasonKey] = "\(reason)"
if let error = error {
if let error {
metadata[Logger.Metadata.errorKey] = .string(.init(describing: error))
}
metadata[Self.metadataPreviousSubstatusKey] = "\(previousSubstatus ?? "nil")"
default:
break
}

metadata[Logger.Metadata.codeKey] = .string(eventCode)

return metadata
Expand All @@ -95,11 +95,11 @@ extension AuthLoggable {
.error
}
}

var source: String? {
"Auth"
}

private var eventCode: String {
let intCode = switch self {
case .initializeDeviceLoginNetworkError:
Expand Down Expand Up @@ -129,7 +129,7 @@ extension AuthLoggable {
case .loadTokensFromStoreError:
13
}

return intCode.description
}
}
16 changes: 9 additions & 7 deletions Sources/Auth/TidalAuth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,20 @@ public class TidalAuth: Auth & CredentialsProvider {
) {
self.config = config

let tokensStore = DefaultTokensStore(credentialsKey: config.credentialsKey, credentialsAccessGroup: config.credentialsAccessGroup)
let tokensStore = DefaultTokensStore(
credentialsKey: config.credentialsKey,
credentialsAccessGroup: config.credentialsAccessGroup
)

let authLogger: TidalLogger?
if config.enableLogging {
authLogger = TidalLogger(label: "Auth", level: .trace)
let authLogger: TidalLogger? = if config.enableLogging {
TidalLogger(label: "Auth", level: .trace)
} else {
authLogger = nil
nil
}
loginRepository = provideLoginRepository(config, tokensStore: tokensStore, logger: authLogger)
tokenRepository = provideTokenRepository(config, tokensStore: tokensStore, logger: authLogger)
}

private func provideLoginRepository(_ config: AuthConfig, tokensStore: TokensStore, logger: TidalLogger?) -> LoginRepository {
LoginRepository(
authConfig: config,
Expand All @@ -48,7 +50,7 @@ public class TidalAuth: Auth & CredentialsProvider {
tokensStore: tokensStore,
tokenService: DefaultTokenService(authBaseUrl: config.tidalAuthServiceBaseUri),
defaultBackoffPolicy: DefaultRetryPolicy(),
upgradeBackoffPolicy: DefaultRetryPolicy(),
upgradeBackoffPolicy: DefaultRetryPolicy(),
logger: logger
)
}
Expand Down
15 changes: 9 additions & 6 deletions Sources/Auth/TokenRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ struct TokenRepository {
) }
} else if let clientSecret = authConfig.clientSecret {
// if nothing is stored, we will try and refresh using a client secret
self.logger?.log(loggable: AuthLoggable.getCredentialsRefreshTokenIsNotAvailable)
logger?.log(loggable: AuthLoggable.getCredentialsRefreshTokenIsNotAvailable)

refreshCredentialsBlock = { await getClientAccessToken(clientSecret: clientSecret) }
networkErrorLoggableBlock = { AuthLoggable.getCredentialsRefreshTokenWithClientCredentialsNetworkError(
Expand All @@ -110,20 +110,23 @@ struct TokenRepository {
switch (authResult, networkErrorLoggableBlock) {
case let (.failure(error), _) where shouldLogoutWithLowerLevelTokenAfterUpdate(error: error):
if let loggable = logoutAfterErrorLoggableBlock?(error) {
self.logger?.log(loggable: loggable)
logger?.log(loggable: loggable)
}
return .success(.init(authConfig: authConfig))

case let (.failure(error), .some(networkErrorLoggableBlock)):
self.logger?.log(loggable: networkErrorLoggableBlock(error))
logger?.log(loggable: networkErrorLoggableBlock(error))

default: break
}

return authResult
}

self.logger?.log(loggable: AuthLoggable.authLogout(reason: "No refresh token or client secret available", previousSubstatus: apiErrorSubStatus))
logger?.log(loggable: AuthLoggable.authLogout(
reason: "No refresh token or client secret available",
previousSubstatus: apiErrorSubStatus
))
return logout()
}

Expand Down Expand Up @@ -162,10 +165,10 @@ struct TokenRepository {
switch result {
case let .success(tokens):
if tokens.credentials.token == nil {
self.logger?.log(loggable: AuthLoggable.getCredentialsUpgradeTokenNoTokenInResponse)
logger?.log(loggable: AuthLoggable.getCredentialsUpgradeTokenNoTokenInResponse)
}
case let .failure(error):
self.logger?.log(loggable: AuthLoggable.getCredentialsUpgradeTokenNetworkError(error: error))
logger?.log(loggable: AuthLoggable.getCredentialsUpgradeTokenNetworkError(error: error))
}

return result
Expand Down
2 changes: 1 addition & 1 deletion Sources/Common/Logger/LoggerMetadata+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public extension Logger.Metadata {
init(stringDict: [String: String]) {
self = stringDict.mapValues { .string($0) }
}

// Common keys that can be used in metadata for the sake of consistency
static let errorKey = "error"
static let codeKey = "code"
Expand Down
9 changes: 5 additions & 4 deletions Sources/Common/Logger/TidalLoggable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import Logging
public protocol TidalLoggable {
/// Message you want to log
var loggingMessage: Logger.Message { get }

/// Additional information attached to a log message
var loggingMetadata: Logger.Metadata { get }

/// Level of a log message
var logLevel: Logger.Level { get }

/// The origin of a log message. If you don't provide it, it will be set automatically to the name of a calling module, which might not be intended

/// The origin of a log message. If you don't provide it, it will be set automatically to the name of a calling module, which
/// might not be intended
var source: String? { get }
}
29 changes: 20 additions & 9 deletions Sources/Common/Logger/TidalLogger.swift
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
import Logging

// MARK: - TidalLogger

/// Struct abstraction for a logger offering a convenient API for logging.
public struct TidalLogger {
private var logger: Logger

public init(label: String, level: Logger.Level = .trace) {
self.logger = Logger(label: label)
self.logger.logLevel = level
logger = Logger(label: label)
logger.logLevel = level
}
}

private extension TidalLogger {
func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata? = nil, source: String? = nil, file: String, function: String, line: UInt) {
self.logger.log(level: level, message, metadata: metadata, source: source, file: file, function: function, line: line)
func log(
level: Logger.Level,
message: Logger.Message,
metadata: Logger.Metadata? = nil,
source: String? = nil,
file: String,
function: String,
line: UInt
) {
logger.log(level: level, message, metadata: metadata, source: source, file: file, function: function, line: line)
}
}

public extension TidalLogger {
func log(loggable: TidalLoggable, file: String = #fileID, function: String = #function, line: UInt = #line) {
self.log(
log(
level: loggable.logLevel,
message: loggable.loggingMessage,
metadata: loggable.loggingMetadata,
Expand All @@ -28,11 +38,12 @@ public extension TidalLogger {
line: line
)
}

/// Logs a string message
/// - Parameters:
/// - message: Message you want to log
/// - source: The origin of a log message. If you don't provide it, it will be set automatically to the name of a calling module, which might not be intended
/// - source: The origin of a log message. If you don't provide it, it will be set automatically to the name of a calling
/// module, which might not be intended
/// - level: Level of a log message
/// - metadata: Additional information attached to a log message
/// - file: The file this log message originates from (there's usually no need to pass it explicitly as it
Expand All @@ -52,8 +63,8 @@ public extension TidalLogger {
) {
let level = level ?? logger.logLevel
let loggerMessage = Logger.Message(stringLiteral: message)
self.log(

log(
level: level,
message: loggerMessage,
metadata: metadata,
Expand Down
5 changes: 3 additions & 2 deletions Sources/EventProducer/TidalEventSender.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ public final class TidalEventSender: EventSender {
)
endOutage(eventName: event.name)
}

/// Used to explicitly send all events directly from the scheduler. Usage would depend on the client (ex. when app moves to the background)

/// Used to explicitly send all events directly from the scheduler. Usage would depend on the client (ex. when app moves to the
/// background)
public func sendAllEvents() async throws {
let headerHelper = HeaderHelper(credentialsProvider: config?.credentialsProvider)
do {
Expand Down
2 changes: 1 addition & 1 deletion Sources/Player/Common/Data/AudioCodec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public enum AudioCodec: Equatable, Codable {
}
switch mode {
// We can't know the exact codec, but the client does not need it.
case AudioMode.DOLBY_ATMOS, AudioMode.SONY_360RA:
case AudioMode.DOLBY_ATMOS, AudioMode.SONY_360RA:
PlayerWorld.logger?.log(loggable: PlayerLoggable.audioCodecInitWithLowQualityAndUnsupportedMode(mode: mode.rawValue))
return nil
case AudioMode.STEREO: self = .HE_AAC_V1
Expand Down
3 changes: 2 additions & 1 deletion Sources/Player/Common/Event/PlayerListener.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ public protocol PlayerListener: AnyObject {

func djSessionTransitioned(to transition: DJSessionTransition)

/// Called when the media services were reset. A chance for the client of the player to respond appropriately to mediaServicesWereResetNotification. More info about this issue:
/// Called when the media services were reset. A chance for the client of the player to respond appropriately to
/// mediaServicesWereResetNotification. More info about this issue:
/// https://developer.apple.com/documentation/avfaudio/avaudiosession/1616540-mediaserviceswereresetnotificati
/// - Important: This is a good time to set up the audio session again.
func mediaServicesWereReset()
Expand Down
5 changes: 4 additions & 1 deletion Sources/Player/Common/HttpClient/ResponseHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ final class ResponseHandler {
PlayerWorld.logger?.log(loggable: PlayerLoggable.backoffHandleResponseFailed(error: error, retryStrategy: "NONE"))
throw error
case let .BACKOFF(duration):
PlayerWorld.logger?.log(loggable: PlayerLoggable.backoffHandleResponseFailed(error: error, retryStrategy: "BACKOFF(duration: \(duration))"))
PlayerWorld.logger?.log(loggable: PlayerLoggable.backoffHandleResponseFailed(
error: error,
retryStrategy: "BACKOFF(duration: \(duration))"
))
try await Task.sleep(seconds: duration)
return try await execute(attemptCount: attemptCount + 1)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ public final class PlayerListenerMock: PlayerListener {
public func djSessionEnded(with reason: DJSessionEndReason) {}

public func djSessionTransitioned(to transition: DJSessionTransition) {}

public func mediaServicesWereReset() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ private extension AVQueuePlayerWrapperLegacy {
onStall: stalled,
onCompletelyDownloaded: downloaded,
onReadyToPlayToPlay: loaded,
onItemPlayedToEnd: playedToEnd,
onItemPlayedToEnd: playedToEnd,
onDjSessionTransition: receivedDjSessionTransition
)
}
Expand Down Expand Up @@ -566,7 +566,7 @@ private extension AVQueuePlayerWrapperLegacy {

func playedToEnd(playerItem: AVPlayerItem) {
if featureFlagProvider.shouldNotPerformActionAtItemEnd() {
self.player.remove(playerItem)
player.remove(playerItem)
}
}
}
Expand Down Expand Up @@ -606,14 +606,14 @@ private extension AVQueuePlayerWrapperLegacy {
// If it's the error related to the media services being reset, we create a specific internal error instead of a generic one.
// This is because the media services being reset is a recoverable error that should be handled differently.
if nserror.domain == ErrorConstants.avfoundationErrorDomain,
nserror.code == ErrorConstants.averrorMediaServicesWereResetErrorCode
nserror.code == ErrorConstants.averrorMediaServicesWereResetErrorCode
{
return PlayerInternalError(
errorId: .PERetryable,
errorType: .mediaServicesWereReset,
code: nserror.code,
description: description
)
errorType: .mediaServicesWereReset,
code: nserror.code,
description: description
)
} else {
return (error as? AVError).map {
PlayerInternalError(
Expand Down
Loading
Loading