From fd216ed29663fd6e8cdabf1c2be178409cc126e3 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Wed, 20 Dec 2023 15:15:40 -0600 Subject: [PATCH 1/5] chore: resolve swiftlint errors --- .../Auth/AuthCategory+ClientBehavior.swift | 2 +- .../Auth/AuthCategoryBehavior.swift | 7 ++++- .../Model/Internal/ModelProvider.swift | 5 ++-- .../Schema/ModelField+Association.swift | 12 ++++++-- .../DataStore/Model/Lazy/LazyReference.swift | 4 +-- .../DataStore/Model/PropertyPath.swift | 4 +-- .../Model/Temporal/TimeZone+Extension.swift | 5 ++-- .../Categories/Logging/LoggingCategory.swift | 2 +- .../Notifications/NotificationsCategory.swift | 2 +- .../Predictions/Models/Language.swift | 2 ++ Amplify/Core/Support/Amplify+Publisher.swift | 9 +++--- .../AmplifyTask+OperationTaskAdapters.swift | 9 ++++-- Amplify/Core/Support/AmplifyTask.swift | 2 +- Amplify/DevMenu/Data/LogEntryHelper.swift | 3 +- .../Auth/AWSAuthSessionBehavior.swift | 28 +++++++++++-------- .../Provider/AuthAWSCredentialsProvider.swift | 2 +- .../AuthCognitoIdentityProvider.swift | 2 +- .../Keychain/KeychainStatus.swift | 5 +++- .../Keychain/KeychainStore.swift | 2 ++ .../Keychain/KeychainStoreError.swift | 4 ++- .../ConflictResolutionDecorator.swift | 6 ++-- 21 files changed, 74 insertions(+), 43 deletions(-) diff --git a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift index dfd92b9e92..cb707db8d7 100644 --- a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift @@ -63,7 +63,7 @@ extension AuthCategory: AuthCategoryBehavior { } public func resetPassword(for username: String, options: AuthResetPasswordRequest.Options? = nil) async throws -> AuthResetPasswordResult { - return try await plugin.resetPassword(for: username,options: options) + return try await plugin.resetPassword(for: username, options: options) } public func confirmResetPassword( diff --git a/Amplify/Categories/Auth/AuthCategoryBehavior.swift b/Amplify/Categories/Auth/AuthCategoryBehavior.swift index dd42213863..005eb965c5 100644 --- a/Amplify/Categories/Auth/AuthCategoryBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategoryBehavior.swift @@ -122,7 +122,12 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - newPassword: new password for the user /// - confirmationCode: Received confirmation code /// - options: Parameters specific to plugin behavior - func confirmResetPassword(for username: String, with newPassword: String, confirmationCode: String, options: AuthConfirmResetPasswordRequest.Options?) async throws + func confirmResetPassword( + for username: String, + with newPassword: String, + confirmationCode: String, + options: AuthConfirmResetPasswordRequest.Options? + ) async throws /// Initiates TOTP Setup /// diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift index 2f61c3c562..dca0c40c28 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift @@ -6,7 +6,7 @@ // import Foundation - +// swiftlint:disable type_name /// Protocol used as a marker to detect when the type is a `LazyReference`. /// Used to retrieve either the `reference` or the `identifiers` of the Model directly, without having load a not /// loaded LazyReference. This is useful when translating the model object over to the payload required for the @@ -18,13 +18,14 @@ import Foundation /// application making any change to these `public` types should be backward compatible, otherwise it will be a breaking /// change. public protocol _LazyReferenceValue { - var _state: _LazyReferenceValueState { get } + var _state: _LazyReferenceValueState { get } // swiftlint:disable:this identifier_name } public enum _LazyReferenceValueState { case notLoaded(identifiers: [LazyReferenceIdentifier]?) case loaded(model: Model?) } +// swiftlint:enable type_name /// State of the ModelProvider /// diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift index b3d85be2d5..6dfafe2c1b 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelField+Association.swift @@ -98,8 +98,14 @@ public enum ModelAssociation { return .belongsTo(associatedFieldName: nil, targetNames: targetNames) } - public static func hasMany(associatedWith: CodingKey? = nil, associatedFields: [CodingKey] = []) -> ModelAssociation { - return .hasMany(associatedFieldName: associatedWith?.stringValue, associatedFieldNames: associatedFields.map { $0.stringValue }) + public static func hasMany( + associatedWith: CodingKey? = nil, + associatedFields: [CodingKey] = [] + ) -> ModelAssociation { + return .hasMany( + associatedFieldName: associatedWith?.stringValue, + associatedFieldNames: associatedFields.map { $0.stringValue } + ) } @available(*, deprecated, message: "Use hasOne(associatedWith:targetNames:)") @@ -230,7 +236,7 @@ extension ModelField { /// directly by host applications. The behavior of this may change without warning. Though it is not used by host /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. - public var _isBelongsToOrHasOne: Bool { + public var _isBelongsToOrHasOne: Bool { // swiftlint:disable:this identifier_name switch association { case .belongsTo, .hasOne: return true diff --git a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift index 9799282fcd..c2625391a4 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift @@ -34,6 +34,7 @@ struct LazyReferenceModelIdentifier: ModelIdentifierProtocol { var fields: [(name: String, value: Persistable)] } +// swiftlint: disable identifier_name /// This class represents a lazy reference to a `Model`, meaning that the reference /// may or may not exist at instantiation time. /// @@ -100,8 +101,7 @@ public class LazyReference: Codable, _LazyReferenceValue { if let element = try? ModelType(from: decoder) { self.init(element) return - } - else { + } else { let identifiers = try ModelType.schema.lazyReferenceIdentifiers(from: object) self.init(identifiers: identifiers) return diff --git a/Amplify/Categories/DataStore/Model/PropertyPath.swift b/Amplify/Categories/DataStore/Model/PropertyPath.swift index 93c24d41c9..f8e6670fd7 100644 --- a/Amplify/Categories/DataStore/Model/PropertyPath.swift +++ b/Amplify/Categories/DataStore/Model/PropertyPath.swift @@ -32,7 +32,7 @@ public protocol PropertyPath { /// i.e. a `struct` representing another `Model`. /// /// - SeeAlso: `ModelPath` -public protocol PropertyContainerPath : PropertyPath { +public protocol PropertyContainerPath: PropertyPath { /// func getKeyPath() -> String @@ -80,7 +80,7 @@ public struct FieldPath: PropertyPath { /// var blog: ModelPath { BlogModelPath(name: "blog", parent: self) } /// } /// ``` -open class ModelPath : PropertyContainerPath { +open class ModelPath: PropertyContainerPath { private let metadata: PropertyPathMetadata diff --git a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift index 9907557f32..e5abf3b19d 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift @@ -31,7 +31,7 @@ extension TimeZone { } } - +// swiftlint:disable identifier_name /// ISO8601 Time Zone formats /// - Note: /// `±hh:mm:ss` is not a standard of ISO8601 date formate. It's supported by `AWSDateTime` exclusively. @@ -39,7 +39,7 @@ extension TimeZone { /// references: /// https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators /// https://docs.aws.amazon.com/appsync/latest/devguide/scalars.html#graph-ql-aws-appsync-scalars -fileprivate enum ISO8601TimeZoneFormat { +private enum ISO8601TimeZoneFormat { case utc, hh, hhmm, hh_mm, hh_mm_ss var format: String { @@ -148,3 +148,4 @@ fileprivate func tryExtract( case .hh_mm_ss: return .hh_mm_ss(hours: parts[0], minutes: parts[1], seconds: parts[2]) } } +// swiftlint:enable identifier_name diff --git a/Amplify/Categories/Logging/LoggingCategory.swift b/Amplify/Categories/Logging/LoggingCategory.swift index 6ec7268d8a..2aeb8c9849 100644 --- a/Amplify/Categories/Logging/LoggingCategory.swift +++ b/Amplify/Categories/Logging/LoggingCategory.swift @@ -57,7 +57,7 @@ final public class LoggingCategory: Category { /// For any external cases, Logging is always ready to be used. Internal configuration state is tracked via a /// different mechanism var isConfigured: Bool { - return plugins.count > 0 + return !plugins.isEmpty } var plugins: [PluginKey: LoggingCategoryPlugin] = Amplify.getLoggingCategoryPluginLookup(loggingPlugin: AWSUnifiedLoggingPlugin()) diff --git a/Amplify/Categories/Notifications/NotificationsCategory.swift b/Amplify/Categories/Notifications/NotificationsCategory.swift index 7e9e929653..02c4122b6f 100644 --- a/Amplify/Categories/Notifications/NotificationsCategory.swift +++ b/Amplify/Categories/Notifications/NotificationsCategory.swift @@ -11,7 +11,7 @@ import Foundation public final class NotificationsCategory { /// The Push Notifications category - public internal(set) var Push = PushNotificationsCategory() + public internal(set) var Push = PushNotificationsCategory() // swiftlint:disable:this identifier_name /// The current available subcategories that have been configured var subcategories: [NotificationsSubcategoryBehaviour] { diff --git a/Amplify/Categories/Predictions/Models/Language.swift b/Amplify/Categories/Predictions/Models/Language.swift index 941ea94e43..484ef1ac1e 100644 --- a/Amplify/Categories/Predictions/Models/Language.swift +++ b/Amplify/Categories/Predictions/Models/Language.swift @@ -8,6 +8,7 @@ import Foundation extension Predictions { + // swiftlint:disable file_length type_body_length public struct Language: Equatable, Decodable { public let code: String @@ -2404,3 +2405,4 @@ extension Predictions.Language { self = .init(code: languageCode) } } +// swiftlint:enable file_length type_body_length diff --git a/Amplify/Core/Support/Amplify+Publisher.swift b/Amplify/Core/Support/Amplify+Publisher.swift index f74b49ed47..3fb6e9b2f5 100644 --- a/Amplify/Core/Support/Amplify+Publisher.swift +++ b/Amplify/Core/Support/Amplify+Publisher.swift @@ -37,7 +37,7 @@ public extension Amplify { _ operation: @escaping @Sendable () async throws -> Success ) -> AnyPublisher { let task = Task(operation: operation) - return Future() { promise in + return Future { promise in Task { do { let value = try await task.value @@ -47,7 +47,7 @@ public extension Amplify { } } } - .handleEvents(receiveCancel: { task.cancel() } ) + .handleEvents(receiveCancel: { task.cancel() }) .eraseToAnyPublisher() } @@ -69,13 +69,13 @@ public extension Amplify { _ operation: @escaping @Sendable () async -> Success ) -> AnyPublisher { let task = Task(operation: operation) - return Future() { promise in + return Future { promise in Task { let value = await task.value promise(.success(value)) } } - .handleEvents(receiveCancel: { task.cancel() } ) + .handleEvents(receiveCancel: { task.cancel() }) .eraseToAnyPublisher() } @@ -113,7 +113,6 @@ public extension Amplify { // This is necessary to prevent the sequence from continuing to send values for a time // after cancellation in the case of a fast Iterator. try Task.checkCancellation() - subject.send(value) } subject.send(completion: .finished) diff --git a/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift b/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift index 74c578c87f..ca6d173c00 100644 --- a/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift +++ b/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift @@ -60,11 +60,14 @@ public class AmplifyOperationTaskAdapter: AmplifyTask, AmplifyInProcessReportingTask { +public class AmplifyInProcessReportingOperationTaskAdapter: AmplifyTask, AmplifyInProcessReportingTask { let operation: AmplifyInProcessReportingOperation let childTask: ChildTask - var resultToken: UnsubscribeToken? = nil - var inProcessToken: UnsubscribeToken? = nil + var resultToken: UnsubscribeToken? + var inProcessToken: UnsubscribeToken? public init(operation: AmplifyInProcessReportingOperation) { self.operation = operation diff --git a/Amplify/Core/Support/AmplifyTask.swift b/Amplify/Core/Support/AmplifyTask.swift index b40ffff779..915f0f06b6 100644 --- a/Amplify/Core/Support/AmplifyTask.swift +++ b/Amplify/Core/Support/AmplifyTask.swift @@ -69,7 +69,7 @@ public extension AmplifyInProcessReportingTask where InProcess == Progress { /// using [Progress](x-source-tag://Progress). /// /// - Tag: AmplifyInProcessReportingTask.progress - var progress : AmplifyAsyncSequence { + var progress: AmplifyAsyncSequence { get async { await inProcess } diff --git a/Amplify/DevMenu/Data/LogEntryHelper.swift b/Amplify/DevMenu/Data/LogEntryHelper.swift index 5b39c85eac..65fa2229da 100644 --- a/Amplify/DevMenu/Data/LogEntryHelper.swift +++ b/Amplify/DevMenu/Data/LogEntryHelper.swift @@ -25,7 +25,8 @@ struct LogEntryHelper { /// Helper function to fetch logs from `PersistentLoggingPlugin` static func getLogHistory() -> [LogEntryItem] { - if let loggingPlugin: PersistentLoggingPlugin = Amplify.Logging.plugins.first(where: { $0.key == DevMenuStringConstants.persistentLoggingPluginKey})?.value as? PersistentLoggingPlugin { + if let loggingPlugin: PersistentLoggingPlugin = Amplify.Logging.plugins.first(where: { + $0.key == DevMenuStringConstants.persistentLoggingPluginKey})?.value as? PersistentLoggingPlugin { if let logger: PersistentLogWrapper = loggingPlugin.default as? PersistentLogWrapper { return logger.getLogHistory() } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift index a74a36e390..36d71a87e8 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthSessionBehavior.swift @@ -17,37 +17,41 @@ import Amplify /// /// Types conforming to the `AuthSession` protocol support an `isSignedIn` flag. `isSignedIn` is true if a user has /// successfully completed a `signIn` flow, and has not subsequently signed out. -public protocol AWSAuthSessionBehavior : AuthSession { +public protocol AWSAuthSessionBehavior: AuthSession { - /// The concrete type holding the OIDC tokens from the authentication provider. Generally, this type will have at least - /// methods for retrieving an identity token and an access token. + /// The concrete type holding the OIDC tokens from the authentication provider. + /// Generally, this type will have at least methods for retrieving an identity token and an access token. associatedtype Tokens /// The result of the most recent attempt to get AWS Credentials. There is no guarantee that the credentials /// are not expired, but conforming types may have logic in place to automatically refresh the credentials. - /// The credentials may be fore either the unauthenticated or authenticated role, depending on the configuration of the - /// identity pool and the tokens used to retrieve the identity ID from Cognito. + /// The credentials may be fore either the unauthenticated or authenticated role, depending on the + /// configuration of the identity pool and the tokens used to retrieve the identity ID from Cognito. /// /// If the most recent attempt caused an error, the result will contain the details of the error. var awsCredentialsResult: Result { get } + // swiftlint:disable line_length /// The result of the most recent attempt to get a /// [Cognito identity pool identity ID](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html#CognitoIdentity-GetId-response-IdentityId). - /// The identityID may represent either an unauthenticated or authenticated identity, depending on the configuration of the - /// identity pool and the tokens used to retrieve the identity ID from Cognito. + /// The identityID may represent either an unauthenticated or authenticated identity, + /// depending on the configuration of the identity pool and the tokens used to + /// retrieve the identity ID from Cognito. /// /// If the most recent attempt caused an error, the result will contain the details of the error. var identityIdResult: Result { get } + // swiftlint:enable line_length - /// The result of the most recent attempt to get the current user's `sub` (unique User ID). Depending on the underlying - /// implementation, the details of the user ID may vary, but it is expected that this value is the `sub` claim of the - /// OIDC identity and access tokens. + /// The result of the most recent attempt to get the current user's `sub` (unique User ID). + /// Depending on the underlying implementation, the details of the user ID may vary, + /// but it is expected that this value is the `sub` claim of the OIDC identity and access tokens. /// /// If the most recent attempt caused an error, the result will contain the details of the error. var userSubResult: Result { get } - /// The result of the most recent attempt to get the current user's `sub` (unique User ID). Depending on the underlying - /// implementation, the details of the tokens may vary, but it is expected that the type will have at least methods for + /// The result of the most recent attempt to get the current user's `sub` (unique User ID). + /// Depending on the underlying implementation, + /// the details of the tokens may vary, but it is expected that the type will have at least methods for /// retrieving an identity token and an access token. /// /// If the most recent attempt caused an error, the result will contain the details of the error. diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift index e9e6c7e6ac..c08e8821c8 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthAWSCredentialsProvider.swift @@ -13,7 +13,7 @@ public protocol AuthAWSCredentialsProvider { func getAWSCredentials() -> Result } -public extension AuthAWSCredentialsProvider where Self:AWSAuthSessionBehavior { +public extension AuthAWSCredentialsProvider where Self: AWSAuthSessionBehavior { /// Return the most recent Result of fetching the AWS Credentials. If the temporary credentials are expired, returns /// a `AuthError.sessionExpired` failure. func getAWSCredentials() -> Result { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift index fe8d6bad45..f58cef8ce3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthCognitoIdentityProvider.swift @@ -15,7 +15,7 @@ public protocol AuthCognitoIdentityProvider { func getUserSub() -> Result } -public extension AuthCognitoIdentityProvider where Self:AWSAuthSessionBehavior { +public extension AuthCognitoIdentityProvider where Self: AWSAuthSessionBehavior { func getIdentityId() -> Result { identityIdResult } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift index ee6c00b1e0..3b7ccee072 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStatus.swift @@ -46,7 +46,10 @@ extension KeychainStatus: CustomStringConvertible { case .itemNotFound: return "The specified item could not be found in the keychain." case .missingEntitlement: - return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." + return """ + Internal error when a required entitlement isn't present, + client has neither application-identifier nor keychain-access-groups entitlements. + """ case .unexpectedError(let status): return "Unexpected error has occurred with status: \(status)." } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift index e1f6934490..e28e26067e 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift @@ -8,6 +8,7 @@ import Foundation import Security +// swiftlint:disable identifier_name public protocol KeychainStoreBehavior { @_spi(KeychainStore) @@ -239,3 +240,4 @@ extension KeychainStore { static let UseDataProtectionKeyChain = String(kSecUseDataProtectionKeychain) } } +// swiftlint:enable identifier_name diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift index c288ec0b38..6ceda508b4 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift @@ -78,7 +78,9 @@ extension KeychainStoreError: AmplifyError { } return """ To use Auth in a macOS project, you'll need to enable the Keychain Sharing capability. - This capability is required because Auth uses the Data Protection Keychain on macOS as a platform best practice. See TN3137: macOS keychain APIs and implementations for more information on how Keychain works on macOS and the Keychain Sharing entitlement. + This capability is required because Auth uses the Data Protection Keychain on macOS as + a platform best practice. See TN3137: macOS keychain APIs and implementations for more + information on how Keychain works on macOS and the Keychain Sharing entitlement. For more information on adding capabilities to your application, see Xcode Capabilities. """ #else diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift index 72ed86a415..f32276e2e6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift @@ -93,8 +93,10 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { if !primaryKeysOnly || graphQLType == .mutation { // Continue to add version fields for all levels, for backwards compatibility // Reduce the selection set only when the type is "subscription" and "query" - // (specifically for syncQuery). Selection set for mutation should not be reduced because it needs to be the full selection set to send mutation events to older iOS clients, which do not have the reduced subscription - // selection set. subscriptions and sync query is to receive data, so it can be reduced to allow decoding to the + // (specifically for syncQuery). Selection set for mutation should not be reduced + // because it needs to be the full selection set to send mutation events to older iOS clients, + // which do not have the reduced subscription selection set. + // subscriptions and sync query is to receive data, so it can be reduced to allow decoding to the // LazyReference type. selectionSet.children.forEach { child in addConflictResolution(selectionSet: child, From 11c11d0369c2dfbff2717c04fb7b18ada51c5cb2 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Thu, 21 Dec 2023 11:40:44 -0600 Subject: [PATCH 2/5] chore: resolve swiftlint warnings --- Amplify/Categories/API/APICategory.swift | 4 +-- .../APICategory+GraphQLBehavior.swift | 6 ++-- .../APICategory+RESTBehavior.swift | 2 +- .../APICategoryGraphQLBehavior.swift | 6 ++-- .../APICategoryRESTBehavior.swift | 4 +-- .../Operation/RetryableGraphQLOperation.swift | 2 +- .../AnalyticsCategory+ClientBehavior.swift | 2 +- .../Auth/AuthCategory+ClientBehavior.swift | 30 +++++++++++++++---- .../Auth/AuthCategory+DeviceBehavior.swift | 9 ++++-- .../Auth/AuthCategory+UserBehavior.swift | 21 ++++++++++--- .../Auth/AuthCategoryBehavior.swift | 22 ++++++++++---- .../Auth/AuthCategoryUserBehavior.swift | 27 +++++++++++++---- .../Auth/Models/AuthUserAttribute.swift | 15 +++++----- .../Auth/Models/DeliveryDestination.swift | 1 - .../Request/AuthFetchSessionRequest.swift | 1 - .../Auth/Request/AuthSignOutRequest.swift | 1 - .../Auth/Request/AuthWebUISignInRequest.swift | 4 +-- .../DataStoreCategory+Behavior.swift | 8 ++--- .../DataStore/DataStoreCategoryBehavior.swift | 4 +-- .../Model/Internal/ModelListProvider.swift | 10 +++---- .../Model/Internal/ModelProvider.swift | 16 +++++----- .../Schema/ModelSchema+Identifiers.swift | 6 ++-- .../Model/Lazy/ArrayLiteralListProvider.swift | 12 ++++---- .../Model/Lazy/DefaultModelProvider.swift | 12 ++++---- .../DataStore/Model/Lazy/LazyReference.swift | 30 +++++++++---------- .../DataStore/Model/Lazy/List+Model.swift | 5 ++-- .../DataStore/Model/PropertyPath.swift | 6 ++-- .../Model/Temporal/TimeZone+Extension.swift | 6 ++-- .../DataStore/Query/QueryField.swift | 4 --- .../DataStore/Query/QueryOperator.swift | 22 +++++++------- .../DataStore/Query/QueryPredicate.swift | 10 +++---- .../DataStoreCategory+Subscribe.swift | 2 +- Amplify/Categories/Hub/HubChannel.swift | 2 +- .../Logging/Internal/BroadcastLogger.swift | 22 +++++++------- ...LoggingCategory+CategoryConfigurable.swift | 4 +-- Amplify/Categories/Logging/LogLevel.swift | 2 +- .../LoggingCategory+ClientBehavior.swift | 10 +++---- .../Logging/LoggingCategory+Logger.swift | 2 +- .../Categories/Logging/LoggingCategory.swift | 2 +- .../LoggingCategoryClientBehavior.swift | 8 ++--- .../NotificationsCategoryConfiguration.swift | 2 +- ...otificationsCategory+ClientBehaviour.swift | 6 ++-- .../PredictionsCategoryBehavior.swift | 1 - .../Identify/Identify+Text+Result.swift | 2 +- Amplify/Core/Category/CategoryType.swift | 2 +- .../Internal/Amplify+Reset.swift | 2 +- Amplify/Core/Error/CoreError.swift | 2 +- Amplify/Core/Support/Amplify+Publisher.swift | 4 +-- .../Core/Support/AmplifyAsyncSequence.swift | 4 +-- .../AmplifyAsyncThrowingSequence.swift | 2 +- Amplify/Core/Support/AmplifyOperation.swift | 1 - .../AmplifyTask+OperationTaskAdapters.swift | 8 +++-- .../Core/Support/AsyncSequence+forEach.swift | 2 +- Amplify/Core/Support/AtomicDictionary.swift | 4 +-- Amplify/Core/Support/ChildTask.swift | 4 +-- Amplify/Core/Support/Fatal.swift | 2 -- Amplify/Core/Support/Optional+Extension.swift | 1 - Amplify/Core/Support/TaskQueue.swift | 2 +- .../Internal/HubChannelDispatcher.swift | 2 +- .../AWSUnifiedLoggingPlugin.swift | 10 +++---- .../ConsoleLoggingConfiguration.swift | 6 ++-- .../Internal/OSLogWrapper.swift | 4 +-- Amplify/DevMenu/Amplify+DevMenu.swift | 6 ++-- Amplify/DevMenu/Data/PluginInfoHelper.swift | 16 +++++----- .../Logging/PersistentLoggingPlugin.swift | 8 ++--- .../AsyncTesting/AsyncExpectation.swift | 4 +-- .../AsyncTestingTests/AsyncTestingTests.swift | 2 +- .../APICategoryGraphQLBehaviorExtended.swift | 2 +- .../AWSPluginsCore/AWSPluginOptions.swift | 2 +- .../Auth/AWSAuthModeStrategy.swift | 10 +++---- .../AWSPluginsCore/Auth/AWSAuthService.swift | 2 +- .../Auth/AWSAuthServiceBehavior.swift | 2 +- .../AmplifyAWSSignatureV4Signer.swift | 5 +++- .../Auth/Provider/AuthTokenProvider.swift | 2 +- .../Keychain/KeychainStore.swift | 16 +++++----- .../Keychain/KeychainStoreAttributes.swift | 4 +-- .../Keychain/KeychainStoreError.swift | 2 +- .../Model/Decorator/AuthRuleDecorator.swift | 2 +- .../ConflictResolutionDecorator.swift | 2 +- .../Model/Decorator/ModelDecorator.swift | 2 +- .../Model/Decorator/ModelIdDecorator.swift | 6 ++-- .../Model/GraphQLDocument/GraphQLQuery.swift | 2 +- .../ModelBasedGraphQLDocumentBuilder.swift | 2 +- .../GraphQLRequest+AnyModelWithSync.swift | 4 +-- .../GraphQLRequest/GraphQLRequest+Model.swift | 20 ++++++------- .../Model/Support/Model+GraphQL.swift | 4 +-- .../Model/Support/SelectionSet.swift | 4 +-- .../Sync/ModelSync/ModelSyncMetadata.swift | 2 +- .../MutationSyncMetadata+Schema.swift | 1 - .../PluginClientEngine.swift | 1 - .../UserAgentSuffixAppender.swift | 2 +- .../MockAWSAuthService.swift | 2 +- 92 files changed, 313 insertions(+), 261 deletions(-) diff --git a/Amplify/Categories/API/APICategory.swift b/Amplify/Categories/API/APICategory.swift index d09ef87cb2..4725180daa 100644 --- a/Amplify/Categories/API/APICategory.swift +++ b/Amplify/Categories/API/APICategory.swift @@ -11,7 +11,7 @@ final public class APICategory: Category { public var categoryType: CategoryType { .api } - + var plugins = [PluginKey: APICategoryPlugin]() /// Returns the plugin added to the category, if only one plugin is added. Accessing this property if no plugins @@ -49,7 +49,7 @@ final public class APICategory: Category { public var isConfigured = false // MARK: - Plugin handling - + /// Adds `plugin` to the list of Plugins that implement functionality for this category. /// /// - Parameter plugin: The Plugin to add diff --git a/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift index 59d5614dd9..10510fc7e0 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategory+GraphQLBehavior.swift @@ -6,16 +6,16 @@ // extension APICategory: APICategoryGraphQLBehavior { - + // MARK: - Request-based GraphQL operations public func query(request: GraphQLRequest) async throws -> GraphQLTask.Success { try await plugin.query(request: request) } - + public func mutate(request: GraphQLRequest) async throws -> GraphQLTask.Success { try await plugin.mutate(request: request) } - + public func subscribe(request: GraphQLRequest) -> AmplifyAsyncThrowingSequence> { plugin.subscribe(request: request) } diff --git a/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift index e0e453f327..8daa59636d 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategory+RESTBehavior.swift @@ -8,7 +8,7 @@ import Foundation extension APICategory: APICategoryRESTBehavior { - + public func get(request: RESTRequest) async throws -> RESTTask.Success { try await plugin.get(request: request) } diff --git a/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift index 841c4e1681..d149b5d945 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategoryGraphQLBehavior.swift @@ -18,7 +18,7 @@ public protocol APICategoryGraphQLBehavior: AnyObject { /// - listener: The event listener for the operation /// - Returns: The AmplifyOperation being enqueued func query(request: GraphQLRequest) async throws -> GraphQLTask.Success - + /// Perform a GraphQL mutate operation against a previously configured API. This operation /// will be asynchronous, with the callback accessible both locally and via the Hub. /// @@ -36,5 +36,7 @@ public protocol APICategoryGraphQLBehavior: AnyObject { /// - valueListener: Invoked when the GraphQL subscription receives a new value from the service /// - completionListener: Invoked when the subscription has terminated /// - Returns: The AmplifyInProcessReportingOperation being enqueued - func subscribe(request: GraphQLRequest) -> AmplifyAsyncThrowingSequence> + func subscribe( + request: GraphQLRequest + ) -> AmplifyAsyncThrowingSequence> } diff --git a/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift b/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift index 8fafc4c52d..0a4c33c27e 100644 --- a/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift +++ b/Amplify/Categories/API/ClientBehavior/APICategoryRESTBehavior.swift @@ -27,13 +27,13 @@ public protocol APICategoryRESTBehavior { /// - Parameter request: Contains information such as path, query parameters, body. /// - Returns: An operation that can be observed for its value func post(request: RESTRequest) async throws -> RESTTask.Success - + /// Perform an HTTP DELETE operation /// /// - Parameter request: Contains information such as path, query parameters, body. /// - Returns: An operation that can be observed for its value func delete(request: RESTRequest) async throws -> RESTTask.Success - + /// Perform an HTTP HEAD operation /// /// - Parameter request: Contains information such as path, query parameters, body. diff --git a/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift b/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift index 7b4b36ef59..ed2a6e2753 100644 --- a/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift +++ b/Amplify/Categories/API/Operation/RetryableGraphQLOperation.swift @@ -116,7 +116,7 @@ public final class RetryableGraphQLOperation: Operation, Ret self.operationFactory = operationFactory self.resultListener = resultListener } - + public override func main() { Task { start(request: await requestFactory()) diff --git a/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift b/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift index 796b3865a5..e73abe1c15 100644 --- a/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift +++ b/Amplify/Categories/Analytics/AnalyticsCategory+ClientBehavior.swift @@ -50,7 +50,7 @@ extension AnalyticsCategory { public func unregisterGlobalProperties(_ keys: String...) { plugin.unregisterGlobalProperties(keys.isEmpty ? nil : Set(keys)) } - + /// Registered global properties can be unregistered though this method. In case no keys are provided, *all* /// registered global properties will be unregistered. Duplicate keys will be ignored. This method can be called /// from `Amplify.Analytics` and is a wrapper for `unregisterGlobalProperties(_ keys: Set? = nil)` diff --git a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift index cb707db8d7..8896be20ea 100644 --- a/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+ClientBehavior.swift @@ -9,7 +9,11 @@ import Foundation extension AuthCategory: AuthCategoryBehavior { - public func signUp( username: String, password: String? = nil, options: AuthSignUpRequest.Options? = nil) async throws -> AuthSignUpResult { + public func signUp( + username: String, + password: String? = nil, + options: AuthSignUpRequest.Options? = nil + ) async throws -> AuthSignUpResult { return try await plugin.signUp(username: username, password: password, options: options) } @@ -19,7 +23,10 @@ extension AuthCategory: AuthCategoryBehavior { return try await plugin.confirmSignUp(for: username, confirmationCode: confirmationCode, options: options) } - public func resendSignUpCode(for username: String, options: AuthResendSignUpCodeRequest.Options? = nil) async throws -> AuthCodeDeliveryDetails { + public func resendSignUpCode( + for username: String, + options: AuthResendSignUpCodeRequest.Options? = nil + ) async throws -> AuthCodeDeliveryDetails { return try await plugin.resendSignUpCode(for: username, options: options) } @@ -46,14 +53,17 @@ extension AuthCategory: AuthCategoryBehavior { } #endif - public func confirmSignIn(challengeResponse: String, options: AuthConfirmSignInRequest.Options? = nil) async throws -> AuthSignInResult { + public func confirmSignIn( + challengeResponse: String, + options: AuthConfirmSignInRequest.Options? = nil + ) async throws -> AuthSignInResult { return try await plugin.confirmSignIn(challengeResponse: challengeResponse, options: options) } public func signOut(options: AuthSignOutRequest.Options? = nil) async -> AuthSignOutResult { return await plugin.signOut(options: options) } - + public func deleteUser() async throws { try await plugin.deleteUser() } @@ -62,7 +72,10 @@ extension AuthCategory: AuthCategoryBehavior { return try await plugin.fetchAuthSession(options: options) } - public func resetPassword(for username: String, options: AuthResetPasswordRequest.Options? = nil) async throws -> AuthResetPasswordResult { + public func resetPassword( + for username: String, + options: AuthResetPasswordRequest.Options? = nil + ) async throws -> AuthResetPasswordResult { return try await plugin.resetPassword(for: username, options: options) } @@ -72,7 +85,12 @@ extension AuthCategory: AuthCategoryBehavior { confirmationCode: String, options: AuthConfirmResetPasswordRequest.Options? = nil ) async throws { - try await plugin.confirmResetPassword(for: username, with: newPassword, confirmationCode: confirmationCode, options: options) + try await plugin.confirmResetPassword( + for: username, + with: newPassword, + confirmationCode: confirmationCode, + options: options + ) } public func setUpTOTP() async throws -> TOTPSetupDetails { diff --git a/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift b/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift index 104fb56a6f..a9da3b0099 100644 --- a/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+DeviceBehavior.swift @@ -9,11 +9,16 @@ import Foundation extension AuthCategory: AuthCategoryDeviceBehavior { - public func fetchDevices( options: AuthFetchDevicesRequest.Options? = nil) async throws -> [AuthDevice] { + public func fetchDevices( + options: AuthFetchDevicesRequest.Options? = nil + ) async throws -> [AuthDevice] { return try await plugin.fetchDevices(options: options) } - public func forgetDevice( _ device: AuthDevice? = nil, options: AuthForgetDeviceRequest.Options? = nil) async throws { + public func forgetDevice( + _ device: AuthDevice? = nil, + options: AuthForgetDeviceRequest.Options? = nil + ) async throws { try await plugin.forgetDevice(device, options: options) } diff --git a/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift b/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift index 5c3fc21076..6589e03083 100644 --- a/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategory+UserBehavior.swift @@ -13,11 +13,16 @@ extension AuthCategory: AuthCategoryUserBehavior { try await plugin.getCurrentUser() } - public func fetchUserAttributes(options: AuthFetchUserAttributesRequest.Options? = nil) async throws -> [AuthUserAttribute] { + public func fetchUserAttributes( + options: AuthFetchUserAttributesRequest.Options? = nil + ) async throws -> [AuthUserAttribute] { try await plugin.fetchUserAttributes(options: options) } - public func update(userAttribute: AuthUserAttribute, options: AuthUpdateUserAttributeRequest.Options? = nil) async throws -> AuthUpdateAttributeResult { + public func update( + userAttribute: AuthUserAttribute, + options: AuthUpdateUserAttributeRequest.Options? = nil + ) async throws -> AuthUpdateAttributeResult { try await plugin.update(userAttribute: userAttribute, options: options) } @@ -45,10 +50,18 @@ extension AuthCategory: AuthCategoryUserBehavior { public func confirm(userAttribute: AuthUserAttributeKey, confirmationCode: String, options: AuthConfirmUserAttributeRequest.Options? = nil) async throws { - try await plugin.confirm(userAttribute: userAttribute, confirmationCode: confirmationCode, options: options) + try await plugin.confirm( + userAttribute: userAttribute, + confirmationCode: confirmationCode, + options: options + ) } - public func update(oldPassword: String, to newPassword: String, options: AuthChangePasswordRequest.Options? = nil) async throws { + public func update( + oldPassword: String, + to newPassword: String, + options: AuthChangePasswordRequest.Options? = nil + ) async throws { try await plugin.update(oldPassword: oldPassword, to: newPassword, options: options) } diff --git a/Amplify/Categories/Auth/AuthCategoryBehavior.swift b/Amplify/Categories/Auth/AuthCategoryBehavior.swift index 005eb965c5..68f6cc2f7f 100644 --- a/Amplify/Categories/Auth/AuthCategoryBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategoryBehavior.swift @@ -24,7 +24,11 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - username: username to signUp /// - password: password as per the password policy of the provider /// - options: Parameters specific to plugin behavior - func signUp(username: String, password: String?, options: AuthSignUpRequest.Options?) async throws -> AuthSignUpResult + func signUp( + username: String, + password: String?, + options: AuthSignUpRequest.Options? + ) async throws -> AuthSignUpResult /// Confirms the `signUp` operation. /// @@ -44,7 +48,10 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - Parameters: /// - username: Username of the user to be confirmed. /// - options: Parameters specific to plugin behavior. - func resendSignUpCode(for username: String, options: AuthResendSignUpCodeRequest.Options?) async throws -> AuthCodeDeliveryDetails + func resendSignUpCode( + for username: String, + options: AuthResendSignUpCodeRequest.Options? + ) async throws -> AuthCodeDeliveryDetails /// SignIn to the authentication provider /// @@ -90,7 +97,10 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// - Parameters: /// - challengeResponse: Challenge response required to confirm the next step in signIn flow /// - options: Parameters specific to plugin behavior. - func confirmSignIn(challengeResponse: String, options: AuthConfirmSignInRequest.Options?) async throws -> AuthSignInResult + func confirmSignIn( + challengeResponse: String, + options: AuthConfirmSignInRequest.Options? + ) async throws -> AuthSignInResult /// Sign out the currently logged-in user. /// @@ -132,7 +142,8 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// Initiates TOTP Setup /// /// Invoke this operation to setup TOTP for the user while signed in. - /// Calling this method will initiate TOTP setup process and returns a shared secret that can be used to generate QR code. + /// Calling this method will initiate TOTP setup process and + /// returns a shared secret that can be used to generate QR code. /// The setup details also contains a URI generator helper that can be used to retireve a TOTP Setup URI. /// func setUpTOTP() async throws -> TOTPSetupDetails @@ -140,7 +151,8 @@ public protocol AuthCategoryBehavior: AuthCategoryUserBehavior, AuthCategoryDevi /// Verifies TOTP Setup /// /// Invoke this operation to verify TOTP setup for the user while signed in. - /// Calling this method with the verification code from the associated Authenticator app will complete the TOTP setup process. + /// Calling this method with the verification code from the associated Authenticator app + /// will complete the TOTP setup process. /// /// - Parameters: /// - code: verification code from the associated Authenticator app diff --git a/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift b/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift index f3917109c7..ad9d106eaf 100644 --- a/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift +++ b/Amplify/Categories/Auth/AuthCategoryUserBehavior.swift @@ -17,22 +17,29 @@ public protocol AuthCategoryUserBehavior: AnyObject { /// /// - Parameters: /// - options: Parameters specific to plugin behavior - func fetchUserAttributes(options: AuthFetchUserAttributesRequest.Options?) async throws -> [AuthUserAttribute] + func fetchUserAttributes( + options: AuthFetchUserAttributesRequest.Options? + ) async throws -> [AuthUserAttribute] /// Update user attribute for the current user /// /// - Parameters: /// - userAttribute: Attribute that need to be updated /// - options: Parameters specific to plugin behavior - func update(userAttribute: AuthUserAttribute, options: AuthUpdateUserAttributeRequest.Options?) async throws -> AuthUpdateAttributeResult + func update( + userAttribute: AuthUserAttribute, + options: AuthUpdateUserAttributeRequest.Options? + ) async throws -> AuthUpdateAttributeResult /// Update a list of user attributes for the current user /// /// - Parameters: /// - userAttributes: List of attribtues that need ot be updated /// - options: Parameters specific to plugin behavior - func update(userAttributes: [AuthUserAttribute], - options: AuthUpdateUserAttributesRequest.Options?) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] + func update( + userAttributes: [AuthUserAttribute], + options: AuthUpdateUserAttributesRequest.Options? + ) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] /// Resends the confirmation code required to verify an attribute /// @@ -61,7 +68,11 @@ public protocol AuthCategoryUserBehavior: AnyObject { /// - userAttribute: Attribute to verify /// - confirmationCode: Confirmation code received /// - options: Parameters specific to plugin behavior - func confirm(userAttribute: AuthUserAttributeKey, confirmationCode: String, options: AuthConfirmUserAttributeRequest.Options?) async throws + func confirm( + userAttribute: AuthUserAttributeKey, + confirmationCode: String, + options: AuthConfirmUserAttributeRequest.Options? + ) async throws /// Update the current logged in user's password /// @@ -70,5 +81,9 @@ public protocol AuthCategoryUserBehavior: AnyObject { /// - oldPassword: Current password of the user /// - newPassword: New password to be updated /// - options: Parameters specific to plugin behavior - func update(oldPassword: String, to newPassword: String, options: AuthChangePasswordRequest.Options?) async throws + func update( + oldPassword: String, + to newPassword: String, + options: AuthChangePasswordRequest.Options? + ) async throws } diff --git a/Amplify/Categories/Auth/Models/AuthUserAttribute.swift b/Amplify/Categories/Auth/Models/AuthUserAttribute.swift index 01d77b6308..7990ffe276 100644 --- a/Amplify/Categories/Auth/Models/AuthUserAttribute.swift +++ b/Amplify/Categories/Auth/Models/AuthUserAttribute.swift @@ -28,7 +28,7 @@ public enum AuthUserAttributeKey { /// Attribute key for user's email case email - + /// Attribute key for user's email verfication status case emailVerified @@ -55,7 +55,7 @@ public enum AuthUserAttributeKey { /// Attribute key for user's phone number case phoneNumber - + /// Attribute key for user's phone number verficiation status case phoneNumberVerified @@ -64,19 +64,19 @@ public enum AuthUserAttributeKey { /// Attribute key for user's preferred user name case preferredUsername - + /// Attribute key for user's profile case profile - + /// Attribute key for user's identifier case sub - + /// Attribute key for time of user's information last updated case updatedAt - + /// Attribute key for user's web page case website - + /// Attribute key for user's time zone case zoneInfo @@ -90,4 +90,3 @@ public enum AuthUserAttributeKey { extension AuthUserAttributeKey: Hashable {} extension AuthUserAttributeKey: Equatable {} - diff --git a/Amplify/Categories/Auth/Models/DeliveryDestination.swift b/Amplify/Categories/Auth/Models/DeliveryDestination.swift index defa40d415..17a417d8ec 100644 --- a/Amplify/Categories/Auth/Models/DeliveryDestination.swift +++ b/Amplify/Categories/Auth/Models/DeliveryDestination.swift @@ -24,4 +24,3 @@ public enum DeliveryDestination { } extension DeliveryDestination: Equatable { } - diff --git a/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift b/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift index da8bbd1e7b..debdb449e4 100644 --- a/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthFetchSessionRequest.swift @@ -47,4 +47,3 @@ extension AuthFetchSessionRequest.Options { return AuthFetchSessionRequest.Options(forceRefresh: true) } } - diff --git a/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift b/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift index df1ca20da8..4d7e12093f 100644 --- a/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthSignOutRequest.swift @@ -52,7 +52,6 @@ public extension AuthSignOutRequest { #endif } - } #if os(iOS) || os(macOS) diff --git a/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift b/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift index 1852dc2564..f320daff43 100644 --- a/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift +++ b/Amplify/Categories/Auth/Request/AuthWebUISignInRequest.swift @@ -21,7 +21,7 @@ public struct AuthWebUISignInRequest: AmplifyOperationRequest { /// Presentation anchor on which the webUI is displayed public let presentationAnchor: AuthUIPresentationAnchor? - + public init(presentationAnchor: AuthUIPresentationAnchor?, authProvider: AuthProvider? = nil, options: Options) { @@ -37,7 +37,7 @@ public extension AuthWebUISignInRequest { /// Scopes to be defined for the sign in user public let scopes: [String]? - + /// Extra plugin specific options, only used in special circumstances when the existing options do not provide /// a way to utilize the underlying auth plugin functionality. See plugin documentation for expected /// key/values diff --git a/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift b/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift index ed400245f0..4d15a9bff1 100644 --- a/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift +++ b/Amplify/Categories/DataStore/DataStoreCategory+Behavior.swift @@ -17,7 +17,7 @@ extension DataStoreCategory: DataStoreBaseBehavior { byId id: String) async throws -> M? { try await plugin.query(modelType, byId: id) } - + public func query(_ modelType: M.Type, byIdentifier id: String) async throws -> M? where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { @@ -41,13 +41,13 @@ extension DataStoreCategory: DataStoreBaseBehavior { where predicate: QueryPredicate? = nil) async throws { try await plugin.delete(model, where: predicate) } - + public func delete(_ modelType: M.Type, withId id: String, where predicate: QueryPredicate? = nil) async throws { try await plugin.delete(modelType, withId: id, where: predicate) } - + public func delete(_ modelType: M.Type, withIdentifier id: String, where predicate: QueryPredicate? = nil) async throws @@ -60,7 +60,7 @@ extension DataStoreCategory: DataStoreBaseBehavior { where predicate: QueryPredicate? = nil) async throws where M: ModelIdentifiable { try await plugin.delete(modelType, withIdentifier: id, where: predicate) } - + public func delete(_ modelType: M.Type, where predicate: QueryPredicate) async throws { try await plugin.delete(modelType, where: predicate) diff --git a/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift b/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift index d6de0186f7..43aa4d3892 100644 --- a/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift +++ b/Amplify/Categories/DataStore/DataStoreCategoryBehavior.swift @@ -39,7 +39,7 @@ public protocol DataStoreBaseBehavior { func delete(_ modelType: M.Type, withId id: String, where predicate: QueryPredicate?) async throws - + func delete(_ modelType: M.Type, withIdentifier id: String, where predicate: QueryPredicate?) async throws where M: ModelIdentifiable, @@ -82,7 +82,7 @@ public protocol DataStoreSubscribeBehavior { /// Returns an AmplifyAsyncThrowingSequence for model changes (create, updates, delete) /// - Parameter modelType: The model type to observe func observe(_ modelType: M.Type) -> AmplifyAsyncThrowingSequence - + /// Returns a Publisher for query snapshots. /// /// - Parameters: diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift b/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift index 9b593b04e0..582d9bdc1c 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelListProvider.swift @@ -40,7 +40,7 @@ public protocol ModelListProvider { associatedtype Element: Model func getState() -> ModelListProviderState - + /// Retrieve the array of `Element` from the data source asychronously. func load() async throws -> [Element] @@ -52,7 +52,7 @@ public protocol ModelListProvider { /// Asynchronously retrieve the next page as a new in-memory List object. Returns a failure if there /// is no next page of results. You can validate whether the list has another page with `hasNextPage()`. func getNextPage() async throws -> List - + /// Custom encoder func encode(to encoder: Encoder) throws } @@ -67,7 +67,7 @@ public struct AnyModelListProvider: ModelListProvider { private let hasNextPageClosure: () -> Bool private let getNextPageAsync: () async throws -> List private let encodeClosure: (Encoder) throws -> Void - + public init( provider: Provider ) where Provider.Element == Self.Element { @@ -81,7 +81,7 @@ public struct AnyModelListProvider: ModelListProvider { public func getState() -> ModelListProviderState { getStateClosure() } - + public func load() async throws -> [Element] { try await loadAsync() } @@ -93,7 +93,7 @@ public struct AnyModelListProvider: ModelListProvider { public func getNextPage() async throws -> List { try await getNextPageAsync() } - + public func encode(to encoder: Encoder) throws { try encodeClosure(encoder) } diff --git a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift index dca0c40c28..98c93dfa00 100644 --- a/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift +++ b/Amplify/Categories/DataStore/Model/Internal/ModelProvider.swift @@ -44,11 +44,11 @@ public enum ModelProviderState { /// change. public protocol ModelProvider { associatedtype Element: Model - + func load() async throws -> Element? - + func getState() -> ModelProviderState - + func encode(to encoder: Encoder) throws } @@ -57,25 +57,25 @@ public protocol ModelProvider { /// application making any change to these `public` types should be backward compatible, otherwise it will be a breaking /// change. public struct AnyModelProvider: ModelProvider { - + private let loadAsync: () async throws -> Element? private let getStateClosure: () -> ModelProviderState private let encodeClosure: (Encoder) throws -> Void - + public init(provider: Provider) where Provider.Element == Self.Element { self.loadAsync = provider.load self.getStateClosure = provider.getState self.encodeClosure = provider.encode } - + public func load() async throws -> Element? { try await loadAsync() } - + public func getState() -> ModelProviderState { getStateClosure() } - + public func encode(to encoder: Encoder) throws { try encodeClosure(encoder) } diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift index 2e01b9b12f..a627525ba9 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelSchema+Identifiers.swift @@ -12,12 +12,12 @@ extension ModelSchema { enum ExtractionError: Error { case unsupportedLazyReferenceIdentifier(name: String, value: JSONValue?) } - + var identifiers = [LazyReferenceIdentifier]() for identifierField in primaryKey.fields { let object = modelObject[identifierField.name] - + switch object { case .string(let identifierValue): identifiers.append(.init(name: identifierField.name, value: identifierValue)) @@ -28,7 +28,7 @@ extension ModelSchema { ) } } - + return identifiers } } diff --git a/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift b/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift index 7aafd0b49a..7c8e128853 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/ArrayLiteralListProvider.swift @@ -8,16 +8,16 @@ import Foundation public struct ArrayLiteralListProvider: ModelListProvider { - + let elements: [Element] public init(elements: [Element]) { self.elements = elements } - + public func getState() -> ModelListProviderState { return .loaded(elements) } - + public func load() -> Result<[Element], CoreError> { .success(elements) } @@ -25,7 +25,7 @@ public struct ArrayLiteralListProvider: ModelListProvider { public func load(completion: @escaping (Result<[Element], CoreError>) -> Void) { completion(.success(elements)) } - + public func load() async throws -> [Element] { return elements } @@ -39,13 +39,13 @@ public struct ArrayLiteralListProvider: ModelListProvider { "Don't call this method", nil))) } - + public func getNextPage() async throws -> List { throw CoreError.clientValidation("No pagination on an array literal", "Don't call this method", nil) } - + public func encode(to encoder: Encoder) throws { try elements.encode(to: encoder) } diff --git a/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift b/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift index 8eb7b22a74..24dca4f26a 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/DefaultModelProvider.swift @@ -10,17 +10,17 @@ import Foundation // MARK: - DefaultModelProvider public struct DefaultModelProvider: ModelProvider { - + var loadedState: ModelProviderState - + public init(element: Element? = nil) { self.loadedState = .loaded(model: element) } - + public init(identifiers: [LazyReferenceIdentifier]?) { self.loadedState = .notLoaded(identifiers: identifiers) } - + public func load() async throws -> Element? { switch loadedState { case .notLoaded: @@ -29,11 +29,11 @@ public struct DefaultModelProvider: ModelProvider { return model } } - + public func getState() -> ModelProviderState { loadedState } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let identifiers): diff --git a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift index c2625391a4..343b059225 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/LazyReference.swift @@ -13,7 +13,7 @@ import Combine public struct LazyReferenceIdentifier: Codable { public let name: String public let value: String - + public init(name: String, value: String) { self.name = name self.value = value @@ -41,15 +41,15 @@ struct LazyReferenceModelIdentifier: ModelIdentifierProtocol { /// The default implementation `DefaultModelProvider` only handles in-memory data, therefore `get()` and /// `require()` will simply return the current `reference`. public class LazyReference: Codable, _LazyReferenceValue { - + /// Represents the data state of the `LazyModel`. enum LoadedState { case notLoaded(identifiers: [LazyReferenceIdentifier]?) case loaded(ModelType?) } - + var loadedState: LoadedState - + @_spi(LazyReference) public var _state: _LazyReferenceValueState { switch loadedState { @@ -59,10 +59,10 @@ public class LazyReference: Codable, _LazyReferenceValue { return .loaded(model: model) } } - + /// The provider for fulfilling list behaviors let modelProvider: AnyModelProvider - + public init(modelProvider: AnyModelProvider) { self.modelProvider = modelProvider switch self.modelProvider.getState() { @@ -72,21 +72,21 @@ public class LazyReference: Codable, _LazyReferenceValue { self.loadedState = .notLoaded(identifiers: identifiers) } } - + // MARK: - Initializers - + public convenience init(_ reference: ModelType?) { let modelProvider = DefaultModelProvider(element: reference).eraseToAnyModelProvider() self.init(modelProvider: modelProvider) } - + public convenience init(identifiers: [LazyReferenceIdentifier]?) { let modelProvider = DefaultModelProvider(identifiers: identifiers).eraseToAnyModelProvider() self.init(modelProvider: modelProvider) } - + // MARK: - Codable implementation - + /// Decodable implementation is delegated to the ModelProviders. required convenience public init(from decoder: Decoder) throws { for modelDecoder in ModelProviderRegistry.decoders.get() { @@ -111,14 +111,14 @@ public class LazyReference: Codable, _LazyReferenceValue { } self.init(identifiers: nil) } - + /// Encodable implementation is delegated to the underlying ModelProviders. public func encode(to encoder: Encoder) throws { try modelProvider.encode(to: encoder) } - + // MARK: - APIs - + /// This function is responsible for retrieving the model reference. In the default /// implementation this means simply returning the existing `reference`, but different /// storage mechanisms can implement their own logic to fetch data, @@ -135,7 +135,7 @@ public class LazyReference: Codable, _LazyReferenceValue { return element } } - + /// The equivalent of `get()` but aimed to retrieve references that are considered /// non-optional. However, referential integrity issues and/or availability constraints /// might affect how required data is fetched. In such scenarios the implementation diff --git a/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift b/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift index aee10e9e53..283cc53ff7 100644 --- a/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift +++ b/Amplify/Categories/DataStore/Model/Lazy/List+Model.swift @@ -26,13 +26,13 @@ public class List: Collection, Codable, ExpressibleByArrayLite /// The current state of lazily loaded list var loadedState: LoadedState - + /// Boolean property to check if list is loaded public var isLoaded: Bool { if case .loaded = loadedState { return true } - + return false } @@ -70,7 +70,6 @@ public class List: Collection, Codable, ExpressibleByArrayLite } } - // MARK: - Initializers public init(listProvider: AnyModelListProvider) { diff --git a/Amplify/Categories/DataStore/Model/PropertyPath.swift b/Amplify/Categories/DataStore/Model/PropertyPath.swift index f8e6670fd7..212430f56d 100644 --- a/Amplify/Categories/DataStore/Model/PropertyPath.swift +++ b/Amplify/Categories/DataStore/Model/PropertyPath.swift @@ -43,7 +43,7 @@ public protocol PropertyContainerPath: PropertyPath { } extension PropertyContainerPath { - + public func getKeyPath() -> String { var metadata = getMetadata() var path = [String]() @@ -123,11 +123,11 @@ open class ModelPath: PropertyContainerPath { public func time(_ name: String) -> FieldPath { FieldPath(name: name, parent: self) } - + public func int(_ name: String) -> FieldPath { FieldPath(name: name, parent: self) } - + public func double(_ name: String) -> FieldPath { FieldPath(name: name, parent: self) } diff --git a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift index e5abf3b19d..efbbbfb673 100644 --- a/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift +++ b/Amplify/Categories/DataStore/Model/Temporal/TimeZone+Extension.swift @@ -5,7 +5,6 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation extension TimeZone { @@ -98,14 +97,13 @@ private enum ISO8601TimeZoneFormat { } } -fileprivate enum ISO8601TimeZonePart { +private enum ISO8601TimeZonePart { case utc case hh(hours: Int) case hhmm(hours: Int, minutes: Int) case hh_mm(hours: Int, minuts: Int) case hh_mm_ss(hours: Int, minutes: Int, seconds: Int) - static func from(iso8601DateString: String) -> ISO8601TimeZonePart? { return tryExtract(from: iso8601DateString, with: .utc) ?? tryExtract(from: iso8601DateString, with: .hh) @@ -116,7 +114,7 @@ fileprivate enum ISO8601TimeZonePart { } } -fileprivate func tryExtract( +private func tryExtract( from dateString: String, with format: ISO8601TimeZoneFormat ) -> ISO8601TimeZonePart? { diff --git a/Amplify/Categories/DataStore/Query/QueryField.swift b/Amplify/Categories/DataStore/Query/QueryField.swift index 07a573945f..9d29967569 100644 --- a/Amplify/Categories/DataStore/Query/QueryField.swift +++ b/Amplify/Categories/DataStore/Query/QueryField.swift @@ -61,10 +61,6 @@ public struct QueryField: QueryFieldOperation { public let name: String - init(name: String) { - self.name = name - } - // MARK: - beginsWith public func beginsWith(_ value: String) -> QueryPredicateOperation { return QueryPredicateOperation(field: name, operator: .beginsWith(value)) diff --git a/Amplify/Categories/DataStore/Query/QueryOperator.swift b/Amplify/Categories/DataStore/Query/QueryOperator.swift index 18578eb552..2fcb50ccd2 100644 --- a/Amplify/Categories/DataStore/Query/QueryOperator.swift +++ b/Amplify/Categories/DataStore/Query/QueryOperator.swift @@ -18,7 +18,7 @@ public enum QueryOperator: Encodable { case notContains(_ value: String) case between(start: Persistable, end: Persistable) case beginsWith(_ value: String) - + public func evaluate(target: Any) -> Bool { switch self { case .notEqual(let predicateValue): @@ -51,17 +51,17 @@ public enum QueryOperator: Encodable { } return false } - + private enum CodingKeys: String, CodingKey { case type case value case start case end } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - + switch self { case .notEqual(let value): try container.encode("notEqual", forKey: .type) @@ -76,32 +76,32 @@ public enum QueryOperator: Encodable { case .lessOrEqual(let value): try container.encode("lessOrEqual", forKey: .type) try container.encode(value, forKey: .value) - + case .lessThan(let value): try container.encode("lessThan", forKey: .type) try container.encode(value, forKey: .value) - + case .greaterOrEqual(let value): try container.encode("greaterOrEqual", forKey: .type) try container.encode(value, forKey: .value) - + case .greaterThan(let value): try container.encode("greaterThan", forKey: .type) try container.encode(value, forKey: .value) - + case .contains(let value): try container.encode("contains", forKey: .type) try container.encode(value, forKey: .value) - + case .notContains(let value): try container.encode("notContains", forKey: .type) try container.encode(value, forKey: .value) - + case .between(let start, let end): try container.encode("between", forKey: .type) try container.encode(start, forKey: .start) try container.encode(end, forKey: .end) - + case .beginsWith(let value): try container.encode("beginsWith", forKey: .type) try container.encode(value, forKey: .value) diff --git a/Amplify/Categories/DataStore/Query/QueryPredicate.swift b/Amplify/Categories/DataStore/Query/QueryPredicate.swift index 5d242502a1..78bdf9f051 100644 --- a/Amplify/Categories/DataStore/Query/QueryPredicate.swift +++ b/Amplify/Categories/DataStore/Query/QueryPredicate.swift @@ -92,9 +92,9 @@ public class QueryPredicateGroup: QueryPredicate, Encodable { return !predicate.evaluate(target: target) } } - + // MARK: - Encodable conformance - + private enum CodingKeys: String, CodingKey { case type case predicates @@ -111,15 +111,15 @@ public class QueryPredicateGroup: QueryPredicate, Encodable { try _encode(encoder) } } - + public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type.rawValue, forKey: .type) - + let anyPredicates = predicates.map(AnyQueryPredicate.init) try container.encode(anyPredicates, forKey: .predicates) } - + } public class QueryPredicateOperation: QueryPredicate, Encodable { diff --git a/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift b/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift index 0e1d802b87..ae669c73f9 100644 --- a/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift +++ b/Amplify/Categories/DataStore/Subscribe/DataStoreCategory+Subscribe.swift @@ -11,7 +11,7 @@ extension DataStoreCategory: DataStoreSubscribeBehavior { public func observe(_ modelType: M.Type) -> AmplifyAsyncThrowingSequence { return plugin.observe(modelType) } - + public func observeQuery(for modelType: M.Type, where predicate: QueryPredicate? = nil, sort sortInput: QuerySortInput? = nil) diff --git a/Amplify/Categories/Hub/HubChannel.swift b/Amplify/Categories/Hub/HubChannel.swift index ba68e0f85a..0979ac95c3 100644 --- a/Amplify/Categories/Hub/HubChannel.swift +++ b/Amplify/Categories/Hub/HubChannel.swift @@ -25,7 +25,7 @@ public enum HubChannel { case logging case predictions - + case pushNotifications case storage diff --git a/Amplify/Categories/Logging/Internal/BroadcastLogger.swift b/Amplify/Categories/Logging/Internal/BroadcastLogger.swift index 267d19c084..849c93533b 100644 --- a/Amplify/Categories/Logging/Internal/BroadcastLogger.swift +++ b/Amplify/Categories/Logging/Internal/BroadcastLogger.swift @@ -11,23 +11,23 @@ /// /// - Tag: BroadcastLogger final class BroadcastLogger { - + /// The default LogLevel used when no targets are available. /// /// - Tag: LogProxy.defaultLogLevel var defaultLogLevel: Amplify.LogLevel = .error - + private let targets: [Logger] - + /// - Tag: BroadcastLogger.init init(targets: [Logger]) { self.targets = targets } - + } extension BroadcastLogger: Logger { - + var logLevel: Amplify.LogLevel { get { if let logger = targets.first { @@ -42,27 +42,27 @@ extension BroadcastLogger: Logger { } } } - + func error(_ message: @autoclosure () -> String) { targets.forEach { $0.error(message()) } } - + func error(error: Error) { targets.forEach { $0.error(error: error) } } - + func warn(_ message: @autoclosure () -> String) { targets.forEach { $0.warn(message()) } } - + func info(_ message: @autoclosure () -> String) { targets.forEach { $0.info(message()) } } - + func debug(_ message: @autoclosure () -> String) { targets.forEach { $0.debug(message()) } } - + func verbose(_ message: @autoclosure () -> String) { targets.forEach { $0.verbose(message()) } } diff --git a/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift b/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift index 8a9bee7890..4c691fd65c 100644 --- a/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift +++ b/Amplify/Categories/Logging/Internal/LoggingCategory+CategoryConfigurable.swift @@ -27,11 +27,11 @@ extension LoggingCategory: CategoryConfigurable { try plugin.configure(using: configuration?.plugins[plugin.key]) self.plugins[plugin.key] = plugin - + if plugin.key != AWSUnifiedLoggingPlugin.key, let consolePlugin = try? self.getPlugin(for: AWSUnifiedLoggingPlugin.key) { try consolePlugin.configure(using: configuration?.plugins[consolePlugin.key]) } - + configurationState = .configured } diff --git a/Amplify/Categories/Logging/LogLevel.swift b/Amplify/Categories/Logging/LogLevel.swift index 57f92a81da..cee8acfff4 100644 --- a/Amplify/Categories/Logging/LogLevel.swift +++ b/Amplify/Categories/Logging/LogLevel.swift @@ -15,7 +15,7 @@ public extension Amplify { case debug case verbose case none - + public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let rawString = try? container.decode(String.self).lowercased() { diff --git a/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift b/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift index 8c3defed2d..082b38ee67 100644 --- a/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift +++ b/Amplify/Categories/Logging/LoggingCategory+ClientBehavior.swift @@ -37,28 +37,28 @@ extension LoggingCategory: LoggingCategoryClientBehavior { } return BroadcastLogger(targets: targets) } - + public func enable() { for plugin in plugins.values { plugin.enable() } } - + public func disable() { for plugin in plugins.values { plugin.disable() } } - + public func logger(forNamespace namespace: String) -> Logger { var targets = [Logger]() for plugin in plugins.values { targets.append(plugin.logger(forNamespace: namespace)) } return BroadcastLogger(targets: targets) - + } - + public func logger(forCategory category: String, forNamespace namespace: String) -> Logger { var targets = [Logger]() for plugin in plugins.values { diff --git a/Amplify/Categories/Logging/LoggingCategory+Logger.swift b/Amplify/Categories/Logging/LoggingCategory+Logger.swift index 33fe94b76b..29f1e95c16 100644 --- a/Amplify/Categories/Logging/LoggingCategory+Logger.swift +++ b/Amplify/Categories/Logging/LoggingCategory+Logger.swift @@ -47,7 +47,7 @@ extension LoggingCategory: Logger { for (_, plugin) in plugins { plugin.default.verbose(message()) } - + } } diff --git a/Amplify/Categories/Logging/LoggingCategory.swift b/Amplify/Categories/Logging/LoggingCategory.swift index 2aeb8c9849..b1dbd0e159 100644 --- a/Amplify/Categories/Logging/LoggingCategory.swift +++ b/Amplify/Categories/Logging/LoggingCategory.swift @@ -19,7 +19,7 @@ final public class LoggingCategory: Category { /// After a custom plugin is added and `configure` is invoked case configured } - + let lock: NSLocking = NSLock() public let categoryType = CategoryType.logging diff --git a/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift b/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift index 33525272ac..44a089635f 100644 --- a/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift +++ b/Amplify/Categories/Logging/LoggingCategoryClientBehavior.swift @@ -15,16 +15,16 @@ public protocol LoggingCategoryClientBehavior { /// Returns a category-specific logger. Defaults to using `Amplify.Logging.logLevel`. func logger(forCategory category: String) -> Logger - + /// enable plugin func enable() - + /// disable plugin func disable() - + /// adding namespace to match Android implementation func logger(forNamespace namespace: String) -> Logger - + /// new api to support category and namespace func logger(forCategory category: String, forNamespace namespace: String) -> Logger } diff --git a/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift b/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift index df0a825451..7d6da59e62 100644 --- a/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift +++ b/Amplify/Categories/Notifications/NotificationsCategoryConfiguration.swift @@ -8,7 +8,7 @@ import Foundation /// The configuration for the Notifications category -public struct NotificationsCategoryConfiguration: CategoryConfiguration { +public struct NotificationsCategoryConfiguration: CategoryConfiguration { /// Plugins public let plugins: [String: JSONValue] diff --git a/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift b/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift index c151422856..4eff36dc84 100644 --- a/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift +++ b/Amplify/Categories/Notifications/PushNotifications/PushNotificationsCategory+ClientBehaviour.swift @@ -12,15 +12,15 @@ extension PushNotificationsCategory: PushNotificationsCategoryBehaviour { public func identifyUser(userId: String, userProfile: UserProfile? = nil) async throws { try await plugin.identifyUser(userId: userId, userProfile: userProfile) } - + public func registerDevice(apnsToken: Data) async throws { try await plugin.registerDevice(apnsToken: apnsToken) } - + public func recordNotificationReceived(_ userInfo: Notifications.Push.UserInfo) async throws { try await plugin.recordNotificationReceived(userInfo) } - + #if !os(tvOS) public func recordNotificationOpened(_ response: UNNotificationResponse) async throws { try await plugin.recordNotificationOpened(response) diff --git a/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift b/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift index 652548eda6..c5639603fa 100644 --- a/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift +++ b/Amplify/Categories/Predictions/PredictionsCategoryBehavior.swift @@ -21,7 +21,6 @@ public protocol PredictionsCategoryBehavior { options: Predictions.Identify.Options? ) async throws -> Output - /// /// - Parameters: /// - request: diff --git a/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift b/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift index 896abd89c1..39f66964a0 100644 --- a/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift +++ b/Amplify/Categories/Predictions/Request/Identify/Identify+Text+Result.swift @@ -13,7 +13,7 @@ extension Predictions.Identify.Text { public let words: [Predictions.IdentifiedWord]? public let rawLineText: [String]? public let identifiedLines: [Predictions.IdentifiedLine]? - + public init( fullText: String?, words: [Predictions.IdentifiedWord]?, diff --git a/Amplify/Core/Category/CategoryType.swift b/Amplify/Core/Category/CategoryType.swift index 254c2d7a2a..9ff9c5b216 100644 --- a/Amplify/Core/Category/CategoryType.swift +++ b/Amplify/Core/Category/CategoryType.swift @@ -57,7 +57,7 @@ public enum CategoryType: String { /// /// - Tag: CategoryType.predictions case predictions - + /// Push Notifications /// /// - Tag: CategoryType.pushNotifications diff --git a/Amplify/Core/Configuration/Internal/Amplify+Reset.swift b/Amplify/Core/Configuration/Internal/Amplify+Reset.swift index 2975f75166..9a2239fe4b 100644 --- a/Amplify/Core/Configuration/Internal/Amplify+Reset.swift +++ b/Amplify/Core/Configuration/Internal/Amplify+Reset.swift @@ -51,7 +51,7 @@ extension Amplify { ModelListDecoderRegistry.reset() ModelProviderRegistry.reset() log.verbose("Resetting ModelRegistry, ModelListDecoderRegistry, ModelProviderRegistry finished") - + #if os(iOS) await MainActor.run { devMenu = nil diff --git a/Amplify/Core/Error/CoreError.swift b/Amplify/Core/Error/CoreError.swift index 623635fb5c..f6c628c764 100644 --- a/Amplify/Core/Error/CoreError.swift +++ b/Amplify/Core/Error/CoreError.swift @@ -14,7 +14,7 @@ public enum CoreError { /// /// - Tag: CoreError.listOperation case listOperation(ErrorDescription, RecoverySuggestion, Error? = nil) - + /// A client side validation error occured. /// /// - Tag: CoreError.clientValidation diff --git a/Amplify/Core/Support/Amplify+Publisher.swift b/Amplify/Core/Support/Amplify+Publisher.swift index 3fb6e9b2f5..98501d9cee 100644 --- a/Amplify/Core/Support/Amplify+Publisher.swift +++ b/Amplify/Core/Support/Amplify+Publisher.swift @@ -9,7 +9,7 @@ import Combine public extension Amplify { - + /// Get Combine Publishers for Amplify APIs. /// /// Provides static methods to create Combine Publishers from Tasks and @@ -78,7 +78,7 @@ public extension Amplify { .handleEvents(receiveCancel: { task.cancel() }) .eraseToAnyPublisher() } - + /// Create a Combine Publisher for a given AsyncSequence. /// /// Example Usage diff --git a/Amplify/Core/Support/AmplifyAsyncSequence.swift b/Amplify/Core/Support/AmplifyAsyncSequence.swift index 95b3a5b631..b98c0f17bb 100644 --- a/Amplify/Core/Support/AmplifyAsyncSequence.swift +++ b/Amplify/Core/Support/AmplifyAsyncSequence.swift @@ -13,8 +13,8 @@ public class AmplifyAsyncSequence: AsyncSequence, Cancellable public typealias Iterator = AsyncStream.Iterator private var asyncStream: AsyncStream! = nil private var continuation: AsyncStream.Continuation! = nil - private var parent: Cancellable? = nil - + private var parent: Cancellable? + public private(set) var isCancelled: Bool = false public init(parent: Cancellable? = nil, diff --git a/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift b/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift index 9ece6896b9..38772392da 100644 --- a/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift +++ b/Amplify/Core/Support/AmplifyAsyncThrowingSequence.swift @@ -13,7 +13,7 @@ public class AmplifyAsyncThrowingSequence: AsyncSequence, Can public typealias Iterator = AsyncThrowingStream.Iterator private var asyncStream: AsyncThrowingStream! = nil private var continuation: AsyncThrowingStream.Continuation! = nil - private var parent: Cancellable? = nil + private var parent: Cancellable? public private(set) var isCancelled: Bool = false diff --git a/Amplify/Core/Support/AmplifyOperation.swift b/Amplify/Core/Support/AmplifyOperation.swift index de556a597e..07d122d68c 100644 --- a/Amplify/Core/Support/AmplifyOperation.swift +++ b/Amplify/Core/Support/AmplifyOperation.swift @@ -61,7 +61,6 @@ open class AmplifyOperation.Promise! #endif - /// Creates an AmplifyOperation for the specified reequest. /// /// ## Events diff --git a/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift b/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift index ca6d173c00..fb56c6df18 100644 --- a/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift +++ b/Amplify/Core/Support/AmplifyTask+OperationTaskAdapters.swift @@ -10,10 +10,12 @@ import Foundation import Combine #endif -public class AmplifyOperationTaskAdapter: AmplifyTask { +public class AmplifyOperationTaskAdapter: AmplifyTask { let operation: AmplifyOperation let childTask: ChildTask - var resultToken: UnsubscribeToken? = nil + var resultToken: UnsubscribeToken? public init(operation: AmplifyOperation) { self.operation = operation @@ -60,7 +62,7 @@ public class AmplifyOperationTaskAdapter: AmplifyTask, AmplifyInProcessReportingTask { diff --git a/Amplify/Core/Support/AsyncSequence+forEach.swift b/Amplify/Core/Support/AsyncSequence+forEach.swift index c38279648c..6a579bad27 100644 --- a/Amplify/Core/Support/AsyncSequence+forEach.swift +++ b/Amplify/Core/Support/AsyncSequence+forEach.swift @@ -16,5 +16,5 @@ public extension AsyncSequence { try await block(element) } } - + } diff --git a/Amplify/Core/Support/AtomicDictionary.swift b/Amplify/Core/Support/AtomicDictionary.swift index 52e6f9de4c..fee9411e87 100644 --- a/Amplify/Core/Support/AtomicDictionary.swift +++ b/Amplify/Core/Support/AtomicDictionary.swift @@ -46,7 +46,7 @@ public final class AtomicDictionary { public func set(value: Value, forKey key: Key) { lock.execute { self.value[key] = value } } - + public subscript(key: Key) -> Value? { get { getValue(forKey: key) @@ -70,7 +70,7 @@ extension AtomicDictionary: ExpressibleByDictionaryLiteral { extension AtomicDictionary: Sequence { typealias Iterator = DictionaryIterator - + public func makeIterator() -> DictionaryIterator { lock.execute { value.makeIterator() diff --git a/Amplify/Core/Support/ChildTask.swift b/Amplify/Core/Support/ChildTask.swift index 63d0e7c62d..b9fa73adad 100644 --- a/Amplify/Core/Support/ChildTask.swift +++ b/Amplify/Core/Support/ChildTask.swift @@ -12,9 +12,9 @@ import Foundation actor ChildTask: BufferingSequence { typealias Element = InProcess private let parent: Cancellable - private var inProcessChannel: AmplifyAsyncSequence? = nil + private var inProcessChannel: AmplifyAsyncSequence? private var valueContinuations: [CheckedContinuation] = [] - private var storedResult: Result? = nil + private var storedResult: Result? private var isCancelled = false var inProcess: AmplifyAsyncSequence { diff --git a/Amplify/Core/Support/Fatal.swift b/Amplify/Core/Support/Fatal.swift index deee767414..fa1600351d 100644 --- a/Amplify/Core/Support/Fatal.swift +++ b/Amplify/Core/Support/Fatal.swift @@ -10,8 +10,6 @@ import Foundation // Credit: Dave DeLong // https://forums.swift.org/t/introducing-namespacing-for-common-swift-error-scenarios/10773 -import Foundation - /// An umbrella type supplying static members to handle common /// and conventional exit scenarios. public enum Fatal { diff --git a/Amplify/Core/Support/Optional+Extension.swift b/Amplify/Core/Support/Optional+Extension.swift index 0d3a6ad3c2..4efb0d736f 100644 --- a/Amplify/Core/Support/Optional+Extension.swift +++ b/Amplify/Core/Support/Optional+Extension.swift @@ -4,7 +4,6 @@ // // SPDX-License-Identifier: Apache-2.0 // - import Foundation diff --git a/Amplify/Core/Support/TaskQueue.swift b/Amplify/Core/Support/TaskQueue.swift index 687f088b8a..f281c57e1c 100644 --- a/Amplify/Core/Support/TaskQueue.swift +++ b/Amplify/Core/Support/TaskQueue.swift @@ -10,7 +10,7 @@ import Foundation /// A helper for executing asynchronous work serially. public actor TaskQueue { private var previousTask: Task? - + public init() {} /// Serializes asynchronous requests made from an async context diff --git a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift index b54dada954..7a3b10d54a 100644 --- a/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift +++ b/Amplify/DefaultPlugins/AWSHubPlugin/Internal/HubChannelDispatcher.swift @@ -122,7 +122,7 @@ final class HubDispatchOperation: Operation { guard let listeners = delegate?.listeners else { return } - + let dispatcher = SerialDispatcher(channel: channel, payload: payload) dispatcher.dispatch(to: listeners) } diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift index 643ce293d3..50f8c484ff 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/AWSUnifiedLoggingPlugin.swift @@ -29,7 +29,7 @@ final public class AWSUnifiedLoggingPlugin: LoggingCategoryPlugin { let subsystem: String var enabled: Bool = true private let lock = NSLock() - + /// Initializes the logging system with a default log, and immediately registers a default logger public init() { self.subsystem = Bundle.main.bundleIdentifier ?? "com.amazonaws.amplify.AWSUnifiedLoggingPlugin" @@ -102,7 +102,7 @@ extension AWSUnifiedLoggingPlugin { wrapper.logLevel = logLevel return wrapper } - + public func enable() { enabled = true lock.execute { @@ -111,7 +111,7 @@ extension AWSUnifiedLoggingPlugin { } } } - + public func disable() { enabled = false lock.execute { @@ -120,12 +120,12 @@ extension AWSUnifiedLoggingPlugin { } } } - + public func logger(forNamespace namespace: String) -> Logger { let wrapper = logWrapper(for: namespace) return wrapper } - + public func logger(forCategory category: String, forNamespace namespace: String) -> Logger { let wrapper = logWrapper(for: category + namespace) return wrapper diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift index 76de5e93ca..751f4a9eda 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/ConsoleLoggingConfiguration.swift @@ -11,7 +11,7 @@ public struct ConsoleLoggingConfiguration: Codable { public init(enable: Bool = true) { self.enable = enable } - + public let enable: Bool } @@ -55,8 +55,7 @@ extension ConsoleLoggingConfiguration { static func decodeConfiguration(from data: Data) throws -> ConsoleLoggingConfiguration? { do { if let configuration = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], - let configurationJson = configuration["consoleLoggingPlugin"] as? [String: Any] - { + let configurationJson = configuration["consoleLoggingPlugin"] as? [String: Any] { let decoder = JSONDecoder() let data = try JSONSerialization.data(withJSONObject: configurationJson) let consoleLoggingConfiguration = try decoder.decode(ConsoleLoggingConfiguration.self, from: data) @@ -79,4 +78,3 @@ extension ConsoleLoggingConfiguration { return nil } } - diff --git a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift index 4f5f38a417..ad3087d867 100644 --- a/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift +++ b/Amplify/DefaultPlugins/AWSUnifiedLoggingPlugin/Internal/OSLogWrapper.swift @@ -9,9 +9,9 @@ import os.log final class OSLogWrapper: Logger { private let osLog: OSLog - + var enabled: Bool = true - + var getLogLevel: () -> LogLevel public var logLevel: LogLevel { diff --git a/Amplify/DevMenu/Amplify+DevMenu.swift b/Amplify/DevMenu/Amplify+DevMenu.swift index 8a9b6bef73..856e00d815 100644 --- a/Amplify/DevMenu/Amplify+DevMenu.swift +++ b/Amplify/DevMenu/Amplify+DevMenu.swift @@ -44,8 +44,10 @@ extension Amplify { return loggingPlugin #endif } - - static func getLoggingCategoryPluginLookup(loggingPlugin: LoggingCategoryPlugin) -> [PluginKey: LoggingCategoryPlugin] { + + static func getLoggingCategoryPluginLookup( + loggingPlugin: LoggingCategoryPlugin + ) -> [PluginKey: LoggingCategoryPlugin] { #if os(iOS) #if DEBUG if isDevMenuEnabled() { diff --git a/Amplify/DevMenu/Data/PluginInfoHelper.swift b/Amplify/DevMenu/Data/PluginInfoHelper.swift index d539a7e6f3..c14d4a05e8 100644 --- a/Amplify/DevMenu/Data/PluginInfoHelper.swift +++ b/Amplify/DevMenu/Data/PluginInfoHelper.swift @@ -13,35 +13,35 @@ struct PluginInfoHelper { static func getPluginInformation() -> [PluginInfoItem] { var pluginList = [PluginInfoItem]() - + pluginList.append(contentsOf: Amplify.Analytics.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.API.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Auth.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.DataStore.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Hub.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Logging.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Predictions.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) - + pluginList.append(contentsOf: Amplify.Storage.plugins.map { makePluginInfoItem(for: $0.key, versionable: $0.value as? AmplifyVersionable) }) diff --git a/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift b/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift index 8bc0218bae..04f41016a1 100644 --- a/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift +++ b/Amplify/DevMenu/Logging/PersistentLoggingPlugin.swift @@ -27,19 +27,19 @@ public class PersistentLoggingPlugin: LoggingCategoryPlugin { public func logger(forCategory category: String) -> Logger { return plugin.logger(forCategory: category) } - + public func enable() { plugin.enable() } - + public func disable() { plugin.disable() } - + public func logger(forNamespace namespace: String) -> Logger { plugin.logger(forNamespace: namespace) } - + public func logger(forCategory category: String, forNamespace namespace: String) -> Logger { plugin.logger(forCategory: category, forNamespace: namespace) } diff --git a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift index 593e4ab047..2746528644 100644 --- a/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift +++ b/AmplifyAsyncTesting/Sources/AsyncTesting/AsyncExpectation.swift @@ -33,11 +33,11 @@ public actor AsyncExpectation { public var isFulfilled: Bool { state == .fulfilled } - + public func setShouldTrigger(_ shouldTrigger: Bool) { self.isInverted = !shouldTrigger } - + public func setExpectedFulfillmentCount(_ count: Int) { self.expectedFulfillmentCount = count } diff --git a/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift b/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift index a4bea03173..a4dbea7c0a 100644 --- a/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift +++ b/AmplifyAsyncTesting/Tests/AsyncTestingTests/AsyncTestingTests.swift @@ -86,7 +86,7 @@ final class AsyncExpectationTests: XCTestCase { let delay = 0.01 let notYetDone = asyncExpectation(description: "not yet done", isInverted: true) let done = asyncExpectation(description: "done") - + let task = Task { await AsyncRunner().run() XCTAssertTrue(Task.isCancelled) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift b/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift index 2f0a3f62d8..91d56f9763 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/API/APICategoryGraphQLBehaviorExtended.swift @@ -33,7 +33,7 @@ public protocol APICategoryGraphQLCallbackBehavior { @discardableResult func mutate(request: GraphQLRequest, listener: GraphQLOperation.ResultListener?) -> GraphQLOperation - + func subscribe(request: GraphQLRequest, valueListener: GraphQLSubscriptionOperation.InProcessListener?, completionListener: GraphQLSubscriptionOperation.ResultListener?) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift index 039215ff5f..e0aac8de36 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/AWSPluginOptions.swift @@ -16,7 +16,7 @@ public struct AWSPluginOptions { /// name of the model public let modelName: String? - + public init(authType: AWSAuthorizationType?, modelName: String?) { self.authType = authType self.modelName = modelName diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift index 1f3edd8786..cce327aed2 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthModeStrategy.swift @@ -42,7 +42,7 @@ public protocol AuthModeStrategy: AnyObject { init() func authTypesFor(schema: ModelSchema, operation: ModelOperation) async -> AWSAuthorizationTypeIterator - + func authTypesFor(schema: ModelSchema, operations: [ModelOperation]) async -> AWSAuthorizationTypeIterator } @@ -95,7 +95,7 @@ public class AWSDefaultAuthModeStrategy: AuthModeStrategy { operation: ModelOperation) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: []) } - + public func authTypesFor(schema: ModelSchema, operations: [ModelOperation]) -> AWSAuthorizationTypeIterator { return AWSAuthorizationTypeIterator(withValues: []) @@ -197,7 +197,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { operation: ModelOperation) async -> AWSAuthorizationTypeIterator { return await authTypesFor(schema: schema, operations: [operation]) } - + /// Returns the union of authorization types for the provided schema for the given list of operations /// - Parameters: /// - schema: model schema @@ -213,7 +213,7 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { } }) .sorted(by: AWSMultiAuthModeStrategy.comparator) - + // if there isn't a user signed in, returns only public or custom rules if let authDelegate = authDelegate, await !authDelegate.isUserLoggedIn() { sortedRules = sortedRules.filter { rule in @@ -225,5 +225,5 @@ public class AWSMultiAuthModeStrategy: AuthModeStrategy { } return AWSAuthorizationTypeIterator(withValues: applicableAuthTypes) } - + } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift index ab72c799a8..d0c279314c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift @@ -69,7 +69,7 @@ public class AWSAuthService: AWSAuthServiceBehavior { } return .success(convertedDictionary) } - + /// Retrieves the Cognito token from the AuthCognitoTokensProvider public func getUserPoolAccessToken() async throws -> String { let authSession = try await Amplify.Auth.fetchAuthSession() diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift index e984116ede..6c302cc928 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift @@ -17,7 +17,7 @@ public protocol AWSAuthServiceBehavior: AnyObject { /// Retrieves the identity identifier of for the Auth service func getIdentityID() async throws -> String - + /// Retrieves the token from the Auth token provider func getUserPoolAccessToken() async throws -> String } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift index 4da2777291..015f2e8395 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift @@ -46,7 +46,10 @@ public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { signatureType: .requestHeaders, signingAlgorithm: .sigv4) - let httpRequest = await AWSSigV4Signer.sigV4SignedRequest(requestBuilder: requestBuilder, signingConfig: signingConfig) + let httpRequest = await AWSSigV4Signer.sigV4SignedRequest( + requestBuilder: requestBuilder, + signingConfig: signingConfig + ) return httpRequest } catch let error { throw AuthError.unknown("Unable to sign request", error) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift index b6fe5442e2..4c79d1d77b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AuthTokenProvider.swift @@ -19,7 +19,7 @@ public struct BasicUserPoolTokenProvider: AuthTokenProvider { public init(authService: AWSAuthServiceBehavior) { self.authService = authService } - + public func getUserPoolAccessToken() async throws -> String { try await authService.getUserPoolAccessToken() } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift index e28e26067e..cbacba2e44 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStore.swift @@ -17,14 +17,14 @@ public protocol KeychainStoreBehavior { /// - Parameter key: A String key use to look up the value in the Keychain /// - Returns: A string value func _getString(_ key: String) throws -> String - + @_spi(KeychainStore) /// Get a data value from the Keychain based on the key. /// This System Programming Interface (SPI) may have breaking changes in future updates. /// - Parameter key: A String key use to look up the value in the Keychain /// - Returns: A data value func _getData(_ key: String) throws -> Data - + @_spi(KeychainStore) /// Set a key-value pair in the Keychain. /// This System Programming Interface (SPI) may have breaking changes in future updates. @@ -32,7 +32,7 @@ public protocol KeychainStoreBehavior { /// - value: A string value to store in Keychain /// - key: A String key for the value to store in the Keychain func _set(_ value: String, key: String) throws - + @_spi(KeychainStore) /// Set a key-value pair in the Keychain. /// This iSystem Programming Interface (SPI) may have breaking changes in future updates. @@ -40,13 +40,13 @@ public protocol KeychainStoreBehavior { /// - value: A data value to store in Keychain /// - key: A String key for the value to store in the Keychain func _set(_ value: Data, key: String) throws - + @_spi(KeychainStore) /// Remove key-value pair from Keychain based on the provided key. /// This System Programming Interface (SPI) may have breaking changes in future updates. /// - Parameter key: A String key to delete the key-value pair func _remove(_ key: String) throws - + @_spi(KeychainStore) /// Removes all key-value pair in the Keychain. /// This System Programming Interface (SPI) may have breaking changes in future updates. @@ -188,7 +188,7 @@ public struct KeychainStore: KeychainStoreBehavior { throw KeychainStoreError.securityError(status) } } - + @_spi(KeychainStore) /// Removes all key-value pair in the Keychain. /// This System Programming Interface (SPI) may have breaking changes in future updates. @@ -220,7 +220,7 @@ extension KeychainStore { static let AttributeLabel = String(kSecAttrLabel) static let AttributeComment = String(kSecAttrComment) static let AttributeAccessible = String(kSecAttrAccessible) - + /** Attribute Accessible Constants */ static let AttributeAccessibleAfterFirstUnlockThisDeviceOnly = String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) @@ -235,7 +235,7 @@ extension KeychainStore { /** Value Type Key Constants */ static let ValueData = String(kSecValueData) - + /** Indicates whether to treat macOS keychain items like iOS keychain items without setting kSecAttrSynchronizable */ static let UseDataProtectionKeyChain = String(kSecUseDataProtectionKeychain) } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift index 5d81c8b8d1..a638b2879b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreAttributes.swift @@ -12,7 +12,7 @@ struct KeychainStoreAttributes { var itemClass: String = KeychainStore.Constants.ClassGenericPassword var service: String var accessGroup: String? - + } extension KeychainStoreAttributes { @@ -23,7 +23,7 @@ extension KeychainStoreAttributes { KeychainStore.Constants.AttributeService: service, KeychainStore.Constants.UseDataProtectionKeyChain: kCFBooleanTrue ] - + if let accessGroup = accessGroup { query[KeychainStore.Constants.AttributeAccessGroup] = accessGroup } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift index 6ceda508b4..4de28d4697 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Keychain/KeychainStoreError.swift @@ -78,7 +78,7 @@ extension KeychainStoreError: AmplifyError { } return """ To use Auth in a macOS project, you'll need to enable the Keychain Sharing capability. - This capability is required because Auth uses the Data Protection Keychain on macOS as + This capability is required because Auth uses the Data Protection Keychain on macOS as a platform best practice. See TN3137: macOS keychain APIs and implementations for more information on how Keychain works on macOS and the Keychain Sharing entitlement. For more information on adding capabilities to your application, see Xcode Capabilities. diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift index 4c70689a10..0cf0f79d04 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/AuthRuleDecorator.swift @@ -198,7 +198,7 @@ private extension AuthRules { return authType == provider.toAWSAuthorizationType() } } - + func filterBy(ownerFieldType: ModelFieldType, modelSchema: ModelSchema) -> AuthRules { return filter { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift index f32276e2e6..7d17b01e57 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ConflictResolutionDecorator.swift @@ -18,7 +18,7 @@ public struct ConflictResolutionDecorator: ModelBasedGraphQLDocumentDecorator { private let lastSync: Int64? private let graphQLType: GraphQLOperationType private var primaryKeysOnly: Bool - + public init(version: Int? = nil, lastSync: Int64? = nil, graphQLType: GraphQLOperationType, diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift index 3a42420f98..7a7ef66cfb 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelDecorator.swift @@ -15,7 +15,7 @@ public struct ModelDecorator: ModelBasedGraphQLDocumentDecorator { private let model: Model private let mutationType: GraphQLMutationType - + public init(model: Model, mutationType: GraphQLMutationType) { self.model = model self.mutationType = mutationType diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift index fb23beb1c1..07a9a2d523 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Decorator/ModelIdDecorator.swift @@ -14,7 +14,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { private var identifierFields = [(name: String, value: GraphQLDocumentValueRepresentable, type: String)]() public init(model: Model, schema: ModelSchema) { - + var firstField = true self.identifierFields = model.identifier(schema: schema).fields.compactMap { fieldName, _ in guard let value = model.graphQLInputForPrimaryKey(modelFieldName: fieldName, @@ -29,7 +29,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { } } } - + public init(identifierFields: [(name: String, value: Persistable)]) { var firstField = true identifierFields.forEach { name, value in @@ -37,7 +37,7 @@ public struct ModelIdDecorator: ModelBasedGraphQLDocumentDecorator { firstField = false } } - + public init(identifiers: [LazyReferenceIdentifier]) { var firstField = true identifiers.forEach({ identifier in diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift index 0b89ba83e6..2f86d9cb44 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/GraphQLQuery.swift @@ -20,7 +20,7 @@ public struct GraphQLQuery: SingleDirectiveGraphQLDocument { self.inputs = inputs self.selectionSet = selectionSet } - + @available(*, deprecated, message: """ Init with modelType is deprecated, use init with modelSchema instead. """) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift index be0558530b..a737d57d2f 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLDocument/ModelBasedGraphQLDocumentBuilder.swift @@ -36,7 +36,7 @@ public struct ModelBasedGraphQLDocumentBuilder { if primaryKeysOnly && ModelRegistry.modelType(from: modelSchema.name)?.rootPath == nil { primaryKeysOnly = false } - + switch operationType { case .query: self.document = GraphQLQuery(modelSchema: modelSchema, primaryKeysOnly: primaryKeysOnly) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift index b779199e53..cdc367dde3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+AnyModelWithSync.swift @@ -44,7 +44,7 @@ protocol ModelSyncGraphQLRequestFactory { subscriptionType: GraphQLSubscriptionType, claims: IdentityClaimsDictionary, authType: AWSAuthorizationType?) -> GraphQLRequest - + static func syncQuery(modelSchema: ModelSchema, where predicate: QueryPredicate?, limit: Int?, @@ -210,7 +210,7 @@ extension GraphQLRequest: ModelSyncGraphQLRequestFactory { decodePath: document.name, options: requestOptions) } - + public static func syncQuery(modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, limit: Int? = nil, diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift index 6e55f0d929..7229c4ea1b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/GraphQLRequest/GraphQLRequest+Model.swift @@ -56,12 +56,12 @@ protocol ModelGraphQLRequestFactory { byIdentifier id: String, includes: IncludedAssociations) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default - + static func get(_ modelType: M.Type, byIdentifier id: ModelIdentifier, includes: IncludedAssociations) -> GraphQLRequest where M: ModelIdentifiable - + // MARK: Mutation /// Creates a `GraphQLRequest` that represents a mutation of a given `type` for a `model` instance. @@ -181,7 +181,7 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { type: GraphQLMutationType) -> GraphQLRequest { mutation(of: model, modelSchema: model.schema, where: predicate, includes: includes, type: type) } - + public static func mutation(of model: M, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, @@ -190,12 +190,12 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelSchema, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: type)) - + if let modelPath = M.rootPath as? ModelPath { let associations = includes(modelPath) documentBuilder.add(decorator: IncludeAssociationDecorator(associations)) } - + switch type { case .create: documentBuilder.add(decorator: ModelDecorator(model: model, mutationType: type)) @@ -239,14 +239,14 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { responseType: M?.self, decodePath: document.name) } - + public static func get(_ modelType: M.Type, byIdentifier id: String, includes: IncludedAssociations = { _ in [] }) -> GraphQLRequest where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { return .get(modelType, byId: id, includes: includes) } - + public static func get(_ modelType: M.Type, byIdentifier id: ModelIdentifier, includes: IncludedAssociations = { _ in [] }) -> GraphQLRequest @@ -254,20 +254,20 @@ extension GraphQLRequest: ModelGraphQLRequestFactory { var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) - + if let modelPath = modelType.rootPath as? ModelPath { let associations = includes(modelPath) documentBuilder.add(decorator: IncludeAssociationDecorator(associations)) } documentBuilder.add(decorator: ModelIdDecorator(identifierFields: id.fields)) let document = documentBuilder.build() - + return GraphQLRequest(document: document.stringValue, variables: document.variables, responseType: M?.self, decodePath: document.name) } - + public static func list(_ modelType: M.Type, where predicate: QueryPredicate? = nil, includes: IncludedAssociations = { _ in [] }, diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift index 18acdaa684..2e4c075b2c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/Model+GraphQL.swift @@ -39,7 +39,7 @@ extension Model { for (modelField, modelFieldValue) in fields { let name = modelField.name - + guard let value = modelFieldValue else { // Scenario: When there is no model field value, set `nil` for removal of values or deassociation. // 1. It is unnessessary to set `nil` values for create mutations. @@ -68,7 +68,7 @@ extension Model { // 3. Set field values to `nil` for removal of values. input.updateValue(nil, forKey: name) } - + continue } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift index 61ab94efe8..b926808de4 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/SelectionSet.swift @@ -56,14 +56,14 @@ extension SelectionSet { if field._isBelongsToOrHasOne { recursive = false } - + let child = SelectionSet(value: .init(name: field.name, fieldType: .model)) if primaryKeysOnly { child.withModelFields(schema.primaryKey.fields, recursive: recursive, primaryKeysOnly: primaryKeysOnly) } else { child.withModelFields(schema.graphQLFields, recursive: recursive, primaryKeysOnly: primaryKeysOnly) } - + self.addChild(settingParentOf: child) } } else { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift index bcecd4e60e..d6723f4835 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/ModelSync/ModelSyncMetadata.swift @@ -13,7 +13,7 @@ public struct ModelSyncMetadata: Model { /// The timestamp (in Unix seconds) at which the last sync was started, as reported by the service public var lastSync: Int64? - + /// The sync predicate for this model, extracted out from the sync expression. public var syncPredicate: String? diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift index 9ddac1677d..718e3348f6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Sync/MutationSync/MutationSyncMetadata+Schema.swift @@ -37,7 +37,6 @@ extension MutationSyncMetadata { } } - extension MutationSyncMetadata: ModelIdentifiable { public typealias IdentifierProtocol = ModelIdentifier public typealias IdentifierFormat = ModelIdentifierFormat.Default diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift index f779aa7fbe..6ba1ab83aa 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift @@ -23,4 +23,3 @@ public func baseClientEngine( #endif return baseClientEngine } - diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift index 863fa636bf..49c3adf55b 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift @@ -10,7 +10,7 @@ import ClientRuntime @_spi(InternalAmplifyPluginExtension) public class UserAgentSuffixAppender: AWSPluginExtension { @_spi(InternalHttpEngineProxy) - public var target: HttpClientEngine? = nil + public var target: HttpClientEngine? public let suffix: String private let userAgentKey = "User-Agent" diff --git a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift index 8c5d7cfa62..d0d87929a9 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift @@ -42,7 +42,7 @@ public class MockAWSAuthService: AWSAuthServiceBehavior { return identityId ?? "IdentityId" } - + public func getUserPoolAccessToken() async throws -> String { interactions.append(#function) if let error = getTokenError { From 09403e56fd43b80484e476b2786e21cb3e4842b3 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Tue, 2 Jan 2024 10:22:37 -0600 Subject: [PATCH 3/5] chore: resolve swiftlint warnings --- .../AWSAPIPlugin+GraphQLBehavior.swift | 6 ++--- .../AWSAPIPlugin+RESTBehavior.swift | 12 ++++----- .../Core/AppSyncListDecoder.swift | 4 +-- .../Core/AppSyncListProvider.swift | 25 +++++++++---------- .../Core/AppSyncModelDecoder.swift | 12 ++++----- .../Core/AppSyncModelMetadata.swift | 24 +++++++++--------- .../Core/AppSyncModelProvider.swift | 18 ++++++------- .../AuthTokenProviderWrapper.swift | 2 +- .../AuthTokenURLRequestInterceptor.swift | 8 +++--- .../IAMURLRequestInterceptor.swift | 2 +- .../Operation/AWSGraphQLOperation.swift | 3 +-- .../AWSGraphQLSubscriptionTaskRunner.swift | 18 ++++++------- .../Operation/AWSHTTPURLResponse.swift | 2 +- .../Reachability/AmplifyReachability.swift | 2 +- .../AmplifyRechability+watchOS.swift | 24 +++++++++--------- .../GraphQLResponseDecoder+DecodeData.swift | 6 ++--- .../Utils/GraphQLRequest+toListQuery.swift | 6 ++--- .../Support/Utils/Result+Async.swift | 2 +- 18 files changed, 87 insertions(+), 89 deletions(-) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift index 002cba23a1..6948f9195d 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+GraphQLBehavior.swift @@ -19,7 +19,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func query(request: GraphQLRequest) async throws -> GraphQLTask.Success { let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .query), session: session, @@ -41,7 +41,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func mutate(request: GraphQLRequest) async throws -> GraphQLTask.Success { let operation = AWSGraphQLOperation(request: request.toOperationRequest(operationType: .mutation), session: session, @@ -69,7 +69,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func subscribe(request: GraphQLRequest) -> AmplifyAsyncThrowingSequence> { let request = request.toOperationRequest(operationType: .subscription) let runner = AWSGraphQLSubscriptionTaskRunner(request: request, diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift index c60ce3e017..59642d79c0 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/AWSAPIPlugin+RESTBehavior.swift @@ -23,7 +23,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func get(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .get) @@ -52,7 +52,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func put(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .put) @@ -81,7 +81,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func post(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .post) @@ -109,7 +109,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func patch(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .patch) @@ -137,7 +137,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func delete(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .delete) @@ -166,7 +166,7 @@ public extension AWSAPIPlugin { queue.addOperation(operation) return operation } - + func head(request: RESTRequest) async throws -> RESTTask.Success { let operationRequest = RESTOperationRequest(request: request, operationType: .head) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift index 605b9d50ba..c6050bb2d7 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListDecoder.swift @@ -19,13 +19,13 @@ public struct AppSyncListDecoder: ModelListDecoder { let appSyncAssociatedFields: [String] let apiName: String? } - + /// Used by the custom decoder implemented in the `List` type to detect if the payload can be /// decoded to an AppSyncListProvider. public static func decode(modelType: ModelType.Type, decoder: Decoder) -> AnyModelListProvider? { self.shouldDecodeToAppSyncListProvider(modelType: modelType, decoder: decoder)?.eraseToAnyModelListProvider() } - + static func shouldDecodeToAppSyncListProvider(modelType: ModelType.Type, decoder: Decoder) -> AppSyncListProvider? { if let listPayload = try? AppSyncListPayload.init(from: decoder) { log.verbose("Creating loaded list of \(modelType.modelName)") diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift index 88388999ab..2edf147c1b 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncListProvider.swift @@ -92,7 +92,7 @@ public class AppSyncListProvider: ModelListProvider { return .loaded(elements) } } - + public func load() async throws -> [Element] { switch loadedState { case .loaded(let elements, _, _): @@ -101,7 +101,7 @@ public class AppSyncListProvider: ModelListProvider { return try await load(associatedIdentifiers: associatedIdentifiers, associatedFields: associatedFields) } } - + //// Internal `load` to perform the retrieval of the first page and storing it in memory func load(associatedIdentifiers: [String], associatedFields: [String]) async throws -> [Element] { @@ -113,7 +113,7 @@ public class AppSyncListProvider: ModelListProvider { filter = predicate.graphQLFilter(for: Element.schema) } else { var queryPredicates: [QueryPredicateOperation] = [] - + let columnNames = columnNames(fields: associatedFields, Element.schema) let predicateValues = zip(columnNames, associatedIdentifiers) for (identifierName, identifierValue) in predicateValues { @@ -123,8 +123,7 @@ public class AppSyncListProvider: ModelListProvider { let groupedQueryPredicates = QueryPredicateGroup(type: .and, predicates: queryPredicates) filter = groupedQueryPredicates.graphQLFilter(for: Element.schema) } - - + let request = GraphQLRequest.listQuery(responseType: JSONValue.self, modelSchema: Element.schema, filter: filter, @@ -142,7 +141,7 @@ public class AppSyncListProvider: ModelListProvider { AWSAppSyncListResponse from: \(graphQLData) """, "", nil) } - + self.loadedState = .loaded(elements: listResponse.items, nextToken: listResponse.nextToken, filter: filter) @@ -163,7 +162,7 @@ public class AppSyncListProvider: ModelListProvider { throw error } } - + public func hasNextPage() -> Bool { switch loadedState { case .loaded(_, let nextToken, _): @@ -172,7 +171,7 @@ public class AppSyncListProvider: ModelListProvider { return false } } - + public func getNextPage() async throws -> List { guard case .loaded(_, let nextTokenOptional, let filter) = loadedState else { throw CoreError.clientValidation(""" @@ -219,7 +218,7 @@ public class AppSyncListProvider: ModelListProvider { throw error } } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let associatedIdentifiers, let associatedFields): @@ -239,9 +238,9 @@ public class AppSyncListProvider: ModelListProvider { try elements.encode(to: encoder) } } - + // MARK: - Helpers - + /// Retrieve the column names for the specified field `field` for this schema. func columnNames(fields: [String], _ modelSchema: ModelSchema) -> [String] { // Associated field names have already been resolved from the parent model's has-many targetNames @@ -257,14 +256,14 @@ public class AppSyncListProvider: ModelListProvider { case .belongsTo(_, let targetNames), .hasOne(_, let targetNames): guard !targetNames.isEmpty else { return [defaultFieldName] - + } return targetNames default: return fields } } - + } extension AppSyncListProvider: DefaultLogger { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift index fd6b1f22e2..9fc1da75b7 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelDecoder.swift @@ -12,22 +12,22 @@ import Amplify /// inside an `AppSyncModelProvider` when decoding to the `LazyReference` as a "not yet loaded" Reference. If the data payload /// can be decoded to the Model, then the model provider is created as a "loaded" reference. public struct AppSyncModelDecoder: ModelProviderDecoder { - + public static let AppSyncSource = "AppSync" - + /// Metadata that contains metadata of a model, specifically the identifiers used to hydrate the model. struct Metadata: Codable { let identifiers: [LazyReferenceIdentifier] let apiName: String? let source: String - + init(identifiers: [LazyReferenceIdentifier], apiName: String?, source: String = AppSyncSource) { self.identifiers = identifiers self.apiName = apiName self.source = source } } - + public static func decode(modelType: ModelType.Type, decoder: Decoder) -> AnyModelProvider? { if let metadata = try? Metadata(from: decoder) { if metadata.source == AppSyncSource { @@ -37,12 +37,12 @@ public struct AppSyncModelDecoder: ModelProviderDecoder { return nil } } - + if let model = try? ModelType.init(from: decoder) { log.verbose("Creating loaded model \(model)") return AppSyncModelProvider(model: model).eraseToAnyModelProvider() } - + return nil } } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift index b929e77eb6..31cb93303a 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelMetadata.swift @@ -10,7 +10,7 @@ import Foundation /// Holds the methods to traverse and maniupulate the response data object by injecting public struct AppSyncModelMetadataUtils { - + // A fairly light check to make sure the payload is an object and we have the schema for `addMetadata`. // Note: `addMetadata` should be very tightly checking the associated fields to determine when it should add // metadata. Do we still need to do this anymore? @@ -65,12 +65,12 @@ public struct AppSyncModelMetadataUtils { encoder.dateEncodingStrategy = ModelDateFormatting.encodingStrategy let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy - + // Iterate over the associations of the model and for each association, either create the identifier metadata // for lazy loading belongs-to or create the model association metadata for lazy loading has-many. // The metadata gets decoded to the LazyReference and List implementations respectively. for modelField in modelSchema.fields.values { - + // Scenario: Belongs-to associations. For the current `modelField` that is a belongs-to association, // retrieve the data and attempt to decode to the association's modelType. If it can be decoded, // this means it is eager loaded and does not need to be lazy loaded. If it cannot, extract the @@ -81,7 +81,7 @@ public struct AppSyncModelMetadataUtils { case .object(let modelObject) = nestedModelJSON, let associatedModelName = modelField.associatedModelName, let associatedModelType = ModelRegistry.modelType(from: associatedModelName) { - + // Scenario: Belongs-To Primary Keys only are available for lazy loading if let modelIdentifierMetadata = createModelIdentifierMetadata(associatedModelType, modelObject: modelObject, @@ -105,11 +105,11 @@ public struct AppSyncModelMetadataUtils { } // otherwise do nothing to the data. } - + // Scenario: Has-Many eager loaded or empty payloads. if modelField.isArray && modelField.hasAssociation, let associatedModelName = modelField.associatedModelName { - + // Scenario: Has-many items array is missing. // Store the association data (parent's identifier and field name) // This allows the list to perform lazy loading of child items using parent identifier as the predicate @@ -127,7 +127,7 @@ public struct AppSyncModelMetadataUtils { """) } } - + // Scenario: Has-Many items array is eager loaded as `nestedModelJSON` // If the model types allow for lazy loading, inject the metadata at each item of `nestedModelJSON` else if let nestedModelJSON = modelJSON[modelField.name], @@ -135,17 +135,17 @@ public struct AppSyncModelMetadataUtils { case .array(var graphQLDataArray) = graphQLDataObject["items"], let associatedModelType = ModelRegistry.modelType(from: associatedModelName), associatedModelType.rootPath != nil { - + for (index, item) in graphQLDataArray.enumerated() { let modelJSON = AppSyncModelMetadataUtils.addMetadata(toModel: item, apiName: apiName) graphQLDataArray[index] = modelJSON } - + graphQLDataObject["items"] = JSONValue.array(graphQLDataArray) let payload = AppSyncListPayload(graphQLData: JSONValue.object(graphQLDataObject), apiName: apiName, variables: nil) - + if let serializedPayload = try? encoder.encode(payload), let payloadJSON = try? decoder.decode(JSONValue.self, from: serializedPayload) { log.verbose("Adding [\(modelField.name): \(payloadJSON)]") @@ -159,7 +159,7 @@ public struct AppSyncModelMetadataUtils { return JSONValue.object(modelJSON) } - + /// Extract the identifiers from the `modelObject`. The number of identifiers extracted compared to the number of /// fields on the `modelObject` is useful determining if the `modelOject` is eager or lazy loaded. If the identifiers /// plus one additional field (`__typename`) doesn't match the number of keys on the `modelObject` then there @@ -185,7 +185,7 @@ public struct AppSyncModelMetadataUtils { return nil } } - + /// Retrieve just the identifiers from the current model. These identifiers are later used /// for creating `AppSyncListDecoder.Metadata` payloads for decoding. static func retrieveIdentifiers(_ modelJSON: [String: JSONValue], _ schema: ModelSchema) -> [String]? { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift index f71f08194e..ed717eec64 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Core/AppSyncModelProvider.swift @@ -10,27 +10,27 @@ import Amplify import AWSPluginsCore public class AppSyncModelProvider: ModelProvider { - + let apiName: String? - + var loadedState: ModelProviderState - + // Creates a "not loaded" provider init(metadata: AppSyncModelDecoder.Metadata) { self.loadedState = .notLoaded(identifiers: metadata.identifiers) self.apiName = metadata.apiName } - + // Creates a "loaded" provider init(model: ModelType?) { self.loadedState = .loaded(model: model) self.apiName = nil } - + // MARK: - APIs - + public func load() async throws -> ModelType? { - + switch loadedState { case .notLoaded(let identifiers): guard let identifiers = identifiers else { @@ -54,11 +54,11 @@ public class AppSyncModelProvider: ModelProvider { return element } } - + public func getState() -> ModelProviderState { loadedState } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let identifiers): diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift index 6be2ea5a5d..bc5be0d627 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenProviderWrapper.swift @@ -16,7 +16,7 @@ class AuthTokenProviderWrapper: AuthTokenProvider { init(tokenAuthProvider: AmplifyAuthTokenProvider) { self.wrappedAuthTokenProvider = tokenAuthProvider } - + func getUserPoolAccessToken() async throws -> String { try await wrappedAuthTokenProvider.getLatestAuthToken() } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift index 2d639afca4..a0b33d5825 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift @@ -10,9 +10,9 @@ import AWSPluginsCore import Foundation struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { - + static let AWSDateISO8601DateFormat2 = "yyyyMMdd'T'HHmmss'Z'" - + private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib let authTokenProvider: AuthTokenProvider @@ -34,14 +34,14 @@ struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { forHTTPHeaderField: URLRequestConstants.Header.xAmzDate) mutableRequest.addValue(userAgent, forHTTPHeaderField: URLRequestConstants.Header.userAgent) - + let token: String do { token = try await authTokenProvider.getUserPoolAccessToken() } catch { throw APIError.operationError("Failed to retrieve authorization token.", "", error) } - + mutableRequest.setValue(token, forHTTPHeaderField: "authorization") return mutableRequest as URLRequest } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift index 4ad5159992..d012985a63 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift @@ -17,7 +17,7 @@ struct IAMURLRequestInterceptor: URLRequestInterceptor { let region: AWSRegionType let endpointType: AWSAPICategoryPluginEndpointType private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib - + init(iamCredentialsProvider: IAMCredentialsProvider, region: AWSRegionType, endpointType: AWSAPICategoryPluginEndpointType) { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift index 859981e321..a6115ff171 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLOperation.swift @@ -154,8 +154,7 @@ final public class AWSGraphQLOperation: GraphQLOperation { getEndpointConfig(from: request).flatMap { endpointConfig in do { if let pluginOptions = request.options.pluginOptions as? AWSPluginOptions, - let authType = pluginOptions.authType - { + let authType = pluginOptions.authType { return .success(try pluginConfig.interceptorsForEndpoint( withConfig: endpointConfig, authType: authType diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift index a9bf16eee9..b8e42644cc 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift @@ -16,7 +16,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, public var request: GraphQLOperationRequest public var context = InternalTaskAsyncThrowingSequenceContext>() - + let pluginConfig: AWSAPICategoryPluginConfiguration let subscriptionConnectionFactory: SubscriptionConnectionFactory let authService: AWSAuthServiceBehavior @@ -28,7 +28,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, private var running = false private let subscriptionQueue = DispatchQueue(label: "AWSGraphQLSubscriptionOperation.subscriptionQueue") - + init(request: Request, pluginConfig: AWSAPICategoryPluginConfiguration, subscriptionConnectionFactory: SubscriptionConnectionFactory, @@ -40,7 +40,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, self.authService = authService self.apiAuthProviderFactory = apiAuthProviderFactory } - + public func cancel() { subscriptionQueue.sync { if let subscriptionItem = subscriptionItem, let subscriptionConnection = subscriptionConnection { @@ -50,7 +50,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, } } } - + public func run() async throws { guard !running else { return } running = true @@ -116,9 +116,9 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, urlRequest.setValue(userAgent, forHTTPHeaderField: URLRequestConstants.Header.userAgent) return urlRequest } - + // MARK: - Subscription callbacks - + private func onAsyncSubscriptionEvent(event: SubscriptionItemEvent) { switch event { case .connection(let subscriptionConnectionEvent): @@ -166,7 +166,7 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, // payload is the right thing to do. Another option would be to propagate a GraphQL error, but // leave the subscription alive. // see https://github.com/aws-amplify/amplify-swift/issues/2577 - + fail(APIError.operationError("Failed to deserialize", "", error)) } } @@ -204,7 +204,7 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri let subscriptionConnectionFactory: SubscriptionConnectionFactory let authService: AWSAuthServiceBehavior private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib - + var subscriptionConnection: SubscriptionConnection? var subscriptionItem: SubscriptionItem? var apiAuthProviderFactory: APIAuthProviderFactory @@ -318,7 +318,7 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri } // MARK: - Subscription callbacks - + private func onAsyncSubscriptionEvent(event: SubscriptionItemEvent) { switch event { case .connection(let subscriptionConnectionEvent): diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift index 68c55eadc6..bb4a87396d 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSHTTPURLResponse.swift @@ -52,7 +52,7 @@ public class AWSHTTPURLResponse: HTTPURLResponse { public override class var supportsSecureCoding: Bool { return true } - + public override func encode(with coder: NSCoder) { coder.encode(body, forKey: "body") coder.encode(response, forKey: "response") diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift index 3dfcfe25ae..9045d31e03 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyReachability.swift @@ -177,7 +177,7 @@ public extension AmplifyReachability { func startNotifier() throws { guard !notifierRunning else { return } - let callback: SCNetworkReachabilityCallBack = { reachability, flags, info in + let callback: SCNetworkReachabilityCallBack = { _, flags, info in guard let info = info else { return } // `weakifiedReachability` is guaranteed to exist by virtue of our diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift index 99195734fe..c5bf5e5dc9 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Reachability/AmplifyRechability+watchOS.swift @@ -20,31 +20,31 @@ import Network public class AmplifyReachability { public var allowsCellularConnection: Bool - + // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default - + public var connection: AmplifyReachability.Connection { guard networkReachability.currentPath.status != .unsatisfied else { return .unavailable } - + // If we're reachable but not running on a device, we must be in Wi-Fi if !isRunningOnDevice { return .wifi } - + if networkReachability.currentPath.usesInterfaceType(.wifi) { return .wifi } - + if networkReachability.currentPath.usesInterfaceType(.cellular) { return allowsCellularConnection ? .cellular : .unavailable } - + return .unavailable } - + private let networkReachability: NWPathMonitor private let notificationQueue: DispatchQueue private var isRunningOnDevice: Bool = { @@ -54,7 +54,7 @@ public class AmplifyReachability { return true #endif }() - + public init( networkReachability: NWPathMonitor = NWPathMonitor(), allowsCellularConnection: Bool = true, @@ -73,22 +73,22 @@ public class AmplifyReachability { ) self.notificationQueue = notificationQueue } - + deinit { stopNotifier() } - + // MARK: - *** Notifier methods *** public func startNotifier() throws { guard networkReachability.pathUpdateHandler == nil else { return } - networkReachability.pathUpdateHandler = { [weak self] path in + networkReachability.pathUpdateHandler = { [weak self] _ in guard let self = self else { return } self.notificationQueue.async { self.notificationCenter.post(name: .reachabilityChanged, object: self) } } } - + public func stopNotifier() { networkReachability.pathUpdateHandler = nil } diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift index 57af2aa6fb..bfaf333a7f 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Decode/GraphQLResponseDecoder+DecodeData.swift @@ -10,7 +10,7 @@ import AWSPluginsCore import Foundation extension GraphQLResponseDecoder { - + /* The sequence of `responseType` checking attempts to decode to specific types before falling back to (5) serializing the data and letting the default decode run its course (6). @@ -39,7 +39,7 @@ extension GraphQLResponseDecoder { graphQLData = graphQLDataWithTypeName } let serializedJSON: Data - + if request.responseType == AnyModel.self { // 2 let anyModel = try AnyModel(modelJSON: graphQLData) serializedJSON = try encoder.encode(anyModel) @@ -89,7 +89,7 @@ extension GraphQLResponseDecoder { let variablesData = try JSONSerialization.data(withJSONObject: variables) return try decoder.decode([String: JSONValue].self, from: variablesData) } - + // The Swift DataStore plugin has a dependency on using `__typename` from the response data. // For example, DataStore will use the type `MutationSync` to decode the model with sync metadata by // pulling out the modelName from `__typename` and use that to decode to the actual model type. diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift index 58c6bae833..130e3d4167 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/GraphQLRequest+toListQuery.swift @@ -31,7 +31,7 @@ extension GraphQLRequest { responseType: responseType.self, decodePath: document.name) } - + static func getRequest(_ modelType: M.Type, byIdentifiers identifiers: [LazyReferenceIdentifier], apiName: String?) -> GraphQLRequest { @@ -39,9 +39,9 @@ extension GraphQLRequest { operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(identifiers: identifiers)) - + let document = documentBuilder.build() - + return GraphQLRequest(apiName: apiName, document: document.stringValue, variables: document.variables, diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift index fbf204c971..1b145420f0 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Support/Utils/Result+Async.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // - import Foundation extension Result { + // swiftlint:disable:next identifier_name func flatMapAsync(_ f: (Success) async -> Result) async -> Result { switch self { case .success(let value): From bb692b04bfa36d7524a7346fa1e40d82eb7088de Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Tue, 2 Jan 2024 11:10:10 -0600 Subject: [PATCH 4/5] chore: resolve swiftlint errors and warnings --- .../AWSCognitoAuthPlugin+Configure.swift | 4 ++-- .../AWSCognitoAuthPlugin+PluginSpecificAPI.swift | 2 +- .../InitializeAuthConfiguration.swift | 6 ++---- .../MigrateLegacyCredentialStore.swift | 4 +++- .../InformUserDeletedAndSignedOut.swift | 2 +- .../InformSessionError.swift | 2 +- .../InformSessionFetched.swift | 2 +- .../InitializeFetchAuthSessionWithUserPool.swift | 2 +- .../InitializeFetchUnAuthSession.swift | 2 +- .../PersistCredentials.swift | 2 +- .../InformSessionRefreshed.swift | 2 +- .../InitializeRefreshSession.swift | 2 +- .../UserPool/RefreshHostedUITokens.swift | 2 +- .../UserPool/RefreshUserPoolTokens.swift | 2 +- .../SignIn/CustomSignIn/InitiateCustomAuth.swift | 2 +- .../DeviceSRPAuth/InitiateAuthDeviceSRP.swift | 7 +++++-- .../VerifyDevicePasswordSRP+Calculations.swift | 2 ++ .../DeviceSRPAuth/VerifyDevicePasswordSRP.swift | 2 +- .../Actions/SignIn/IntializeSignInFlow.swift | 2 +- .../SignIn/MigrateAuth/InitiateMigrateAuth.swift | 2 +- .../Actions/SignIn/SRPAuth/CancelSignIn.swift | 2 +- .../Actions/SignIn/SRPAuth/InitiateAuthSRP.swift | 2 +- .../SignIn/SRPAuth/ThrowSignInError.swift | 2 +- .../SRPAuth/VerifyPasswordSRP+Calculations.swift | 2 ++ .../SignIn/SRPAuth/VerifyPasswordSRP.swift | 2 +- .../AWSCognitoAuthPlugin+ClientBehavior.swift | 5 +++-- .../AWSCognitoAuthPlugin+DeviceBehavior.swift | 8 +++++--- .../AWSCognitoAuthPlugin+UserBehavior.swift | 8 +++++++- .../HubEvents/AuthHubEventHandler.swift | 2 +- .../Models/AWSCognitoUserPoolTokens.swift | 4 +++- .../Models/MFAPreference.swift | 2 +- .../AWSAuthConfirmResetPasswordOptions.swift | 1 - .../Models/UserMFAPreference.swift | 5 ----- .../FetchAuthSessionOperationHelper.swift | 4 +--- .../Helpers/HostedUISignInHelper.swift | 5 ++--- .../SRP/AmplifySRPClient.swift | 5 +++-- ...AWSCognitoIdentity+AuthErrorConvertible.swift | 1 - ...toIdentityProvider+AuthErrorConvertible.swift | 7 ------- .../CodeGen/Data/HostedUIConfigurationData.swift | 10 ---------- .../Data/IdentityPoolConfigurationData.swift | 6 ------ .../CodeGen/Data/RespondToAuthChallenge.swift | 2 +- .../StateMachine/CodeGen/Data/SRPStateData.swift | 16 ---------------- .../CodeGen/Errors/AuthorizationError.swift | 2 +- .../CodeGen/Events/SetUpTOTPEvent.swift | 1 - .../DebugInfo/CredentialStoreState+Debug.swift | 1 - .../DebugInfo/MigrateSignInState+Debug.swift | 4 ++-- .../States/DebugInfo/SignInState+Debug.swift | 2 +- .../ErrorMapping/SignInError+Helper.swift | 2 +- .../AuthenticationState+Resolver.swift | 2 ++ .../AuthorizationState+Resolver.swift | 4 +++- .../RefreshSessionState+Resolver.swift | 1 + .../Resolvers/SignIn/SignInState+Resolver.swift | 4 ++-- .../Constants/AuthPluginErrorConstants.swift | 7 +++++-- .../Support/Helpers/DeviceMetadataHelper.swift | 6 ++---- .../Support/Helpers/UserPoolSignInHelper.swift | 6 ++---- .../AuthUIPresentationAnchorPlaceholder.swift | 4 ++-- .../HostedUIASWebAuthenticationSession.swift | 2 +- .../Logging/AWSCognitoAuthPlugin+Log.swift | 2 +- .../Support/Utils/HttpClientEngineProxy.swift | 2 +- .../RespondToAuthChallengeInput+Amplify.swift | 3 +++ .../Task/AWSAuthChangePasswordTask.swift | 2 +- ...WSAuthClearFederationToIdentityPoolTask.swift | 2 +- .../Task/AWSAuthConfirmResetPasswordTask.swift | 6 +++--- .../Task/AWSAuthConfirmSignInTask.swift | 2 +- .../Task/AWSAuthConfirmSignUpTask.swift | 3 +-- .../Task/AWSAuthDeleteUserTask.swift | 7 +++++-- .../Task/AWSAuthFetchSessionTask.swift | 2 +- .../Task/AWSAuthResendSignUpCodeTask.swift | 2 +- .../Task/AWSAuthSignInTask.swift | 2 +- .../Task/AWSAuthSignOutTask.swift | 2 +- .../Task/AWSAuthWebUISignInTask.swift | 2 +- .../Task/FetchMFAPreferenceTask.swift | 4 ++-- .../Task/Helpers/AWSAuthTaskHelper.swift | 6 +++--- ...AuthAttributeResendConfirmationCodeTask.swift | 1 + ...thSendUserAttributeVerificationCodeTask.swift | 1 + .../UserTasks/AuthUpdateUserAttributeTask.swift | 1 + .../UserTasks/AuthUpdateUserAttributesTask.swift | 1 + ...AuthAttributeResendConfirmationCodeTask.swift | 2 +- ...thSendUserAttributeVerificationCodeTask.swift | 2 +- .../Task/VerifyTOTPSetupTask.swift | 2 +- .../AmplifyBigInteger/AmplifyBigIntHelper.swift | 4 ++-- .../Auth/Sources/AmplifySRP/HKDF.swift | 12 ++++++++---- .../Auth/Sources/AmplifySRP/SRPClientState.swift | 3 ++- .../Auth/Sources/AmplifySRP/SRPCommonState.swift | 2 ++ 84 files changed, 135 insertions(+), 147 deletions(-) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift index 4fce0d3311..5869e8a229 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift @@ -108,7 +108,7 @@ extension AWSCognitoAuthPlugin { } if let maxRetryUnwrapped = networkPreferences?.maxRetryCount { - configuration.retryStrategyOptions = RetryStrategyOptions(maxRetriesBase: Int(maxRetryUnwrapped)) + configuration.retryStrategyOptions = RetryStrategyOptions(maxRetriesBase: Int(maxRetryUnwrapped)) } return CognitoIdentityProviderClient(config: configuration) @@ -131,7 +131,7 @@ extension AWSCognitoAuthPlugin { } if let maxRetryUnwrapped = networkPreferences?.maxRetryCount { - configuration.retryStrategyOptions = RetryStrategyOptions(maxRetriesBase: Int(maxRetryUnwrapped)) + configuration.retryStrategyOptions = RetryStrategyOptions(maxRetriesBase: Int(maxRetryUnwrapped)) } return CognitoIdentityClient(config: configuration) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift index bc5adbfa95..6155f93d27 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift @@ -51,5 +51,5 @@ public extension AWSCognitoAuthPlugin { userPoolFactory: authEnvironment.cognitoUserPoolFactory) return try await task.value } - + } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift index b55a033077..4d1388d7ef 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift @@ -30,11 +30,9 @@ struct InitializeAuthConfiguration: Action { if case .amplifyCredentials(let fetchedCredentials) = data { credentials = fetchedCredentials } - } - catch KeychainStoreError.itemNotFound { + } catch KeychainStoreError.itemNotFound { logInfo("No existing session found.", environment: environment) - } - catch { + } catch { logError("Error when loading amplify credentials: \(error)", environment: environment) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift index ee63e5063a..6017f71215 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift @@ -9,6 +9,7 @@ import Foundation import Amplify @_spi(KeychainStore) import AWSPluginsCore +// swiftlint:disable identifier_name struct MigrateLegacyCredentialStore: Action { let identifier = "MigrateLegacyCredentialStore" @@ -361,7 +362,7 @@ extension MigrateLegacyCredentialStore: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } @@ -380,3 +381,4 @@ extension MigrateLegacyCredentialStore: CustomDebugStringConvertible { debugDictionary.debugDescription } } +// swiftlint:enable identifier_name diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift index 2f084dc27f..a604270478 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift @@ -36,7 +36,7 @@ extension InformUserDeletedAndSignedOut: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift index d21f30363a..bca1e5e6d0 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift @@ -47,7 +47,7 @@ extension InformSessionError: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionFetched.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionFetched.swift index d312295754..6bf1e5471a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionFetched.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionFetched.swift @@ -30,7 +30,7 @@ extension InformSessionFetched: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift index 88c3b42d91..09ecfed4b2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift @@ -43,7 +43,7 @@ extension InitializeFetchAuthSessionWithUserPool: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift index 225e740b24..619e2586ff 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift @@ -34,7 +34,7 @@ extension InitializeFetchUnAuthSession: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/PersistCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/PersistCredentials.swift index bacbda3a71..ca59a387f6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/PersistCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/PersistCredentials.swift @@ -41,7 +41,7 @@ extension PersistCredentials: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InformSessionRefreshed.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InformSessionRefreshed.swift index 6b5fd05aa3..47d937cbbb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InformSessionRefreshed.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InformSessionRefreshed.swift @@ -28,7 +28,7 @@ extension InformSessionRefreshed: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift index 402acbdc79..43c36c2cb9 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift @@ -64,7 +64,7 @@ extension InitializeRefreshSession: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshHostedUITokens.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshHostedUITokens.swift index 859355272f..367b9eb222 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshHostedUITokens.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshHostedUITokens.swift @@ -117,7 +117,7 @@ extension RefreshHostedUITokens: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift index 5a6da9d7bc..cbd3fcbd60 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift @@ -104,7 +104,7 @@ extension RefreshUserPoolTokens: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift index 0b0c717d54..0dc41794d9 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift @@ -78,7 +78,7 @@ extension InitiateCustomAuth: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift index 7a89fa6615..bc7614301a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift @@ -86,7 +86,10 @@ struct InitiateAuthDeviceSRP: Action { _ response: SignInResponseBehavior, with stateData: SRPStateData) -> StateMachineEvent { guard case .devicePasswordVerifier = response.challengeName else { - let message = "Unsupported challenge response during DeviceSRPAuth \(response.challengeName ?? .sdkUnknown("Response did not contain challenge info"))" + let message = """ + Unsupported challenge response during DeviceSRPAuth + \(response.challengeName ?? .sdkUnknown("Response did not contain challenge info")) + """ let error = SignInError.unknown(message: message) return SignInEvent(eventType: .throwAuthError(error)) } @@ -99,7 +102,7 @@ extension InitiateAuthDeviceSRP: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift index 59cf47a99f..d1846ff20d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift @@ -10,6 +10,7 @@ import CryptoKit extension VerifyDevicePasswordSRP { + // swiftlint:disable:next function_parameter_count identifier_name func signature(deviceGroupKey: String, deviceKey: String, deviceSecret: String, @@ -28,6 +29,7 @@ extension VerifyDevicePasswordSRP { do { let dateStr = stateData.clientTimestamp.utcString let clientClass = type(of: srpClient) + // swiftlint:disable:next identifier_name let u = try clientClass.calculateUHexValue( clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue, serverPublicKeyHexValue: serverPublicBHexString) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift index 08153d6d1d..38b96dac1e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift @@ -99,7 +99,7 @@ extension VerifyDevicePasswordSRP: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift index 7f02972975..8ea604a1ff 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift @@ -30,7 +30,7 @@ struct InitializeSignInFlow: Action { let event = SignInEvent(eventType: .throwAuthError(.configuration(message: message))) return event } - + var deviceMetadata = DeviceMetadata.noData if let username = signInEventData.username { deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift index 827d29cf22..ed1c98507f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift @@ -82,7 +82,7 @@ extension InitiateMigrateAuth: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift index 9cf1df4217..eb5832ac4a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift @@ -25,7 +25,7 @@ extension CancelSignIn: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift index 60c2ccb2be..a2c2e23f35 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift @@ -112,7 +112,7 @@ extension InitiateAuthSRP: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift index ef123c9695..80222157e2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift @@ -29,7 +29,7 @@ extension ThrowSignInError: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift index 4d70f76521..cab2fbc412 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift @@ -10,6 +10,7 @@ import CryptoKit extension VerifyPasswordSRP { + // swiftlint:disable:next function_parameter_count func signature(userIdForSRP: String, saltHex: String, secretBlock: Data, @@ -28,6 +29,7 @@ extension VerifyPasswordSRP { let strippedPoolId = strippedPoolId(poolId) let dateStr = stateData.clientTimestamp.utcString let clientClass = type(of: srpClient) + // swiftlint:disable:next identifier_name let u = try clientClass.calculateUHexValue( clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue, serverPublicKeyHexValue: serverPublicBHexString) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift index 8327dbd659..bf09ea4f63 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift @@ -118,7 +118,7 @@ extension VerifyPasswordSRP: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift index 0dc729a532..75bed80e89 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift @@ -9,6 +9,7 @@ import Foundation import Amplify import AuthenticationServices +// swiftlint:disable force_cast extension AWSCognitoAuthPlugin: AuthCategoryBehavior { public func signUp(username: String, @@ -27,7 +28,7 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { public func confirmSignUp(for username: String, confirmationCode: String, options: AuthConfirmSignUpRequest.Options?) - async throws-> AuthSignUpResult { + async throws -> AuthSignUpResult { let options = options ?? AuthConfirmSignUpRequest.Options() let request = AuthConfirmSignUpRequest(username: username, code: confirmationCode, @@ -176,7 +177,6 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } as! TOTPSetupDetails } - public func verifyTOTPSetup( code: String, options: VerifyTOTPSetupRequest.Options? @@ -194,3 +194,4 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } } } +// swiftlint:enable force_cast diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift index fa055a30cf..4dc7c9c348 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift @@ -19,11 +19,13 @@ extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { userPoolFactory: authEnvironment.cognitoUserPoolFactory) return try await taskQueue.sync { return try await task.value - } as! [AuthDevice] + } as! [AuthDevice] // swiftlint:disable:this force_cast } - public func forgetDevice(_ device: AuthDevice? = nil, - options: AuthForgetDeviceRequest.Options? = nil) async throws { + public func forgetDevice( + _ device: AuthDevice? = nil, + options: AuthForgetDeviceRequest.Options? = nil + ) async throws { let options = options ?? AuthForgetDeviceRequest.Options() let request = AuthForgetDeviceRequest(device: device, options: options) let task = AWSAuthForgetDeviceTask(request, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift index 9d2608bf16..21df88d96b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift @@ -8,6 +8,7 @@ import Foundation import Amplify +// swiftlint:disable force_cast public extension AWSCognitoAuthPlugin { func fetchUserAttributes(options: AuthFetchUserAttributesRequest.Options? = nil) async throws -> [AuthUserAttribute] { @@ -50,7 +51,11 @@ public extension AWSCognitoAuthPlugin { let options = options ?? AuthAttributeResendConfirmationCodeRequest.Options() let request = AuthAttributeResendConfirmationCodeRequest( attributeKey: userAttributeKey, options: options) - let task = AWSAuthAttributeResendConfirmationCodeTask(request, authStateMachine: authStateMachine, userPoolFactory: authEnvironment.cognitoUserPoolFactory) + let task = AWSAuthAttributeResendConfirmationCodeTask( + request, + authStateMachine: authStateMachine, + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await taskQueue.sync { return try await task.value } as! AuthCodeDeliveryDetails @@ -98,3 +103,4 @@ public extension AWSCognitoAuthPlugin { return try await taskHelper.getCurrentUser() } } +// swiftlint:enable force_cast diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift index c3ca0364e0..c8248e156f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift @@ -67,7 +67,7 @@ class AuthHubEventHandler: AuthHubEventBehavior { } self?.handleSignInEvent(result) #endif - + case HubPayload.EventName.Auth.deleteUserAPI: guard let event = payload.data as? AWSAuthDeleteUserTask.AmplifyAuthTaskResult, case .success = event else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift index c5f4daed06..38d34ba4d9 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift @@ -19,6 +19,7 @@ public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { @available(*, deprecated, message: "Use of `expiration` is deprecated, use `exp` claim in the `idToken` or `accessToken` for expiries") public let expiration: Date + // swiftlint:disable:next line_length @available(*, deprecated, message: "Use of `init(idToken,accessToken,refreshToken:expiresIn)` is deprecated, use `exp` claim in the `idToken` or `accessToken` instead") public init(idToken: String, accessToken: String, @@ -30,6 +31,7 @@ public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { self.expiration = Date().addingTimeInterval(TimeInterval(expiresIn)) } + // swiftlint:disable:next line_length @available(*, deprecated, message: "Use of `init(idToken,accessToken,refreshToken:expiration)` is deprecated, use `exp` claim in the `idToken` or `accessToken` instead") public init(idToken: String, accessToken: String, @@ -71,7 +73,7 @@ public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { self.expiration = Date(timeIntervalSince1970: TimeInterval(expirationDoubleValue)) } } - + } extension AWSCognitoUserPoolTokens: Equatable { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFAPreference.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFAPreference.swift index 521b6f4d8d..0b94b34d77 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFAPreference.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFAPreference.swift @@ -10,7 +10,7 @@ import Foundation /// Input for updating the MFA preference for a MFA Type public enum MFAPreference { - + // enabled: false case disabled diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmResetPasswordOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmResetPasswordOptions.swift index 9a386c59e7..17de94fab0 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmResetPasswordOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmResetPasswordOptions.swift @@ -15,4 +15,3 @@ public struct AWSAuthConfirmResetPasswordOptions { self.metadata = metadata } } - diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/UserMFAPreference.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/UserMFAPreference.swift index 6f7068cfe8..a3724c25aa 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/UserMFAPreference.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/UserMFAPreference.swift @@ -16,9 +16,4 @@ public struct UserMFAPreference { /// nil if no preference public let preferred: MFAType? - internal init(enabled: Set?, preferred: MFAType?) { - self.enabled = enabled - self.preferred = preferred - } - } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift index b9fdbc1d88..7aa1997b72 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift @@ -10,8 +10,6 @@ import Amplify class FetchAuthSessionOperationHelper: DefaultLogger { - - typealias FetchAuthSessionCompletion = (Result) -> Void func fetch(_ authStateMachine: AuthStateMachine, @@ -181,7 +179,7 @@ class FetchAuthSessionOperationHelper: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift index 6399757df3..375216c8d5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift @@ -59,7 +59,6 @@ struct HostedUISignInHelper: DefaultLogger { } } - private func doSignIn() async throws -> AuthSignInResult { let oauthConfiguration: OAuthConfigurationData @@ -156,11 +155,11 @@ struct HostedUISignInHelper: DefaultLogger { } } } - + public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift index bd76c0e862..de41eead55 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift @@ -13,7 +13,7 @@ struct AmplifySRPClient: SRPClientBehavior { let commonState: SRPCommonState let client: SRPClientState - + // swiftlint:disable identifier_name init(NHexValue: String, gHexValue: String) throws { guard let N = BigInt(NHexValue, radix: 16), let g = BigInt(gHexValue, radix: 16) @@ -36,6 +36,7 @@ struct AmplifySRPClient: SRPClientBehavior { return srpKeys } + // swiftlint:disable:next function_parameter_count func calculateSharedSecret(username: String, password: String, saltHexValue: String, @@ -120,5 +121,5 @@ struct AmplifySRPClient: SRPClientBehavior { return (saltData, verifierData) } - + // swiftlint:enable identifier_name } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift index dd16b203a0..dbe795e4fc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift @@ -102,7 +102,6 @@ extension AWSCognitoIdentity.TooManyRequestsException: AuthErrorConvertible { } } - extension AWSCognitoIdentity.LimitExceededException: AuthErrorConvertible { var fallbackDescription: String { "Too many requests error." } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift index 6179940724..0b3f3c2fa4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift @@ -160,7 +160,6 @@ extension InvalidLambdaResponseException: AuthErrorConvertible { } } - extension ExpiredCodeException: AuthErrorConvertible { var fallbackDescription: String { "Provided code has expired." } @@ -256,7 +255,6 @@ extension InvalidEmailRoleAccessPolicyException: AuthErrorConvertible { } } - extension InvalidSmsRoleAccessPolicyException: AuthErrorConvertible { var fallbackDescription: String { "Invalid SMS Role Access Policy error." } @@ -328,7 +326,6 @@ extension AWSCognitoIdentityProvider.ConcurrentModificationException: AuthErrorC } } - extension AWSCognitoIdentityProvider.EnableSoftwareTokenMFAException: AuthErrorConvertible { var fallbackDescription: String { "Unable to enable software token MFA" } @@ -355,7 +352,3 @@ extension AWSClientRuntime.UnknownAWSHTTPServiceError: AuthErrorConvertible { ) } } - - - - diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift index c22b127a88..4c62415442 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift @@ -50,16 +50,6 @@ struct OAuthConfigurationData: Equatable { let scopes: [String] let signInRedirectURI: String let signOutRedirectURI: String - - init(domain: String, - scopes: [String], - signInRedirectURI: String, - signOutRedirectURI: String) { - self.domain = domain - self.scopes = scopes - self.signInRedirectURI = signInRedirectURI - self.signOutRedirectURI = signOutRedirectURI - } } extension OAuthConfigurationData: Codable { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/IdentityPoolConfigurationData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/IdentityPoolConfigurationData.swift index 3647fbfaa1..11e2474e48 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/IdentityPoolConfigurationData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/IdentityPoolConfigurationData.swift @@ -11,12 +11,6 @@ struct IdentityPoolConfigurationData: Equatable { let poolId: String let region: String - init(poolId: String, - region: String) { - self.poolId = poolId - self.region = region - } - } extension IdentityPoolConfigurationData: Codable { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift index 0ee7a963d3..c8a5297f86 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift @@ -53,7 +53,7 @@ extension RespondToAuthChallenge { let mfaTypesArray = try? JSONDecoder().decode( [String].self, from: Data(mfaTypeParameters.utf8) - ) + ) else { return .init() } let mfaTypes = mfaTypesArray.compactMap(MFAType.init(rawValue:)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SRPStateData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SRPStateData.swift index 3d19c9140a..45e138e15c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SRPStateData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SRPStateData.swift @@ -15,22 +15,6 @@ struct SRPStateData { let srpKeyPair: SRPKeys let clientTimestamp: Date - init( - username: String, - password: String, - NHexValue: String, - gHexValue: String, - srpKeyPair: SRPKeys, - clientTimestamp: Date - ) { - self.username = username - self.password = password - self.NHexValue = NHexValue - self.gHexValue = gHexValue - self.srpKeyPair = srpKeyPair - self.clientTimestamp = clientTimestamp - } - } extension SRPStateData: Equatable { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift index 8c1ed9c1e0..249c189781 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift @@ -23,7 +23,7 @@ extension AuthorizationError: AuthErrorConvertible { switch self { case .sessionExpired(let error): return .sessionExpired( - "Session expired", + "Session expired", "Invoke Auth.signIn to re-authenticate the user", error) case .configuration(let message): diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift index d21caecae7..387262e785 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift @@ -67,5 +67,4 @@ extension SetUpTOTPEvent.EventType: Equatable { } } - } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift index b12c8ec64f..4b9eb908af 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift @@ -35,7 +35,6 @@ extension CredentialStoreState: CustomDebugStringConvertible { return [type: additionalMetadataDictionary] } - var debugDescription: String { return (debugDictionary as AnyObject).description } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift index 0b7571271b..a0df091306 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift @@ -17,11 +17,11 @@ extension MigrateSignInState: CustomDebugDictionaryConvertible { case .notStarted: additionalMetadataDictionary = [:] - case .signingIn(_): + case .signingIn: additionalMetadataDictionary = [:] case .signedIn(let signedInData): additionalMetadataDictionary = ["SignedInData": signedInData.debugDictionary] - case .error(_): + case .error: additionalMetadataDictionary = [:] } return [type: additionalMetadataDictionary] diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift index 51d86499fe..1cba475ba8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift @@ -47,7 +47,7 @@ extension SignInState: CustomDebugDictionaryConvertible { case .resolvingTOTPSetup(let signInTOTPSetupState, let signInEventData): additionalMetadataDictionary = [ "SignInTOTPSetupState": signInTOTPSetupState.debugDictionary, - "SignInEventData" : signInEventData.debugDictionary] + "SignInEventData": signInEventData.debugDictionary] case .error: additionalMetadataDictionary = [:] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift index 31b7d6b12e..75ba411059 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift @@ -25,7 +25,7 @@ extension SignInError { switch self { case .service(error: let serviceError): return serviceError is AWSCognitoIdentityProvider.PasswordResetRequiredException - default: + default: return false } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift index 95d24ea6de..d7703d9482 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift @@ -7,12 +7,14 @@ extension AuthenticationState { + // swiftlint:disable:next nesting struct Resolver: StateMachineResolver { typealias StateType = AuthenticationState let defaultState = AuthenticationState.notConfigured init() { } + // swiftlint:disable:next cyclomatic_complexity func resolve( oldState: StateType, byApplying event: StateMachineEvent diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift index 46203130b8..51be1d9500 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift @@ -9,12 +9,14 @@ import Foundation extension AuthorizationState { + // swiftlint:disable:next type_body_length nesting struct Resolver: StateMachineResolver { typealias StateType = AuthorizationState let defaultState = AuthorizationState.notConfigured init() { } + // swiftlint:disable:next cyclomatic_complexity function_body_length func resolve( oldState: StateType, byApplying event: StateMachineEvent @@ -247,7 +249,7 @@ extension AuthorizationState { if case .sessionEstablished(let credentials) = event.isAuthorizationEvent { return .init(newState: .sessionEstablished(credentials)) } - + if case .throwError(let error) = event.isAuthorizationEvent { return .init(newState: .error(error)) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift index a614bea112..94e09d0412 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift @@ -14,6 +14,7 @@ extension RefreshSessionState { var defaultState: RefreshSessionState = .notStarted + // swiftlint:disable:next cyclomatic_complexity func resolve(oldState: RefreshSessionState, byApplying event: StateMachineEvent) -> StateResolution { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift index 644e9fabc2..d95da1588c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift @@ -8,11 +8,13 @@ import Foundation extension SignInState { + // swiftlint:disable:next nesting struct Resolver: StateMachineResolver { typealias StateType = SignInState let defaultState = SignInState.notStarted + // swiftlint:disable:next cyclomatic_complexity function_body_length func resolve( oldState: SignInState, byApplying event: StateMachineEvent) @@ -296,7 +298,6 @@ extension SignInState { signInEventData) return .init(newState: signingInWithSRP, actions: resolution.actions) - case .resolvingTOTPSetup(let setUpTOTPState, let signInEventData): if case .finalizeSignIn(let signedInData) = event.isSignInEvent { @@ -341,7 +342,6 @@ extension SignInState { signInEventData) return .init(newState: settingUpTOTPState, actions: resolution.actions) - case .resolvingDeviceSrpa(let deviceSrpState): let signInMethod = SignInMethod.apiBased(.userSRP) if let signInEvent = event as? SignInEvent, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift index c43ec28007..baa46fc0d3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift @@ -217,7 +217,10 @@ extension AuthPluginErrorConstants { static let confirmSignInMFASelectionResponseError: AuthPluginValidationErrorString = ( "challengeResponse", "challengeResponse for MFA selection can only have SMS_MFA or SOFTWARE_TOKEN_MFA.", - "Make sure that a valid challenge response is passed for confirmSignIn. Try using `MFAType.totp.challengeResponse` or `MFAType.sms.challengeResponse` as the challenge response" + """ + Make sure that a valid challenge response is passed for confirmSignIn. + Try using `MFAType.totp.challengeResponse` or `MFAType.sms.challengeResponse` as the challenge response + """ ) static let confirmResetPasswordUsernameError: AuthPluginValidationErrorString = ( @@ -335,7 +338,7 @@ extension AuthPluginErrorConstants { """ static let forbiddenError: RecoverySuggestion = """ - Check if you are allowed to make this request based on the web ACL thats associated with your user pool + Check if you are allowed to make this request based on the web ACL thats associated with your user pool """ static let concurrentModificationException: RecoverySuggestion = """ diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift index 0065ae8819..f53ae871c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift @@ -20,12 +20,10 @@ struct DeviceMetadataHelper { if case .deviceMetadata(let fetchedMetadata, _) = data { return fetchedMetadata } - } - catch KeychainStoreError.itemNotFound { + } catch KeychainStoreError.itemNotFound { let logger = (environment as? LoggerProvider)?.logger logger?.info("No existing device metadata found. \(environment)") - } - catch { + } catch { let logger = (environment as? LoggerProvider)?.logger logger?.error("Unable to fetch device metadata with error: \(error)") } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift index 8e23f842bb..02a2d74f62 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift @@ -100,8 +100,6 @@ struct UserPoolSignInHelper: DefaultLogger { return event } - - static func parseResponse( _ response: SignInResponseBehavior, for username: String, @@ -162,11 +160,11 @@ struct UserPoolSignInHelper: DefaultLogger { return SignInEvent(eventType: .throwAuthError(error)) } } - + public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift index 64469c240e..c15d072b39 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift @@ -15,9 +15,9 @@ typealias AuthUIPresentationAnchor = AuthUIPresentationAnchorPlaceholder /// It cannot be initialized and exists strictly to facilitate cross-platform compilation without requiring compiler /// checks thorughout the codebase. class AuthUIPresentationAnchorPlaceholder: Equatable { - + private init() {} - + public static func == (lhs: AuthUIPresentationAnchorPlaceholder, rhs: AuthUIPresentationAnchorPlaceholder) -> Bool { true diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift index c5e5b21835..45cc3124c2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift @@ -70,7 +70,7 @@ class HostedUIASWebAuthenticationSession: NSObject, HostedUISessionBehavior { #if os(iOS) || os(macOS) var authenticationSessionFactory = ASWebAuthenticationSession.init(url:callbackURLScheme:completionHandler:) - + private func createAuthenticationSession( url: URL, callbackURLScheme: String?, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Logging/AWSCognitoAuthPlugin+Log.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Logging/AWSCognitoAuthPlugin+Log.swift index 1f190abdc9..62898d9094 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Logging/AWSCognitoAuthPlugin+Log.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Logging/AWSCognitoAuthPlugin+Log.swift @@ -11,7 +11,7 @@ extension AWSCognitoAuthPlugin: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift index e2cd4dd7d1..82a6b939de 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift @@ -10,7 +10,7 @@ import ClientRuntime import Foundation protocol HttpClientEngineProxy: HttpClientEngine { - var target: HttpClientEngine? { set get } + var target: HttpClientEngine? { get set } } extension UserAgentSuffixAppender: HttpClientEngineProxy {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift index 358dab87aa..7ee75ff8b8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift @@ -10,6 +10,7 @@ import AWSCognitoIdentityProvider extension RespondToAuthChallengeInput { + // swiftlint:disable:next function_parameter_count static func passwordVerifier(username: String, stateData: SRPStateData, session: String?, @@ -36,6 +37,7 @@ extension RespondToAuthChallengeInput { environment: environment) } + // swiftlint:disable:next function_parameter_count static func deviceSRP(username: String, environment: UserPoolEnvironment, deviceMetadata: DeviceMetadata, @@ -83,6 +85,7 @@ extension RespondToAuthChallengeInput { environment: environment) } + // swiftlint:disable:next function_parameter_count static func verifyChallenge( username: String, challengeType: CognitoIdentityProviderClientTypes.ChallengeNameType, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift index 6e16c26142..0fb50718c1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift @@ -57,5 +57,5 @@ class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { proposedPassword: request.newPassword) _ = try await userPoolService.changePassword(input: input) } - + } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift index 06dfe200c9..293ae92b2f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift @@ -41,5 +41,5 @@ public class AWSAuthClearFederationToIdentityPoolTask: AuthClearFederationToIden log.verbose("Cleared federation") return } - + } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift index 4bf0c1bc12..a7b1b03e90 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift @@ -32,7 +32,7 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg throw validationError } do { - + try await confirmResetPassword() } catch let error as AuthErrorConvertible { throw error.authError @@ -44,7 +44,7 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg func confirmResetPassword() async throws { let userPoolEnvironment = try environment.userPoolEnvironment() let userPoolService = try userPoolEnvironment.cognitoUserPoolFactory() - + let clientMetaData = (request.options.pluginOptions as? AWSAuthConfirmResetPasswordOptions)?.metadata ?? [:] @@ -88,5 +88,5 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg _ = try await userPoolService.confirmForgotPassword(input: input) } - + } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift index cba88b1466..3c19a16d61 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift @@ -32,7 +32,7 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { log.verbose("Starting execution") await taskHelper.didStateMachineConfigured() - //Check if we have a user pool configuration + // Check if we have a user pool configuration guard authConfiguration.getUserPoolConfiguration() != nil else { let message = AuthPluginErrorConstants.configurationError let authError = AuthError.configuration( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift index 819e4e44c9..6a03e246b5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift @@ -42,7 +42,7 @@ class AWSAuthConfirmSignUpTask: AuthConfirmSignUpTask, DefaultLogger { _ = try await client.confirmSignUp(input: input) log.verbose("Received success") return AuthSignUpResult(.done, userID: nil) - } catch let error as AuthErrorConvertible { + } catch let error as AuthErrorConvertible { throw error.authError } catch { throw AuthError.configuration( @@ -52,5 +52,4 @@ class AWSAuthConfirmSignUpTask: AuthConfirmSignUpTask, DefaultLogger { ) } } - } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift index a684ed36d7..4539bcecba 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift @@ -48,7 +48,10 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { log.verbose("Waiting for delete user to complete") for await state in stateSequences { guard case .configured(let authNState, _) = state else { - let error = AuthError.invalidState("Auth state should be in configured state and authentication state should be in deleting user state", AuthPluginErrorConstants.invalidStateError, nil) + let error = AuthError.invalidState( + "Auth state should be in configured state and authentication state should be in deleting user state", + AuthPluginErrorConstants.invalidStateError, + nil) throw error } @@ -85,5 +88,5 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { await authStateMachine.send(event) await taskHelper.didStateMachineConfigured() } - + } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift index 2995593ff6..7a00941ad9 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift @@ -32,5 +32,5 @@ class AWSAuthFetchSessionTask: AuthFetchSessionTask, DefaultLogger { return try await fetchAuthSessionHelper.fetch(authStateMachine, forceRefresh: doesNeedForceRefresh) } - + } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift index 9df2af8c99..32402637a3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift @@ -93,5 +93,5 @@ class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { return deliveryDetails } - + } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift index 3cb18018bf..3a68e3aeff 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift @@ -31,7 +31,7 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { func execute() async throws -> AuthSignInResult { log.verbose("Starting execution") await taskHelper.didStateMachineConfigured() - //Check if we have a user pool configuration + // Check if we have a user pool configuration guard let userPoolConfiguration = authConfiguration.getUserPoolConfiguration() else { let message = AuthPluginErrorConstants.configurationError let authError = AuthError.configuration( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift index 52c6b94f68..f5de608577 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift @@ -69,7 +69,7 @@ class AWSAuthSignOutTask: AuthSignOutTask, DefaultLogger { #else presentationAnchor = nil #endif - + let signOutData = SignOutEventData( globalSignOut: request.options.globalSignOut, presentationAnchor: presentationAnchor diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift index 7244ea854c..564b5c177e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift @@ -46,6 +46,6 @@ class AWSAuthWebUISignInTask: AuthWebUISignInTask, DefaultLogger { } } - + } #endif diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift index b3a456214d..acb63eacec 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift @@ -56,8 +56,8 @@ class FetchMFAPreferenceTask: AuthFetchMFAPreferenceTask, DefaultLogger { let input = GetUserInput(accessToken: accessToken) let result = try await userPoolService.getUser(input: input) - var enabledList: Set? = nil - var preferred: MFAType? = nil + var enabledList: Set? + var preferred: MFAType? for mfaValue in result.userMFASettingList ?? [] { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift index 5c9dbeaeae..44267909b1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift @@ -85,13 +85,13 @@ class AWSAuthTaskHelper: DefaultLogger { func getCurrentUser() async throws -> AuthUser { await didStateMachineConfigured() let authState = await authStateMachine.currentState - + guard case .configured(let authenticationState, _) = authState else { throw AuthError.configuration( "Plugin not configured", AuthPluginErrorConstants.configurationError) } - + switch authenticationState { case .notConfigured: throw AuthError.configuration("UserPool configuration is missing", AuthPluginErrorConstants.configurationError) @@ -112,7 +112,7 @@ class AWSAuthTaskHelper: DefaultLogger { public static var log: Logger { Amplify.Logging.logger(forCategory: CategoryType.auth.displayName, forNamespace: String(describing: self)) } - + public var log: Logger { Self.log } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthAttributeResendConfirmationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthAttributeResendConfirmationCodeTask.swift index bac4785fa1..bd79d06294 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthAttributeResendConfirmationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthAttributeResendConfirmationCodeTask.swift @@ -7,6 +7,7 @@ import Amplify +// swiftlint:disable:next line_length protocol AuthAttributeResendConfirmationCodeTask: AmplifyAuthTask where Request == AuthAttributeResendConfirmationCodeRequest, Success == AuthCodeDeliveryDetails, Failure == AuthError {} public extension HubPayload.EventName.Auth { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthSendUserAttributeVerificationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthSendUserAttributeVerificationCodeTask.swift index 2399826053..1c7818e5cf 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthSendUserAttributeVerificationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthSendUserAttributeVerificationCodeTask.swift @@ -7,6 +7,7 @@ import Amplify +// swiftlint:disable:next line_length protocol AuthSendUserAttributeVerificationCodeTask: AmplifyAuthTask where Request == AuthSendUserAttributeVerificationCodeRequest, Success == AuthCodeDeliveryDetails, Failure == AuthError {} public extension HubPayload.EventName.Auth { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift index 1c9807685f..eaadcd9e78 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift @@ -6,6 +6,7 @@ // import Amplify +// swiftlint:disable:next line_length protocol AuthUpdateUserAttributeTask: AmplifyAuthTask where Request == AuthUpdateUserAttributeRequest, Success == AuthUpdateAttributeResult, Failure == AuthError {} public extension HubPayload.EventName.Auth { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift index a81f4f592d..b16def3182 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift @@ -6,6 +6,7 @@ // import Amplify +// swiftlint:disable:next line_length protocol AuthUpdateUserAttributesTask: AmplifyAuthTask where Request == AuthUpdateUserAttributesRequest, Success == [AuthUserAttributeKey: AuthUpdateAttributeResult], Failure == AuthError {} public extension HubPayload.EventName.Auth { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift index 70d30b966b..763af3e80c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift @@ -37,7 +37,7 @@ class AWSAuthAttributeResendConfirmationCodeTask: AuthAttributeResendConfirmatio return devices } catch let error as AuthErrorConvertible { throw error.authError - } catch { + } catch { throw AuthError.configuration( "Unable to execute auth task", AuthPluginErrorConstants.configurationError, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift index 6acd247d98..0d8d09f435 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift @@ -39,7 +39,7 @@ class AWSAuthSendUserAttributeVerificationCodeTask: AuthSendUserAttributeVerific return devices } catch let error as AuthErrorConvertible { throw error.authError - } catch { + } catch { throw AuthError.configuration( "Unable to execute auth task", AuthPluginErrorConstants.configurationError, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift index 40156b2e12..f5cf58d112 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift @@ -46,7 +46,7 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { } } - func verifyTOTPSetup(with accessToken: String, userCode: String) async throws { + func verifyTOTPSetup(with accessToken: String, userCode: String) async throws { let userPoolService = try userPoolFactory() let friendlyDeviceName = (request.options.pluginOptions as? VerifyTOTPSetupOptions)?.friendlyDeviceName let input = VerifySoftwareTokenInput( diff --git a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigIntHelper.swift b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigIntHelper.swift index 9eb2fb8b40..3b8d78aa99 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigIntHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigIntHelper.swift @@ -21,8 +21,8 @@ public enum AmplifyBigIntHelper { if byteCount > 1 && bytesArray[0] == 1 { var invertedBytes = [UInt8](repeating: 0, count: bytesArray.count) invertedBytes[0] = ~invertedBytes[0] - for i in 1 ..< bytesArray.count { - invertedBytes[i] = ~bytesArray[i] + for index in 1 ..< bytesArray.count { + invertedBytes[index] = ~bytesArray[index] } let unsignedInvertedBytes = AmplifyBigInt(unsignedData: invertedBytes) let twosComplementNum = unsignedInvertedBytes + AmplifyBigInt(1) diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift index 9db66655e2..26aebf4545 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift @@ -9,6 +9,7 @@ import Foundation import CommonCrypto import CryptoKit +// swiftlint:disable identifier_name // https://tools.ietf.org/html/rfc5869 public enum HMACKeyDerivationFunction { @@ -28,10 +29,12 @@ public enum HMACKeyDerivationFunction { } @available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) - private static func generateHKDF(keyingMaterial: Data, - salt: Data, - info: String?, - outputLength: Int) -> Data { + private static func generateHKDF( + keyingMaterial: Data, + salt: Data, + info: String?, + outputLength: Int + ) -> Data { let key = SymmetricKey(data: keyingMaterial) var hkdf: SymmetricKey if let info { @@ -83,3 +86,4 @@ public enum HMACKeyDerivationFunction { return Data(hmacFinal) } } +// swiftlint:enable identifier_name diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift index 3641e83372..2bc92a7583 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift @@ -11,6 +11,7 @@ import AmplifyBigInteger public typealias BigInt = AmplifyBigInt +// swiftlint:disable identifier_name public struct SRPClientState { public let privateA: BigInt @@ -106,5 +107,5 @@ public struct SRPClientState { return (salt, passwordVerifier) } - +// swiftlint:enable identifier_name } diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift index c549b0e719..524e96106a 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift @@ -9,6 +9,7 @@ import Foundation import CryptoKit import AmplifyBigInteger +// swiftlint:disable identifier_name public struct SRPCommonState { /// Group Parameter N of SRP protocol @@ -37,3 +38,4 @@ public struct SRPCommonState { return BigInt(unsignedData: hashBytes) } } +// swiftlint:enable identifier_name From 104b63afcb2471354638c2b6549146bb67923d88 Mon Sep 17 00:00:00 2001 From: Tuan Pham Date: Tue, 2 Jan 2024 11:29:56 -0600 Subject: [PATCH 5/5] chore: resolve swiftlint errors and warnings --- ...ataStorePlugin+DataStoreBaseBehavior.swift | 36 +++++++++---------- ...orePlugin+DataStoreSubscribeBehavior.swift | 5 ++- .../AWSDataStorePlugin.swift | 8 ++--- .../DataStoreConfiguration+Helper.swift | 4 +-- .../DataStoreConfiguration.swift | 2 +- .../InternalDatastoreConfiguration.swift | 8 ++--- .../Core/DataStoreListDecoder.swift | 12 +++---- .../Core/DataStoreListProvider.swift | 12 +++---- .../Core/DataStoreModelDecoder.swift | 14 ++++---- .../Core/DataStoreModelProvider.swift | 16 ++++----- .../ModelSyncMetadataMigration.swift | 12 +++---- .../Storage/CascadeDeleteOperation.swift | 25 +++++++------ .../Storage/ModelStorageBehavior.swift | 2 +- .../Storage/SQLite/Model+SQLite.swift | 3 +- .../SQLite/SQLStatement+AlterTable.swift | 3 +- .../Storage/SQLite/Statement+Model.swift | 9 ++--- .../SQLite/StorageEngineAdapter+SQLite.swift | 13 +++---- .../StorageEngineAdapter+UntypedModel.swift | 4 +-- .../Storage/StorageEngineAdapter.swift | 1 - .../DataStoreObserveQueryOperation.swift | 36 +++++++++---------- .../Subscribe/DataStorePublisher.swift | 2 -- .../Subscribe/ObserveTaskRunner.swift | 8 ++--- .../Subscribe/Support/Model+Sort.swift | 4 +-- .../InitialSync/InitialSyncOperation.swift | 20 +++++------ .../InitialSync/InitialSyncOrchestrator.swift | 12 +++---- ...atabaseAdapter+MutationEventIngester.swift | 8 ++--- .../MutationEvent/MutationEventIngester.swift | 2 +- .../OutgoingMutationQueue.swift | 6 ++-- ...ocessMutationErrorFromCloudOperation.swift | 12 ++++--- .../SyncMutationToCloudOperation.swift | 2 +- ...eSyncEngine+AuthModeStrategyDelegate.swift | 4 +-- .../Sync/RemoteSyncEngine.swift | 10 +++--- .../Sync/RemoteSyncEngineBehavior.swift | 2 +- .../AWSIncomingEventReconciliationQueue.swift | 17 ++++----- ...onDisabledSubscriptionEventPublisher.swift | 2 +- .../AWSModelReconciliationQueue.swift | 6 ++-- .../ReconcileAndLocalSaveOperation.swift | 8 +++-- .../RemoteSyncReconciler.swift | 2 +- .../Sync/Support/MutationEvent+Query.swift | 6 ++-- 39 files changed, 181 insertions(+), 177 deletions(-) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift index 36eeeca8c2..a7a128f638 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreBaseBehavior.swift @@ -16,7 +16,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { completion: @escaping DataStoreCallback) { save(model, modelSchema: model.schema, where: condition, completion: completion) } - + public func save(_ model: M, where condition: QueryPredicate? = nil) async throws -> M { try await save(model, modelSchema: model.schema, where: condition) @@ -56,7 +56,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { completion(.failure(error)) } } - + public func save(_ model: M, modelSchema: ModelSchema, where condition: QueryPredicate? = nil) async throws -> M { @@ -107,7 +107,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { identifier: DefaultModelIdentifier.makeDefault(id: identifier), completion: completion) } - + public func query(_ modelType: M.Type, byIdentifier identifier: String) async throws -> M? where M: ModelIdentifiable, M.IdentifierFormat == ModelIdentifierFormat.Default { @@ -124,7 +124,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { identifier: identifier, completion: completion) } - + public func query(_ modelType: M.Type, byIdentifier identifier: ModelIdentifier) async throws -> M? where M: ModelIdentifiable { @@ -154,7 +154,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } } - + private func queryByIdentifier(_ modelType: M.Type, modelSchema: ModelSchema, identifier: ModelIdentifierProtocol) async throws -> M? { @@ -177,7 +177,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { paginate: paginationInput, completion: completion) } - + public func query(_ modelType: M.Type, where predicate: QueryPredicate? = nil, sort sortInput: QuerySortInput? = nil, @@ -212,7 +212,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { completion(.failure(error)) } } - + public func query(_ modelType: M.Type, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil, @@ -233,7 +233,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { try await delete(modelType, modelSchema: modelType.schema, withId: id, where: predicate) } - + @available(*, deprecated, renamed: "delete(withIdentifier:)") public func delete(_ modelType: M.Type, modelSchema: ModelSchema, @@ -264,7 +264,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { where: predicate, completion: completion) } - + public func delete(_ modelType: M.Type, withIdentifier identifier: String, where predicate: QueryPredicate? = nil) async throws @@ -285,7 +285,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { where: predicate, completion: completion) } - + public func delete(_ modelType: M.Type, withIdentifier identifier: ModelIdentifier, where predicate: QueryPredicate? = nil) async throws where M: ModelIdentifiable { @@ -319,7 +319,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - + private func deleteByIdentifier(_ modelType: M.Type, modelSchema: ModelSchema, identifier: ModelIdentifierProtocol, @@ -336,7 +336,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { completion: @escaping DataStoreCallback) { delete(model, modelSchema: model.schema, where: predicate, completion: completion) } - + public func delete(_ model: M, where predicate: QueryPredicate? = nil) async throws { try await delete(model, modelSchema: model.schema, where: predicate) @@ -361,7 +361,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } - + public func delete(_ model: M, modelSchema: ModelSchema, where predicate: QueryPredicate? = nil) async throws { @@ -377,7 +377,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { completion: @escaping DataStoreCallback) { delete(modelType, modelSchema: modelType.schema, where: predicate, completion: completion) } - + public func delete(_ modelType: M.Type, where predicate: QueryPredicate) async throws { try await delete(modelType, modelSchema: modelType.schema, where: predicate) @@ -408,7 +408,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { completion(.failure(error)) } } - + public func delete(_ modelType: M.Type, modelSchema: ModelSchema, where predicate: QueryPredicate) async throws { @@ -425,7 +425,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { completion(result) } } - + public func start() async throws { _ = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation, Error>) in start { result in @@ -454,7 +454,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } } - + public func stop() async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in stop { result in @@ -488,7 +488,7 @@ extension AWSDataStorePlugin: DataStoreBaseBehavior { } } } - + public func clear() async throws { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in clear { result in diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift index 76302653f2..ca41efd230 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin+DataStoreSubscribeBehavior.swift @@ -9,7 +9,7 @@ import Amplify import Combine extension AWSDataStorePlugin: DataStoreSubscribeBehavior { - + public var publisher: AnyPublisher { _ = initStorageEngineAndStartSync() // Force-unwrapping: The optional 'dataStorePublisher' is expected @@ -25,7 +25,7 @@ extension AWSDataStorePlugin: DataStoreSubscribeBehavior { let runner = ObserveTaskRunner(publisher: publisher(for: modelType.modelName)) return runner.sequence } - + public func observeQuery(for modelType: M.Type, where predicate: QueryPredicate?, sort sortInput: QuerySortInput?) -> AmplifyAsyncThrowingSequence> { @@ -53,7 +53,6 @@ extension AWSDataStorePlugin: DataStoreSubscribeBehavior { case .failure(let error): return Fatal.preconditionFailure("Unable to get storage adapter \(error.localizedDescription)") } - } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift index 5f775a0e69..cdcbbc2bfb 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/AWSDataStorePlugin.swift @@ -22,7 +22,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { /// The Publisher that sends mutation events to subscribers var dataStorePublisher: ModelSubcriptionBehavior? - + var dataStoreStateSubject = PassthroughSubject() var dispatchedModelSyncedEvents: [ModelName: AtomicValue] @@ -108,7 +108,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { self.dispatchedModelSyncedEvents = [:] } #endif - + /// Internal initializer for testing init(modelRegistration: AmplifyModelRegistration, configuration dataStoreConfiguration: DataStoreConfiguration = .testDefault(), @@ -142,7 +142,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { /// them to `StorageEngine.setUp(modelSchemas:)` public func configure(using amplifyConfiguration: Any?) throws { modelRegistration.registerModels(registry: ModelRegistry.self) - + for modelSchema in ModelRegistry.modelSchemas { dispatchedModelSyncedEvents[modelSchema.name] = AtomicValue(initialValue: false) configuration.updateIsEagerLoad(modelSchema: modelSchema) @@ -151,7 +151,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin { ModelListDecoderRegistry.registerDecoder(DataStoreListDecoder.self) ModelProviderRegistry.registerDecoder(DataStoreModelDecoder.self) } - + /// Initializes the underlying storage engine /// - Returns: success if the engine is successfully initialized or /// a failure with a DataStoreError diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift index 04487a2ed0..564918daa2 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift @@ -83,7 +83,7 @@ extension DataStoreConfiguration { authModeStrategy: authModeStrategy) } #endif - + #if os(watchOS) /// Default configuration with subscriptions disabled for watchOS. DataStore uses subscriptions via websockets, /// which work on the watchOS simulator but not on the device. Running DataStore on watchOS with subscriptions @@ -98,7 +98,7 @@ extension DataStoreConfiguration { .custom() } #endif - + #if os(watchOS) /// Internal method for testing static func testDefault(disableSubscriptions: @escaping () -> Bool = { false }) -> DataStoreConfiguration { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift index 96271bd008..a1c3ec8788 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration.swift @@ -71,7 +71,7 @@ public struct DataStoreConfiguration { public var authModeStrategyType: AuthModeStrategyType public let disableSubscriptions: () -> Bool - + #if os(watchOS) init(errorHandler: @escaping DataStoreErrorHandler, conflictHandler: @escaping DataStoreConflictHandler, diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift index 55fb1c8523..f70585d5a1 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/InternalDatastoreConfiguration.swift @@ -16,7 +16,7 @@ struct InternalDatastoreConfiguration { /// Configuration of the query against the local storage, whether it should load /// the belongs-to/has-one associations or not. /// - ///`isEagerLoad` is true by default, unless the models contain the rootPath + /// `isEagerLoad` is true by default, unless the models contain the rootPath /// which is indication of the codegen that supports for lazy loading. var isEagerLoad: Bool = true @@ -30,12 +30,12 @@ struct InternalDatastoreConfiguration { /// Configuration provided during Datastore initialization, this is a `public` configuration. let pluginConfiguration: DataStoreConfiguration - - mutating func updateIsSyncEnabled(_ isEnabled: Bool) { + + mutating func updateIsSyncEnabled(_ isEnabled: Bool) { self.isSyncEnabled = isEnabled } - mutating func updateIsEagerLoad(modelSchema: ModelSchema) { + mutating func updateIsEagerLoad(modelSchema: ModelSchema) { guard isEagerLoad else { return } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift index ccacde105a..9241da72e2 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListDecoder.swift @@ -10,30 +10,30 @@ import Amplify import Combine public struct DataStoreListDecoder: ModelListDecoder { - + struct Metadata: Codable { let dataStoreAssociatedIdentifiers: [String] let dataStoreAssociatedFields: [String] } - + /// Creates a data structure that is capable of initializing a `List` with /// lazy-load capabilities when the list is being decoded. static func lazyInit(associatedIds: [String], associatedWith: [String]) -> [String: Any?] { return [ "dataStoreAssociatedIdentifiers": associatedIds, - "dataStoreAssociatedFields": associatedWith, + "dataStoreAssociatedFields": associatedWith ] } - + public static func decode(modelType: ModelType.Type, decoder: Decoder) -> AnyModelListProvider? { shouldDecodeToDataStoreListProvider(modelType: modelType, decoder: decoder)?.eraseToAnyModelListProvider() } - + public static func shouldDecodeToDataStoreListProvider(modelType: ModelType.Type, decoder: Decoder) -> DataStoreListProvider? { if let metadata = try? Metadata.init(from: decoder) { return DataStoreListProvider(metadata: metadata) } - + let json = try? JSONValue(from: decoder) switch json { case .array: diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift index c754725026..59aee21603 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreListProvider.swift @@ -28,7 +28,7 @@ public class DataStoreListProvider: ModelListProvider { init(_ elements: [Element]) { self.loadedState = .loaded(elements) } - + public func getState() -> ModelListProviderState { switch loadedState { case .notLoaded(let associatedIdentifiers, let associatedFields): @@ -37,7 +37,7 @@ public class DataStoreListProvider: ModelListProvider { return .loaded(elements) } } - + public func load() async throws -> [Element] { switch loadedState { case .loaded(let elements): @@ -59,7 +59,7 @@ public class DataStoreListProvider: ModelListProvider { self.log.verbose("Loading List of \(Element.schema.name) by \(associatedFields) == \(associatedIdentifiers) ") predicate = QueryPredicateGroup(type: .and, predicates: queryPredicates) } - + do { let elements = try await Amplify.DataStore.query(Element.self, where: predicate) self.loadedState = .loaded(elements) @@ -71,7 +71,7 @@ public class DataStoreListProvider: ModelListProvider { error) } catch { throw error - + } } } @@ -79,13 +79,13 @@ public class DataStoreListProvider: ModelListProvider { public func hasNextPage() -> Bool { false } - + public func getNextPage() async throws -> List { throw CoreError.clientValidation("There is no next page.", "Only call `getNextPage()` when `hasNextPage()` is true.", nil) } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let associatedIdentifiers, diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift index 647785d78f..54ede2c97c 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelDecoder.swift @@ -10,14 +10,14 @@ import Amplify import SQLite public struct DataStoreModelDecoder: ModelProviderDecoder { - + public static let DataStoreSource = "DataStore" - + /// Metadata that contains the foreign key value of a parent model, which is the primary key of the model to be loaded. struct Metadata: Codable { let identifiers: [LazyReferenceIdentifier] let source: String - + init(identifiers: [LazyReferenceIdentifier], source: String = DataStoreSource) { self.identifiers = identifiers self.source = source @@ -27,7 +27,7 @@ public struct DataStoreModelDecoder: ModelProviderDecoder { try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self)) } } - + /// Create a SQLite payload that is capable of initializting a LazyReference, by decoding to `DataStoreModelDecoder.Metadata`. static func lazyInit(identifiers: [LazyReferenceIdentifier]) -> Metadata? { if identifiers.isEmpty { @@ -35,7 +35,7 @@ public struct DataStoreModelDecoder: ModelProviderDecoder { } return Metadata(identifiers: identifiers) } - + public static func decode(modelType: ModelType.Type, decoder: Decoder) -> AnyModelProvider? { if let metadata = try? DataStoreModelDecoder.Metadata(from: decoder) { if metadata.source == DataStoreSource { @@ -44,11 +44,11 @@ public struct DataStoreModelDecoder: ModelProviderDecoder { return nil } } - + if let model = try? ModelType.init(from: decoder) { return DataStoreModelProvider(model: model).eraseToAnyModelProvider() } - + return nil } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift index e6e98f3f8d..4b43c7de2f 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Core/DataStoreModelProvider.swift @@ -9,21 +9,21 @@ import Foundation import Amplify import Combine -public class DataStoreModelProvider: ModelProvider { +public class DataStoreModelProvider: ModelProvider { var loadedState: ModelProviderState - + // Create a "not loaded" model provider with the identifier metadata, useful for hydrating the model init(metadata: DataStoreModelDecoder.Metadata) { self.loadedState = .notLoaded(identifiers: metadata.identifiers) } - + // Create a "loaded" model provider with the model instance init(model: ModelType?) { self.loadedState = .loaded(model: model) } - + // MARK: - APIs - + public func load() async throws -> ModelType? { switch loadedState { case .notLoaded(let identifiers): @@ -46,18 +46,18 @@ public class DataStoreModelProvider: ModelProvider { return model } } - + public func getState() -> ModelProviderState { loadedState } - + public func encode(to encoder: Encoder) throws { switch loadedState { case .notLoaded(let identifiers): let metadata = DataStoreModelDecoder.Metadata(identifiers: identifiers ?? []) var container = encoder.singleValueContainer() try container.encode(metadata) - + case .loaded(let element): try element.encode(to: encoder) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift index 08dffbe272..0a0eb72e03 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Migration/ModelSyncMetadataMigration.swift @@ -11,17 +11,17 @@ import SQLite import AWSPluginsCore class ModelSyncMetadataMigration: ModelMigration { - + weak var storageAdapter: SQLiteStorageEngineAdapter? - + func apply() throws { try performModelMetadataSyncPredicateUpgrade() } - + init(storageAdapter: SQLiteStorageEngineAdapter? = nil) { self.storageAdapter = storageAdapter } - + /// Add the new syncPredicate column for the ModelSyncMetadata system table. /// /// ModelSyncMetadata's syncPredicate column was added in Amplify version 2.22.0 to @@ -47,7 +47,7 @@ class ModelSyncMetadataMigration: ModelMigration { log.debug("Detected ModelSyncMetadata table has syncPredicate column. No migration needed") return false } - + log.debug("Detected ModelSyncMetadata table exists without syncPredicate column.") guard let storageAdapter = storageAdapter else { log.debug("Missing SQLiteStorageEngineAdapter for model migration") @@ -75,7 +75,7 @@ class ModelSyncMetadataMigration: ModelMigration { guard let connection = storageAdapter.connection else { throw DataStoreError.nilSQLiteConnection() } - + let tableInfoStatement = TableInfoStatement(modelSchema: modelSchema) do { let existingColumns = try connection.prepare(tableInfoStatement.stringValue).run() diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift index dc479426b2..08f604de7a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/CascadeDeleteOperation.swift @@ -10,6 +10,7 @@ import Amplify import AWSPluginsCore import Combine +// swiftlint:disable type_body_length file_length /// CascadeDeleteOperation has the following logic: /// 1. Query models from local store based on the following use cases: /// 1a. If the use case is Delete with id, then query by `id` @@ -31,7 +32,7 @@ public class CascadeDeleteOperation: AsynchronousOperation { private let serialQueueSyncDeletions = DispatchQueue(label: "com.amazoncom.Storage.CascadeDeleteOperation.concurrency") private let isDeveloperDefinedModel: Bool - + convenience init( storageAdapter: StorageEngineAdapter, syncEngine: RemoteSyncEngineBehavior?, @@ -110,12 +111,12 @@ public class CascadeDeleteOperation: AsynchronousOperation { syncIfNeededAndFinish(.failure(causedBy: error)) } } - + func queryAndDeleteTransaction() async -> DataStoreResult> { var queriedResult: DataStoreResult<[M]>? var deletedResult: DataStoreResult<[M]>? var associatedModels: [(ModelName, Model)] = [] - + queriedResult = await withCheckedContinuation { continuation in self.storageAdapter.query(self.modelType, modelSchema: self.modelSchema, @@ -139,7 +140,7 @@ public class CascadeDeleteOperation: AsynchronousOperation { deleteResult: deletedResult, associatedModels: associatedModels) } - + // Query using the computed predicate did not return any results, check if model actually exists. do { if try self.storageAdapter.exists(self.modelSchema, withIdentifier: identifier, predicate: nil) { @@ -153,15 +154,15 @@ public class CascadeDeleteOperation: AsynchronousOperation { } catch { queriedResult = .failure(DataStoreError.invalidOperation(causedBy: error)) } - + return collapseResults(queryResult: queriedResult, deleteResult: deletedResult, associatedModels: associatedModels) } - + let modelIds = queriedModels.map { $0.identifier(schema: self.modelSchema).stringValue } logMessage("[CascadeDelete.1] Deleting \(modelSchema.name) with identifiers: \(modelIds)") - + associatedModels = await self.recurseQueryAssociatedModels(modelSchema: self.modelSchema, ids: modelIds) deletedResult = await withCheckedContinuation { continuation in @@ -208,7 +209,7 @@ public class CascadeDeleteOperation: AsynchronousOperation { ids: associatedModelIds) ) } - + return associatedModels } @@ -224,7 +225,7 @@ public class CascadeDeleteOperation: AsynchronousOperation { queryPredicates.append(QueryPredicateOperation(field: associatedField.name, operator: .equals(id))) } let groupedQueryPredicates = QueryPredicateGroup(type: .or, predicates: queryPredicates) - + do { let models = try await withCheckedThrowingContinuation { continuation in storageAdapter.query(modelSchema: modelSchema, predicate: groupedQueryPredicates, eagerLoad: true) { result in @@ -275,7 +276,10 @@ public class CascadeDeleteOperation: AsynchronousOperation { switch transactionResult { case .success(let queryAndDeleteResult): logMessage( - "[CascadeDelete.4] sending a total of \(queryAndDeleteResult.associatedModels.count + queryAndDeleteResult.deletedModels.count) delete mutations" + """ + [CascadeDelete.4] sending a total of + \(queryAndDeleteResult.associatedModels.count + queryAndDeleteResult.deletedModels.count) delete mutations + """ ) switch deleteInput { case .withIdentifier, .withIdentifierAndCondition: @@ -549,3 +553,4 @@ extension CascadeDeleteOperation: DefaultLogger { Self.log } } +// swiftlint:enable type_body_length file_length diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift index 3a74af0a60..e33537baa5 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/ModelStorageBehavior.swift @@ -32,7 +32,7 @@ protocol ModelStorageBehavior { withId id: Model.Identifier, condition: QueryPredicate?, completion: @escaping DataStoreCallback) - + func delete(_ modelType: M.Type, modelSchema: ModelSchema, withIdentifier identifier: ModelIdentifierProtocol, diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift index 5559050c6e..7ff35dccb2 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Model+SQLite.swift @@ -82,7 +82,7 @@ extension Model { existingFieldOptionalValue = self[internalFieldName] } } - + guard let existingFieldValue = existingFieldOptionalValue else { return nil } @@ -147,7 +147,6 @@ extension Model { return values } - /// Given a serialized JSON model, returns the serialized value of its primary key. /// The returned value is either the value of the field or the serialization of multiple values in case of a composite PK. /// - Parameters: diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+AlterTable.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+AlterTable.swift index b60016d856..b29800d8d7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+AlterTable.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/SQLStatement+AlterTable.swift @@ -26,9 +26,8 @@ struct AlterTableStatement: SQLStatement { struct AlterTableAddColumnStatement: SQLStatement { var modelSchema: ModelSchema var field: ModelField - + var stringValue: String { "ALTER TABLE \"\(modelSchema.name)\" ADD COLUMN \"\(field.sqlName)\" \"\(field.sqlType)\";" } } - diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift index 7ada38d738..6045206d6d 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/Statement+Model.swift @@ -53,7 +53,6 @@ extension Statement: StatementModelConvertible { Amplify.Logging.logger(forCategory: .dataStore) } - func convert(to modelType: M.Type, withSchema modelSchema: ModelSchema, using statement: SelectStatement, @@ -173,8 +172,7 @@ extension Statement: StatementModelConvertible { private func convertCollection(field: ModelField, schema: ModelSchema, from element: Element, path: [String]) -> Any? { if field.isArray && field.hasAssociation, - case let .some(.hasMany(associatedFieldName: associatedFieldName, associatedFieldNames: associatedFieldNames)) = field.association - { + case let .some(.hasMany(associatedFieldName: associatedFieldName, associatedFieldNames: associatedFieldNames)) = field.association { // Construct the lazy list based on the field reference name and `@@primarykey` or primary key field of the parent if associatedFieldNames.count <= 1, let associatedFieldName = associatedFieldName { let primaryKeyName = schema.primaryKey.isCompositeKey @@ -221,12 +219,11 @@ extension Statement: StatementModelConvertible { private func schemeMetadata(schema: ModelSchema, element: Element, path: [String]) -> ModelValues { var metadata = [ - "__typename": schema.name, + "__typename": schema.name ] if schema.primaryKey.isCompositeKey, - let compositeKey = getValue(from: element, by: path + [ModelIdentifierFormat.Custom.sqlColumnName]) - { + let compositeKey = getValue(from: element, by: path + [ModelIdentifierFormat.Custom.sqlColumnName]) { metadata.updateValue(String(describing: compositeKey), forKey: ModelIdentifierFormat.Custom.sqlColumnName) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift index 1f65ffc7e7..ae3549bf81 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+SQLite.swift @@ -10,6 +10,7 @@ import Foundation import SQLite import AWSPluginsCore +// swiftlint:disable type_body_length file_length /// [SQLite](https://sqlite.org) `StorageEngineAdapter` implementation. This class provides /// an integration layer between the AppSyncLocal `StorageEngine` and SQLite for local storage. final class SQLiteStorageEngineAdapter: StorageEngineAdapter { @@ -118,9 +119,9 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { storageAdapter: self, modelSchemas: modelSchemas) let mutationSyncMetadataMigration = MutationSyncMetadataMigration(delegate: delegate) - + let modelSyncMetadataMigration = ModelSyncMetadataMigration(storageAdapter: self) - + let modelMigrations = ModelMigrations(modelMigrations: [mutationSyncMetadataMigration, modelSyncMetadataMigration]) do { @@ -246,8 +247,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } } - - + func delete(_ modelType: M.Type, modelSchema: ModelSchema, withIdentifier identifier: ModelIdentifierProtocol, @@ -265,7 +265,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { } } } - + func delete(untypedModelType modelType: Model.Type, modelSchema: ModelSchema, withId id: Model.Identifier, @@ -277,7 +277,7 @@ final class SQLiteStorageEngineAdapter: StorageEngineAdapter { condition: condition, completion: completion) } - + func delete(untypedModelType modelType: Model.Type, modelSchema: ModelSchema, withIdentifier id: ModelIdentifierProtocol, @@ -567,3 +567,4 @@ extension SQLiteStorageEngineAdapter: DefaultLogger { Self.log } } +// swiftlint:enable type_body_length file_length diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift index 60c1a6637c..212840733f 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/SQLite/StorageEngineAdapter+UntypedModel.swift @@ -42,7 +42,7 @@ extension SQLiteStorageEngineAdapter { let statement = InsertStatement(model: untypedModel, modelSchema: modelSchema) _ = try connection.prepare(statement.stringValue).run(statement.variables) } - + query(modelSchema: modelSchema, predicate: untypedModel.identifier(schema: modelSchema).predicate, eagerLoad: eagerLoad) { @@ -58,7 +58,7 @@ extension SQLiteStorageEngineAdapter { completion(.failure(error)) } } - + } catch { completion(.failure(causedBy: error)) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift index 8bfe682307..b911f0a1c3 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Storage/StorageEngineAdapter.swift @@ -72,7 +72,6 @@ extension StorageEngineAdapter { delete(modelType, modelSchema: modelType.schema, filter: predicate, completion: completion) } - func delete(untypedModelType modelType: Model.Type, withIdentifier identifier: ModelIdentifierProtocol, condition: QueryPredicate? = nil, diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift index 775b576da5..6e6781716a 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStoreObserveQueryOperation.swift @@ -17,9 +17,9 @@ protocol DataStoreObserveQueryOperation { class ObserveQueryRequest: AmplifyOperationRequest { var options: Any - + typealias Options = Any - + init(options: Any) { self.options = options } @@ -44,11 +44,11 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr typealias InProcess = DataStoreQuerySnapshot var request: ObserveQueryRequest var context = InternalTaskAsyncThrowingSequenceContext>() - + private let serialQueue = DispatchQueue(label: "com.amazonaws.AWSDataStoreObseverQueryOperation.serialQueue", target: DispatchQueue.global()) private let itemsChangedPeriodicPublishTimeInSeconds: DispatchQueue.SchedulerTimeType.Stride = 2 - + let modelType: M.Type let modelSchema: ModelSchema let predicate: QueryPredicate? @@ -64,16 +64,16 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr var batchItemsChangedSink: AnyCancellable? var itemsChangedSink: AnyCancellable? var modelSyncedEventSink: AnyCancellable? - + var currentSnapshot: DataStoreQuerySnapshot { DataStoreQuerySnapshot(items: currentItems.sortedModels, isSynced: dispatchedModelSyncedEvent.get()) } - + private var running = false - + var dataStoreStatePublisher: AnyPublisher var dataStoreStateSink: AnyCancellable? - + init(request: ObserveQueryRequest = .init(options: []), context: InternalTaskAsyncThrowingSequenceContext> = InternalTaskAsyncThrowingSequenceContext>(), modelType: M.Type, @@ -87,7 +87,7 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr dataStoreStatePublisher: AnyPublisher) { self.request = request self.context = context - + self.modelType = modelType self.modelSchema = modelSchema self.predicate = predicate @@ -99,22 +99,22 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr self.stopwatch = Stopwatch() self.observeQueryStarted = false self.currentItems = SortedList(sortInput: sortInput, modelSchema: modelSchema) - + self.dataStoreStatePublisher = dataStoreStatePublisher } - + func run() async throws { guard !running else { return } running = true - + subscribeToDataStoreState() startObserveQuery() } - + func subscribeToDataStoreState() { serialQueue.async { [weak self] in guard let self = self else { return } - + self.dataStoreStateSink = self.dataStoreStatePublisher.sink { completion in switch completion { case .finished: @@ -133,17 +133,17 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr } } - + public func cancel() { serialQueue.sync { if let itemsChangedSink = itemsChangedSink { itemsChangedSink.cancel() } - + if let batchItemsChangedSink = batchItemsChangedSink { batchItemsChangedSink.cancel() } - + if let modelSyncedEventSink = modelSyncedEventSink { modelSyncedEventSink.cancel() } @@ -244,7 +244,7 @@ class ObserveQueryTaskRunner: InternalTaskRunner, InternalTaskAsyncThr ) .sink(receiveCompletion: self.onReceiveCompletion(completed:), receiveValue: self.onItemsChangeDuringSync(mutationEvents:)) - + self.itemsChangedSink = self.dataStorePublisher.publisher .filter { _ in self.dispatchedModelSyncedEvent.get() } .filter(self.filterByModelName(mutationEvent:)) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStorePublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStorePublisher.swift index 6e3dd97e31..9c40ead977 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStorePublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/DataStorePublisher.swift @@ -39,5 +39,3 @@ protocol ModelSubcriptionBehavior { func sendFinished() } - - diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift index a3f0ad02b7..755a105f91 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/ObserveTaskRunner.swift @@ -25,18 +25,18 @@ class ObserveTaskRunner: InternalTaskRunner, InternalTaskAsyncThrowingSequence, var publisher: AnyPublisher var sink: AnyCancellable? var context = InternalTaskAsyncThrowingSequenceContext() - + private var running = false - + public init(request: ObserveRequest = .init(), publisher: AnyPublisher) { self.request = request self.publisher = publisher } - + func run() async throws { guard !running else { return } running = true - + self.sink = publisher.sink { completion in switch completion { case .finished: diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift index 4c3b72f55c..b9eed6bbd9 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Subscribe/Support/Model+Sort.swift @@ -108,13 +108,13 @@ extension ModelSchema { value2Optional: value2Optional) .sortComparator(sortOrder: sortOrder) } - + if let value1Optional = value1 as? Int64?, let value2Optional = value2 as? Int64? { return ModelValueCompare(value1Optional: value1Optional, value2Optional: value2Optional) .sortComparator(sortOrder: sortOrder) } - + return false case .double: guard let value1Optional = value1 as? Double?, let value2Optional = value2 as? Double? else { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift index 1fc206425e..6785669c6f 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOperation.swift @@ -29,13 +29,13 @@ final class InitialSyncOperation: AsynchronousOperation { private var syncPageSize: UInt { return dataStoreConfiguration.syncPageSize } - + private var syncPredicate: QueryPredicate? { return dataStoreConfiguration.syncExpressions.first { $0.modelSchema.name == self.modelSchema.name }?.modelPredicate() } - + private var syncPredicateString: String? { guard let syncPredicate = syncPredicate, let data = try? syncPredicateEncoder.encode(syncPredicate) else { @@ -43,18 +43,18 @@ final class InitialSyncOperation: AsynchronousOperation { } return String(data: data, encoding: .utf8) } - + private lazy var _syncPredicateEncoder: JSONEncoder = { var encoder = JSONEncoder() encoder.dateEncodingStrategy = ModelDateFormatting.encodingStrategy encoder.outputFormatting = [.sortedKeys] return encoder }() - + var syncPredicateEncoder: JSONEncoder { _syncPredicateEncoder } - + private let initialSyncOperationTopic: PassthroughSubject var publisher: AnyPublisher { return initialSyncOperationTopic.eraseToAnyPublisher() @@ -110,7 +110,7 @@ final class InitialSyncOperation: AsynchronousOperation { return nil } } - + /// Retrieve the lastSync time for the request before performing the query operation. /// /// - Parameter lastSyncMetadata: Retrieved persisted sync metadata for this model @@ -129,7 +129,7 @@ final class InitialSyncOperation: AsynchronousOperation { initialSyncOperationTopic.send(.started(modelName: modelSchema.name, syncType: syncType)) return lastSyncTime } - + private func syncPredicateChanged(_ lastSyncPredicate: String?, _ currentSyncPredicate: String?) -> Bool { switch (lastSyncPredicate, currentSyncPredicate) { case (.some, .some): @@ -140,7 +140,7 @@ final class InitialSyncOperation: AsynchronousOperation { return false } } - + private func getLastSyncTime(lastSync: Int64?) -> Int64? { guard let lastSync = lastSync else { return nil @@ -174,7 +174,7 @@ final class InitialSyncOperation: AsynchronousOperation { if self.isAuthSignedOutError(apiError: apiError) { self.log.error("Sync for \(self.modelSchema.name) failed due to signed out error \(apiError.errorDescription)") } - + // TODO: Retry query on error let error = DataStoreError.api(apiError) self.dataStoreConfiguration.errorHandler(error) @@ -250,7 +250,7 @@ final class InitialSyncOperation: AsynchronousOperation { finish(result: .failure(DataStoreError.nilStorageAdapter())) return } - + let syncMetadata = ModelSyncMetadata(id: modelSchema.name, lastSync: lastSyncTime, syncPredicate: syncPredicateString) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift index 3c2dec737d..dbfe953ab1 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/InitialSync/InitialSyncOrchestrator.swift @@ -164,7 +164,7 @@ final class AWSInitialSyncOrchestrator: InitialSyncOrchestrator { allMessages.joined(separator: "\n"), underlyingError ) - + return .failure(syncError) } @@ -215,7 +215,7 @@ extension AWSInitialSyncOrchestrator { else { return false } - + // The following check is to categorize the error as an unauthorized error when the process fails to retrieve // the authorization token. This is taken directly from `AuthTokenURLRequestInterceptor`'s error handling path // that returns an APIError.operationError with an underlying AuthError. @@ -246,7 +246,7 @@ extension AWSInitialSyncOrchestrator { case .unauthorized = AppSyncErrorType(errorTypeValue) { return true } - + // Check is API error is of unauthorized type if case let .api(amplifyError, _) = datastoreError, let apiError = amplifyError as? APIError { @@ -255,13 +255,13 @@ extension AWSInitialSyncOrchestrator { options: .caseInsensitive) != nil { return true } - + if case .httpStatusError(let statusCode, _) = apiError, - (statusCode == 401 || statusCode == 403) { + statusCode == 401 || statusCode == 403 { return true } } - + return false } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift index 88851515f7..bf655df7b1 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/AWSMutationDatabaseAdapter/AWSMutationDatabaseAdapter+MutationEventIngester.swift @@ -13,15 +13,15 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { /// Accepts a mutation event without a version, applies the latest version from the MutationSyncMetadata table, /// writes the updated mutation event to the local database, then submits it to `mutationEventSubject` - func submit(mutationEvent: MutationEvent, completion: @escaping (Result)->Void) { + func submit(mutationEvent: MutationEvent, completion: @escaping (Result) -> Void) { Task { log.verbose("\(#function): \(mutationEvent)") - + guard let storageAdapter = self.storageAdapter else { completion(.failure(DataStoreError.nilStorageAdapter())) return } - + self.resolveConflictsThenSave(mutationEvent: mutationEvent, storageAdapter: storageAdapter, completion: completion) @@ -32,7 +32,7 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester { /// rejects the event with an error func resolveConflictsThenSave(mutationEvent: MutationEvent, storageAdapter: StorageEngineAdapter, - completion: @escaping (Result)->Void) { + completion: @escaping (Result) -> Void) { // We don't want to query MutationSync because a) we already have the model, and b) delete mutations // are submitted *after* the delete has already been applied to the local data store, meaning there is no model diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventIngester.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventIngester.swift index 6a116d76e4..854cdd03e1 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventIngester.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/MutationEvent/MutationEventIngester.swift @@ -10,5 +10,5 @@ import Combine /// Ingests MutationEvents from and writes them to the MutationEvent persistent store protocol MutationEventIngester: AnyObject { - func submit(mutationEvent: MutationEvent, completion: @escaping (Result)->Void) + func submit(mutationEvent: MutationEvent, completion: @escaping (Result) -> Void) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift index 5e833b41a5..829cc68296 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift @@ -71,7 +71,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { .$state .sink { [weak self] newState in guard let self else { return } - + self.log.verbose("New state: \(newState)") self.mutationDispatchQueue.async { self.respond(to: newState) @@ -139,7 +139,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { queryMutationEventsFromStorage { [weak self] in guard let self = self else { return } - + self.operationQueue.isSuspended = false // State machine notification to ".receivedSubscription" will be handled in `receive(subscription:)` mutationEventPublisher.publisher.subscribe(self) @@ -337,7 +337,7 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { paginationInput: nil, eagerLoad: true) { [weak self] result in guard let self else { return } - + switch result { case .success(let events): self.dispatchOutboxStatusEvent(isEmpty: events.isEmpty) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift index 2e4528a2e6..bbc4ec0895 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/ProcessMutationErrorFromCloudOperation.swift @@ -10,6 +10,7 @@ import Combine import Foundation import AWSPluginsCore +// swiftlint:disable type_body_length file_length /// Checks the GraphQL error response for specific error scenarios related to data synchronziation to the local store. /// 1. When there is an APIError which is for an unauthenticated user, call the error handler. /// 2. When there is a "conditional request failed" error, then emit to the Hub a 'conditionalSaveFailed' event. @@ -28,7 +29,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { private var mutationOperation: AtomicValue>?> private weak var api: APICategoryGraphQLBehaviorExtended? private weak var reconciliationQueue: IncomingEventReconciliationQueue? - + init(dataStoreConfiguration: DataStoreConfiguration, mutationEvent: MutationEvent, api: APICategoryGraphQLBehaviorExtended, @@ -314,7 +315,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { if case .failure(let error) = cloudResult { dataStoreConfiguration.errorHandler(error) } - + if case let .success(graphQLResponse) = cloudResult { if case .failure(let error) = graphQLResponse { dataStoreConfiguration.errorHandler(error) @@ -330,11 +331,11 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { finish(result: .failure(dataStoreError)) return } - + reconciliationQueue.offer([graphQLResult], modelName: mutationEvent.modelName) } } - + finish(result: .success(nil)) } @@ -357,7 +358,7 @@ class ProcessMutationErrorFromCloudOperation: AsynchronousOperation { } let identifier = remoteModel.model.identifier(schema: modelSchema) - + storageAdapter.delete(untypedModelType: modelType, modelSchema: modelSchema, withIdentifier: identifier, @@ -471,3 +472,4 @@ extension ProcessMutationErrorFromCloudOperation: DefaultLogger { Self.log } } +// swiftlint:enable type_body_length file_length diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift index dac31dd0bf..6cc1cac59f 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/SyncMutationToCloudOperation.swift @@ -47,7 +47,7 @@ class SyncMutationToCloudOperation: AsynchronousOperation { if let modelSchema = ModelRegistry.modelSchema(from: mutationEvent.modelName), let mutationType = GraphQLMutationType(rawValue: mutationEvent.mutationType) { - + self.authTypesIterator = await authModeStrategy.authTypesFor(schema: modelSchema, operation: mutationType.toModelOperation()) } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift index ee5c84c460..db2ae3b9e4 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine+AuthModeStrategyDelegate.swift @@ -11,11 +11,11 @@ import Foundation import AWSPluginsCore extension RemoteSyncEngine: AuthModeStrategyDelegate { - + func isUserLoggedIn() async -> Bool { if let authProviderFactory = api as? APICategoryAuthProviderFactoryBehavior, let oidcAuthProvider = authProviderFactory.apiAuthProviderFactory().oidcAuthProvider() { - + // if OIDC is used as authentication provider // use `getLatestAuthToken` var isLoggedInWithOIDC = false diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift index b361e0ab22..26bb453571 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngine.swift @@ -10,6 +10,7 @@ import Combine import Foundation import AWSPluginsCore +// swiftlint:disable type_body_length file_length class RemoteSyncEngine: RemoteSyncEngineBehavior { weak var storageAdapter: StorageEngineAdapter? @@ -84,10 +85,10 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { OutgoingMutationQueue(storageAdapter: storageAdapter, dataStoreConfiguration: dataStoreConfiguration, authModeStrategy: resolvedAuthStrategy) - + // swiftlint:disable line_length let reconciliationQueueFactory = reconciliationQueueFactory ?? AWSIncomingEventReconciliationQueue.init(modelSchemas:api:storageAdapter:syncExpressions:auth:authModeStrategy:modelReconciliationQueueFactory:disableSubscriptions:) - + // swiftlint:enable line_length let initialSyncOrchestratorFactory = initialSyncOrchestratorFactory ?? AWSInitialSyncOrchestrator.init(dataStoreConfiguration:authModeStrategy:api:reconciliationQueue:storageAdapter:) @@ -245,7 +246,7 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { } } - func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result)->Void) { + func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result) -> Void) { mutationEventIngester.submit(mutationEvent: mutationEvent, completion: completion) } @@ -278,7 +279,7 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior { } } } - + private func initializeSubscriptions(api: APICategoryGraphQLBehaviorExtended, storageAdapter: StorageEngineAdapter) async { log.debug("[InitializeSubscription] \(#function)") @@ -448,3 +449,4 @@ extension RemoteSyncEngine: Resettable { } } } +// swiftlint:enable type_body_length file_length diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngineBehavior.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngineBehavior.swift index bc9cb80634..ee5710ff21 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngineBehavior.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/RemoteSyncEngineBehavior.swift @@ -49,7 +49,7 @@ protocol RemoteSyncEngineBehavior: AnyObject { /// Submits a new mutation for synchronization to the remote API. The response will be handled by the appropriate /// reconciliation queue - func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result)->Void) + func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result) -> Void) var publisher: AnyPublisher { get } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift index 0f116dec8e..7705120b4b 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueue.swift @@ -44,7 +44,7 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu return modelSchemasCount == reconciliationQueueConnectionStatus.count } private let modelSchemasCount: Int - + init(modelSchemas: [ModelSchema], api: APICategoryGraphQLBehaviorExtended, storageAdapter: StorageEngineAdapter, @@ -52,27 +52,27 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu auth: AuthCategoryBehavior? = nil, authModeStrategy: AuthModeStrategy, modelReconciliationQueueFactory: ModelReconciliationQueueFactory? = nil, - disableSubscriptions: @escaping () -> Bool = { false } ) async { + disableSubscriptions: @escaping () -> Bool = { false }) async { self.modelSchemasCount = modelSchemas.count self.modelReconciliationQueueSinks.set([:]) self.eventReconciliationQueueTopic = CurrentValueSubject(.idle) self.reconciliationQueues.set([:]) self.reconciliationQueueConnectionStatus = [:] self.reconcileAndSaveQueue = ReconcileAndSaveQueue(modelSchemas) - + if let modelReconciliationQueueFactory = modelReconciliationQueueFactory { self.modelReconciliationQueueFactory = modelReconciliationQueueFactory } else { self.modelReconciliationQueueFactory = AWSModelReconciliationQueue.init } - + // TODO: Add target for SyncEngine system to help prevent thread explosion and increase performance // https://github.com/aws-amplify/amplify-ios/issues/399 self.connectionStatusSerialQueue = DispatchQueue(label: "com.amazonaws.DataStore.AWSIncomingEventReconciliationQueue") let subscriptionsDisabled = disableSubscriptions() - + #if targetEnvironment(simulator) && os(watchOS) if !subscriptionsDisabled { let message = """ @@ -102,7 +102,7 @@ final class AWSIncomingEventReconciliationQueue: IncomingEventReconciliationQueu auth, authModeStrategy, subscriptionsDisabled ? OperationDisabledIncomingSubscriptionEventPublisher() : nil) - + reconciliationQueues.with { reconciliationQueues in reconciliationQueues[modelName] = queue } @@ -207,7 +207,8 @@ extension AWSIncomingEventReconciliationQueue: DefaultLogger { // MARK: - Static factory extension AWSIncomingEventReconciliationQueue { - static let factory: IncomingEventReconciliationQueueFactory = { modelSchemas, api, storageAdapter, syncExpressions, auth, authModeStrategy, _, disableSubscriptions in + static let factory: IncomingEventReconciliationQueueFactory = { + modelSchemas, api, storageAdapter, syncExpressions, auth, authModeStrategy, _, disableSubscriptions in await AWSIncomingEventReconciliationQueue(modelSchemas: modelSchemas, api: api, storageAdapter: storageAdapter, @@ -238,7 +239,7 @@ extension AWSIncomingEventReconciliationQueue: Resettable { // We're sometimes hitting a deadlock when waiting for them to finish. Commenting this out and letting // the tests continue onto the next works pretty well, but ideally ReconcileAndLocalSaveOperation's should // always finish. We can uncomment this to explore a better fix that will still gives us test stability. - //reconcileAndSaveQueue.waitUntilOperationsAreFinished() + // reconcileAndSaveQueue.waitUntilOperationsAreFinished() log.verbose("Resetting reconcileAndSaveQueue: finished") log.verbose("Cancelling AWSIncomingEventReconciliationQueue") diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/OperationDisabledSubscriptionEventPublisher.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/OperationDisabledSubscriptionEventPublisher.swift index 277b4685d8..de12d96dca 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/OperationDisabledSubscriptionEventPublisher.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/OperationDisabledSubscriptionEventPublisher.swift @@ -23,7 +23,7 @@ final class OperationDisabledIncomingSubscriptionEventPublisher: IncomingSubscri let apiError = APIError.operationError(AppSyncErrorType.operationDisabled.rawValue, "", nil) let dataStoreError = DataStoreError.api(apiError, nil) subscriptionEventSubject.send(completion: .failure(dataStoreError)) - + } func cancel() { diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift index 86c7aca2c9..7eacedb029 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/AWSModelReconciliationQueue.swift @@ -111,7 +111,7 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { authModeStrategy: authModeStrategy ) } - + self.incomingSubscriptionEvents = resolvedIncomingSubscriptionEvents self.reconcileAndLocalSaveOperationSinks = AtomicValue(initialValue: Set()) self.incomingEventsSink = resolvedIncomingSubscriptionEvents @@ -122,7 +122,7 @@ final class AWSModelReconciliationQueue: ModelReconciliationQueue { self?.receive(receiveValue) }) } - + /// (Re)starts the incoming subscription event queue. func start() { incomingSubscriptionEventQueue.isSuspended = false @@ -289,7 +289,7 @@ extension AWSModelReconciliationQueue { case .operationDisabled = AppSyncErrorType(errorMessage) { return true } - + if let responseError = error as? GraphQLResponseError, let graphQLError = graphqlErrors(from: responseError)?.first, let errorTypeValue = errorTypeValueFrom(graphQLError: graphQLError), diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift index 9afaf2e8a1..3d926d9719 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/ReconcileAndLocalSaveOperation.swift @@ -10,6 +10,7 @@ import Combine import Foundation import AWSPluginsCore +// swiftlint:disable type_body_length file_length /// Reconciles an incoming model mutation with the stored model. If there is no conflict (e.g., the incoming model has /// a later version than the stored model), then write the new data to the store. class ReconcileAndLocalSaveOperation: AsynchronousOperation { @@ -42,7 +43,7 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { } var isEagerLoad: Bool = true - + init(modelSchema: ModelSchema, remoteModels: [RemoteModel], storageAdapter: StorageEngineAdapter?, @@ -56,13 +57,13 @@ class ReconcileAndLocalSaveOperation: AsynchronousOperation { self.mutationEventPublisher = PassthroughSubject() self.cancellables = Set() - + // `isEagerLoad` is true by default, unless the models contain the rootPath // which is indication that codegenerated model types support for lazy loading. if isEagerLoad && ModelRegistry.modelType(from: modelSchema.name)?.rootPath != nil { self.isEagerLoad = false } - + super.init() self.stateMachineSink = self.stateMachine @@ -469,3 +470,4 @@ enum ReconcileAndLocalSaveOperationEvent { case mutationEvent(MutationEvent) case mutationEventDropped(modelName: String, error: DataStoreError? = nil) } +// swiftlint:enable type_body_length file_length diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift index 9115e96cd5..5086bd7059 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/SubscriptionSync/ReconcileAndLocalSave/RemoteSyncReconciler.swift @@ -84,7 +84,7 @@ struct RemoteSyncReconciler { guard remoteModel.syncMetadata.version > localMetadata.version else { return nil } - + return remoteModel.syncMetadata.deleted ? .delete(remoteModel) : .update(remoteModel) } } diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift index 5d9e157475..d84dad4ce7 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/Support/MutationEvent+Query.swift @@ -56,7 +56,7 @@ extension MutationEvent { completion: completion ) } - + private static func pendingMutationEvents(for modelIds: [(String, String)], storageAdapter: StorageEngineAdapter, completion: @escaping DataStoreCallback<[MutationEvent]>) { @@ -74,7 +74,7 @@ extension MutationEvent { let groupedQueryPredicates = QueryPredicateGroup(type: .or, predicates: queryPredicates) let final = QueryPredicateGroup(type: .and, predicates: [groupedQueryPredicates, predicate]) let sort = QuerySortDescriptor(fieldName: fields.createdAt.stringValue, order: .ascending) - + do { let mutationEvents = try await withCheckedThrowingContinuation { continuation in storageAdapter.query(MutationEvent.self, @@ -85,7 +85,7 @@ extension MutationEvent { continuation.resume(with: result) } } - + queriedMutationEvents.append(contentsOf: mutationEvents) } catch { completion(.failure(causedBy: error))