Skip to content

Commit

Permalink
chore: resolve swiftlint errors and warnings for Analytics plugin (#3445
Browse files Browse the repository at this point in the history
)

* chore: resolve swiftlint errors

* chore: resolve swiftlint warnings

* chore: resolve swiftlint warnings

* chore: resolve swiftlint errors and warnings

* chore: resolve swiftlint errors and warnings

* chore: resolve swiftlint errors and warnings

* chore: resolve swiftlint errors and warnings
  • Loading branch information
phantumcode authored Jan 3, 2024
1 parent c980aa7 commit bf374b7
Show file tree
Hide file tree
Showing 24 changed files with 58 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ extension AWSPinpointAnalyticsPlugin {
globalProperties.removeAll()
return
}

for key in keys {
if let value = globalProperties[key] {
await pinpoint.removeGlobalProperty(value, forKey: key)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ extension AWSPinpointAnalyticsPlugin {
appId: configuration.appId,
region: configuration.region
)

let interval = TimeInterval(configuration.autoFlushEventsInterval)
pinpoint.setAutomaticSubmitEventsInterval(interval) { result in
switch result {
Expand All @@ -47,18 +47,18 @@ extension AWSPinpointAnalyticsPlugin {
Amplify.Hub.dispatchFlushEvents(AnalyticsErrorHelper.getDefaultError(error))
}
}

if configuration.trackAppSessions {
let sessionBackgroundTimeout: TimeInterval
if configuration.autoSessionTrackingInterval == .max {
sessionBackgroundTimeout = .infinity
} else {
sessionBackgroundTimeout = TimeInterval(configuration.autoSessionTrackingInterval)
}

pinpoint.startTrackingSessions(backgroundTimeout: sessionBackgroundTimeout)
}

let networkMonitor = NWPathMonitor()
networkMonitor.startMonitoring(
using: DispatchQueue(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ extension AWSPinpointAnalyticsPlugin {
if isEnabled != nil {
isEnabled = nil
}

if networkMonitor != nil {
networkMonitor.stopMonitoring()
networkMonitor = nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public struct AWSPinpointAnalyticsPluginConfiguration {
let autoFlushEventsInterval: Int
let trackAppSessions: Bool
let autoSessionTrackingInterval: Int

private static let logger = Amplify.Logging.logger(forCategory: CategoryType.analytics.displayName, forNamespace: String(describing: Self.self))

init(_ configuration: JSONValue) throws {
Expand All @@ -52,13 +52,13 @@ public struct AWSPinpointAnalyticsPluginConfiguration {
AnalyticsPluginErrorConstant.missingPinpointAnalyicsConfiguration.recoverySuggestion
)
}

let pluginConfiguration = try AWSPinpointPluginConfiguration(pinpointAnalyticsConfig)

let autoFlushEventsInterval = try Self.getAutoFlushEventsInterval(configObject)
let trackAppSessions = try Self.getTrackAppSessions(configObject)
let autoSessionTrackingInterval = try Self.getAutoSessionTrackingInterval(configObject)

// Warn users in case they set different regions between pinpointTargeting and pinpointAnalytics
if let pinpointTargetingJson = configObject[Self.pinpointTargetingConfigKey],
let pinpointTargetingConfig = try? AWSPinpointPluginConfiguration(pinpointTargetingJson),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ extension NWPathMonitor: NetworkMonitor {
var isOnline: Bool {
currentPath.status == .satisfied
}

func startMonitoring(using queue: DispatchQueue) {
start(queue: queue)
}

func stopMonitoring() {
cancel()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,19 @@ public protocol AWSPinpointBehavior {
/// Records the specified `PinpointEvent` to the local storage.
/// - Parameter event: The `PinpointEvent` to persist
func record(_ event: PinpointEvent) async throws

/// Sets the interval for the automatic submission of event. If set to `TimeInterval.zero`,
/// the automatic submission is disabled
/// - Parameter interval: How much to wait between submissions
/// - Parameter onSubmit: An optional callback to be run after each submission happens
func setAutomaticSubmitEventsInterval(_ interval: TimeInterval,
onSubmit: AnalyticsClientBehaviour.SubmitResult?)

// MARK: Session
/// Beings automatically tracking session activity in the device.
/// - Parameter backgroundTimeout: How much to wait after the device goes to the background before stopping the session
func startTrackingSessions(backgroundTimeout: TimeInterval)

/// Submits all recorded events to Pinpoint.
/// Events are automatically submitted when the application goes into the background.
/// - Returns: An array of successfully submitted events.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,20 @@ actor AnalyticsClient: AnalyticsClientBehaviour {
self.eventRecorder = eventRecorder
self.sessionProvider = sessionProvider
}

// Actors no longer use 'convenience' for inits. This is a warning in swift 5.7 and an error in swift 6+.
// However, 'convenience' is required to build with swift <5.7
#if swift(>=5.7)
init(applicationId: String,
pinpointClient: PinpointClientProtocol,
endpointClient: EndpointClientBehaviour,
sessionProvider: @escaping SessionProvider) throws
{
sessionProvider: @escaping SessionProvider) throws {
let dbAdapter = try SQLiteLocalStorageAdapter(prefixPath: Constants.eventRecorderStoragePathPrefix,
databaseName: applicationId)
let eventRecorder = try EventRecorder(appId: applicationId,
storage: AnalyticsEventSQLStorage(dbAdapter: dbAdapter),
pinpointClient: pinpointClient, endpointClient: endpointClient)

self.init(eventRecorder: eventRecorder, sessionProvider: sessionProvider)
}
#else
Expand All @@ -98,11 +97,11 @@ actor AnalyticsClient: AnalyticsClientBehaviour {
let eventRecorder = try EventRecorder(appId: applicationId,
storage: AnalyticsEventSQLStorage(dbAdapter: dbAdapter),
pinpointClient: pinpointClient, endpointClient: endpointClient)

self.init(eventRecorder: eventRecorder, sessionProvider: sessionProvider)
}
#endif

nonisolated var pinpointClient: PinpointClientProtocol {
return eventRecorder.pinpointClient
}
Expand Down Expand Up @@ -278,7 +277,7 @@ actor AnalyticsClient: AnalyticsClientBehaviour {
automaticSubmitEventsTimer = nil
return
}

log.info("Enabling Automatic Submission of Events after \(interval) seconds.")
automaticSubmitEventsTimer = RepeatingTimer.createRepeatingTimer(
timeInterval: automaticSubmitEventsInterval,
Expand All @@ -302,7 +301,7 @@ extension AnalyticsClient: DefaultLogger {
public static var log: Logger {
Amplify.Logging.logger(forCategory: CategoryType.analytics.displayName, forNamespace: String(describing: self))
}

public nonisolated var log: Logger {
Self.log
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ actor EventRecorder: AnalyticsEventRecording {
_ = try? await submissionTask?.value
submittedEvents = []
let eventsBatch = try getBatchRecords()
if eventsBatch.count > 0 {
if eventsBatch.isEmpty {
log.verbose("No events to submit")
} else {
let endpointProfile = await endpointClient.currentEndpointProfile()
try await processBatch(eventsBatch, endpointProfile: endpointProfile)
} else {
log.verbose("No events to submit")
}
return submittedEvents
}
Expand All @@ -115,7 +115,7 @@ actor EventRecorder: AnalyticsEventRecording {
}
try storage.removeFailedEvents()
let nextEventsBatch = try getBatchRecords()
if nextEventsBatch.count > 0 {
if !nextEventsBatch.isEmpty {
try await processBatch(nextEventsBatch, endpointProfile: endpointProfile)
}
}
Expand Down Expand Up @@ -231,7 +231,7 @@ actor EventRecorder: AnalyticsEventRecording {
throw error
}
}

private func handleError(_ error: Error, for pinpointEvents: [PinpointEvent]) {
if isConnectivityError(error) {
// Connectivity errors should be retried indefinitely, so we won't update the database
Expand All @@ -256,7 +256,7 @@ actor EventRecorder: AnalyticsEventRecording {
}
return type(of: modeledError).isRetryable
}

private func errorDescription(_ error: Error) -> String {
if isConnectivityError(error) {
return AWSPinpointErrorConstants.deviceOffline.errorDescription
Expand All @@ -273,7 +273,7 @@ actor EventRecorder: AnalyticsEventRecording {
return error.localizedDescription
}
}

private func isConnectivityError(_ error: Error) -> Bool {
switch error {
case let error as CommonRunTimeError:
Expand All @@ -291,7 +291,7 @@ actor EventRecorder: AnalyticsEventRecording {
return false
}
}

private func deleteEvent(eventId: String) {
retry(onErrorMessage: "Unable to delete event with id \(eventId).") {
try storage.deleteEvent(eventId: eventId)
Expand All @@ -303,18 +303,17 @@ actor EventRecorder: AnalyticsEventRecording {
try storage.setDirtyEvent(eventId: eventId)
}
}

private func markEventsAsDirty(_ events: [PinpointEvent]) {
events.forEach { setDirtyEvent(eventId: $0.id) }
}


private func incrementEventRetry(eventId: String) {
retry(onErrorMessage: "Unable to update retry count for event with id \(eventId).") {
try storage.incrementEventRetry(eventId: eventId)
}
}

private func incrementRetryCounter(for events: [PinpointEvent]) {
events.forEach { incrementEventRetry(eventId: $0.id) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ extension PinpointEvent {
guard let eventId = element[EventPropertyIndex.id] as? String else {
return nil
}

var retryCount = 0
if let retryCountInt = element[EventPropertyIndex.retryCount] as? Int64 {
retryCount = Int(retryCountInt)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ extension SQLiteLocalStorageAdapter: DefaultLogger {
public static var log: Logger {
Amplify.Logging.logger(forCategory: CategoryType.analytics.displayName, forNamespace: String(describing: self))
}

public var log: Logger {
Self.log
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ extension PinpointEvent: DefaultLogger {
public static var log: Logger {
Amplify.Logging.logger(forCategory: CategoryType.analytics.displayName, forNamespace: String(describing: self))
}

public var log: Logger {
Self.log
}
Expand All @@ -117,12 +117,12 @@ extension PinpointEvent: CustomStringConvertible {
"""
return string
}

private func string(from dictionary: AnalyticsProperties) -> String {
if dictionary.isEmpty {
return "[:]"
}

var string = ""
for (key, value) in dictionary.sorted(by: { $0.key < $1.key}) {
string += "\n\t\t\"\(key)\": \"\(value)\""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ public class AWSPinpointFactory {
let appId: String
let region: String
}

private static var instances: AtomicDictionary<PinpointContextKey, PinpointContext> = [:]

private init() {}

static var credentialsProvider = AWSAuthService().getCredentialsProvider()

static var provisioningProfileReader: ProvisioningProfileReader = .default

public static func sharedPinpoint(appId: String,
region: String) throws -> AWSPinpointBehavior {
let key = PinpointContextKey(appId: appId, region: region)
Expand All @@ -49,10 +49,9 @@ public class AWSPinpointFactory {
credentialsProvider: credentialsProvider,
isDebug: isDebug
)

let pinpointContext = try PinpointContext(with: configuration)
instances[key] = pinpointContext
return pinpointContext
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ extension PinpointContext: AWSPinpointBehavior {
await analyticsClient.removeGlobalMetric(forKey: forKey)
}
}

func addGlobalProperty(_ value: AnalyticsPropertyValue, forKey: String) async {
if let value = value as? String {
await analyticsClient.addGlobalAttribute(value, forKey: forKey)
Expand All @@ -57,17 +57,17 @@ extension PinpointContext: AWSPinpointBehavior {
}
}

func setRemoteGlobalAttributes(_ attributes: [String : String]) async {
func setRemoteGlobalAttributes(_ attributes: [String: String]) async {
await analyticsClient.setRemoteGlobalAttributes(attributes)
}

func setAutomaticSubmitEventsInterval(_ interval: TimeInterval,
onSubmit: AnalyticsClientBehaviour.SubmitResult?) {
Task {
await analyticsClient.setAutomaticSubmitEventsInterval(interval, onSubmit: onSubmit)
}
}

func startTrackingSessions(backgroundTimeout: TimeInterval) {
sessionClient.startTrackingSessions(backgroundTimeout: backgroundTimeout)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ extension FileManager: FileManagerBehaviour, DefaultLogger {
public var log: Logger {
Self.log
}

func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool) throws {
try createDirectory(atPath: path,
withIntermediateDirectories: createIntermediates,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ actor EndpointClient: EndpointClientBehaviour {
log.error("Unable to migrate Analytics key-value store for key \(Constants.endpointProfileKey)")
}
}

let keychainTokenData = try? keychain._getData(Constants.deviceTokenKey)
if let tokenData = userDefaults.data(forKey: Constants.deviceTokenKey), keychainTokenData == nil {
do {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ extension Data {
.map { String(chars[$0]) + String(chars[$0 + 1]) }
.compactMap { UInt8($0, radix: 16) }

guard bytes.count > 0, hexString.count / bytes.count == 2 else {
guard !bytes.isEmpty, hexString.count / bytes.count == 2 else {
return nil
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ extension PutEventsOutput: AmplifyStringConvertible {
enum CodingKeys: Swift.String, Swift.CodingKey {
case eventsResponse = "EventsResponse"
}

public func encode(to encoder: Encoder) throws {
var encodeContainer = encoder.container(keyedBy: CodingKeys.self)
if let eventsResponse = self.eventsResponse {
Expand Down
Loading

0 comments on commit bf374b7

Please sign in to comment.