diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 00000000..1e5b841f --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,275 @@ +# +# Copyright 2026 Adobe. All rights reserved. +# This file is licensed to you under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. You may obtain a copy +# of the License at http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed under +# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +# OF ANY KIND, either express or implied. See the License for the specific language +# governing permissions and limitations under the License. +# + +version: 2.1 + +orbs: + macos: circleci/macos@2 + +workflows: + version: 2 + build-and-test: + jobs: + - validate-code + - test-ios-unit: + requires: + - validate-code + - test-ios-functional: + requires: + - validate-code + - test-ios-integration: + requires: + - validate-code + - test-tvos-unit: + requires: + - validate-code + - test-tvos-functional: + requires: + - validate-code + - build-xcframework-and-app: + requires: + - validate-code + +commands: + install_dependencies: + steps: + - run: + name: Install XcodeGen + command: brew install xcodegen + + - restore_cache: + name: Restore Gemfile cache + keys: + - gems-v1-{{ checksum "Gemfile.lock" }} + - gems-v1- + + - run: + name: Configure Bundler + command: | + bundle config set path 'vendor/bundle' + bundle check || bundle install + + - save_cache: + name: Save Gemfile cache + key: gems-v1-{{ checksum "Gemfile.lock" }} + paths: + - vendor/bundle + + - restore_cache: + name: Restore CocoaPods cache + keys: + - pods-v1-{{ checksum "Podfile.lock" }} + - pods-v1- + + - run: + name: Install CocoaPods + command: make ci-pod-install + + - save_cache: + name: Save CocoaPods cache + key: pods-v1-{{ checksum "Podfile.lock" }} + paths: + - Pods + - ~/.cocoapods + + prestart_ios_simulator: + steps: + - macos/preboot-simulator: + platform: "iOS" + device: "iPhone 16" + version: "18.6" + + prestart_tvos_simulator: + steps: + - macos/preboot-simulator: + platform: "tvOS" + device: "Apple TV" + version: "18.5" + + parse_and_upload_coverage: + description: "Convert .xcresult → Cobertura XML and upload to Codecov" + parameters: + path: { type: string } + flag: { type: string } + steps: + - run: + name: Install xcresultparser + command: brew list xcresultparser || brew install xcresultparser + + - run: + name: Parse .xcresult bundle(s) + command: | + set -eo pipefail + mkdir -p ./build/coverage + + BUNDLE="<< parameters.path >>" + + if [ -d "$BUNDLE" ]; then + echo "Directory given; searching for .xcresult…" + RESULT_FILES=$(find "$BUNDLE" -name "*.xcresult") + [ -z "$RESULT_FILES" ] && { echo "No .xcresult found"; exit 0; } + + COUNT=$(echo "$RESULT_FILES" | wc -w) + if [ "$COUNT" -gt 1 ]; then + echo "Merging $COUNT result bundles" + MERGE_CMD="xcrun xccov merge --output ./build/Merged.xcresult" + for f in $RESULT_FILES; do MERGE_CMD="$MERGE_CMD $f"; done + eval "$MERGE_CMD" + xcresultparser --output-format cobertura ./build/Merged.xcresult > ./build/coverage/coverage.xml + else + echo "Single bundle found" + xcresultparser --output-format cobertura $RESULT_FILES > ./build/coverage/coverage.xml + fi + else + echo "File given; parsing $BUNDLE" + xcresultparser --output-format cobertura "$BUNDLE" > ./build/coverage/coverage.xml + fi + + - run: + name: Upload coverage to Codecov + command: | + python3 -m pip install --user --break-system-packages codecov-cli || true + export PATH="$(python3 -m site --user-base)/bin:$PATH" + codecovcli upload-process \ + -t "${CODECOV_TOKEN}" \ + -f ./build/coverage/coverage.xml \ + -F "<< parameters.flag >>" \ + -n "<< parameters.flag >>" \ + --disable-search || echo "Codecov upload failed (non-fatal)" + +jobs: + validate-code: + resource_class: m4pro.medium + macos: + xcode: 26.6.0 + + steps: + - checkout + - install_dependencies + - run: + name: Lint Source Code + command: make lint + + test-ios-unit: + resource_class: m4pro.medium + macos: + xcode: 26.6.0 + + environment: + IOS_DEVICE_NAME: "iPhone 16" + IOS_VERSION: "18.6" + + steps: + - checkout + - install_dependencies + - prestart_ios_simulator + - run: + name: Run Unit Tests (iOS) + command: make unit-test-ios + - parse_and_upload_coverage: + path: build/reports/iosUnitResults.xcresult + flag: ios-unit-tests + + test-ios-functional: + resource_class: m4pro.medium + macos: + xcode: 26.6.0 + + environment: + IOS_DEVICE_NAME: "iPhone 16" + IOS_VERSION: "18.6" + + steps: + - checkout + - install_dependencies + - prestart_ios_simulator + - run: + name: Run Functional Tests (iOS) + command: make functional-test-ios + - parse_and_upload_coverage: + path: build/reports/iosFunctionalResults.xcresult + flag: ios-functional-tests + + test-ios-integration: + resource_class: m4pro.medium + macos: + xcode: 26.6.0 + + environment: + IOS_DEVICE_NAME: "iPhone 16" + IOS_VERSION: "18.6" + + steps: + - checkout + - install_dependencies + - prestart_ios_simulator + - run: + name: Run Integration Tests (iOS) + command: make integration-test-ios + - parse_and_upload_coverage: + path: build/reports/iosIntegrationUpstreamResults.xcresult + flag: ios-integration-tests + + test-tvos-unit: + resource_class: m4pro.medium + macos: + xcode: 26.6.0 + + environment: + TVOS_DEVICE_NAME: "Apple TV" + TVOS_VERSION: "18.5" + + steps: + - checkout + - install_dependencies + - prestart_tvos_simulator + - run: + name: Run Unit Tests (tvOS) + command: make unit-test-tvos + - parse_and_upload_coverage: + path: build/reports/tvosUnitResults.xcresult + flag: tvos-unit-tests + + test-tvos-functional: + resource_class: m4pro.medium + macos: + xcode: 26.6.0 + + environment: + TVOS_DEVICE_NAME: "Apple TV" + TVOS_VERSION: "18.5" + + steps: + - checkout + - install_dependencies + - prestart_tvos_simulator + - run: + name: Run Functional Tests (tvOS) + command: make functional-test-tvos + - parse_and_upload_coverage: + path: build/reports/tvosFunctionalResults.xcresult + flag: tvos-functional-tests + + build-xcframework-and-app: + resource_class: m4pro.medium + macos: + xcode: 26.6.0 + + steps: + - checkout + - install_dependencies + - run: + name: Build XCFramework + command: make archive + - run: + name: Build Test App + command: make build-app diff --git a/AEPEdge.podspec b/AEPEdge.podspec index 019af5b2..ecca8453 100644 --- a/AEPEdge.podspec +++ b/AEPEdge.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "AEPEdge" - s.version = "5.2.0" + s.version = "5.3.0" s.summary = "Experience Platform Edge extension for Adobe Experience Platform Mobile SDK. Written and maintained by Adobe." s.description = <<-DESC diff --git a/AEPEdge.xcodeproj/project.pbxproj b/AEPEdge.xcodeproj/project.pbxproj index 021b0cbb..8f30a635 100644 --- a/AEPEdge.xcodeproj/project.pbxproj +++ b/AEPEdge.xcodeproj/project.pbxproj @@ -21,6 +21,16 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ + DA0A02000000000000000000 /* DeviceAttributesConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01000000000000000000 /* DeviceAttributesConstants.swift */; }; + DA0A02010000000000000000 /* Event+DeviceAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01010000000000000000 /* Event+DeviceAttributes.swift */; }; + DA0A02020000000000000000 /* DeviceAttributesRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01020000000000000000 /* DeviceAttributesRequestBuilder.swift */; }; + DA0A02030000000000000000 /* DeviceAttributesNetworkService.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01030000000000000000 /* DeviceAttributesNetworkService.swift */; }; + DA0A020A0000000000000000 /* DeviceAttributesNetworkResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A010A0000000000000000 /* DeviceAttributesNetworkResult.swift */; }; + DA0A02050000000000000000 /* DeviceAttributesHitProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01050000000000000000 /* DeviceAttributesHitProcessor.swift */; }; + DA0A02060000000000000000 /* DeviceAttributesEdgeExtensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01060000000000000000 /* DeviceAttributesEdgeExtensionTests.swift */; }; + DA0A02070000000000000000 /* DeviceAttributesEdgeStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01070000000000000000 /* DeviceAttributesEdgeStateTests.swift */; }; + DA0A02080000000000000000 /* DeviceAttributesHitProcessorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01080000000000000000 /* DeviceAttributesHitProcessorTests.swift */; }; + DA0A02090000000000000000 /* DeviceAttributesRequestBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0A01090000000000000000 /* DeviceAttributesRequestBuilderTests.swift */; }; 1CCD27DC245A240F00E912B2 /* ExperienceEventTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CCD27C82458CB8000E912B2 /* ExperienceEventTests.swift */; }; 211BCB8126030DCD00AACFEF /* EdgeDataEntity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 211BCB8026030DCD00AACFEF /* EdgeDataEntity.swift */; }; 216989652554B39900B2752C /* EdgeHit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 216989642554B39900B2752C /* EdgeHit.swift */; }; @@ -221,6 +231,16 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + DA0A01000000000000000000 /* DeviceAttributesConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesConstants.swift; sourceTree = ""; }; + DA0A01010000000000000000 /* Event+DeviceAttributes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Event+DeviceAttributes.swift"; sourceTree = ""; }; + DA0A01020000000000000000 /* DeviceAttributesRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesRequestBuilder.swift; sourceTree = ""; }; + DA0A01030000000000000000 /* DeviceAttributesNetworkService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesNetworkService.swift; sourceTree = ""; }; + DA0A010A0000000000000000 /* DeviceAttributesNetworkResult.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesNetworkResult.swift; sourceTree = ""; }; + DA0A01050000000000000000 /* DeviceAttributesHitProcessor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesHitProcessor.swift; sourceTree = ""; }; + DA0A01060000000000000000 /* DeviceAttributesEdgeExtensionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesEdgeExtensionTests.swift; sourceTree = ""; }; + DA0A01070000000000000000 /* DeviceAttributesEdgeStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesEdgeStateTests.swift; sourceTree = ""; }; + DA0A01080000000000000000 /* DeviceAttributesHitProcessorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesHitProcessorTests.swift; sourceTree = ""; }; + DA0A01090000000000000000 /* DeviceAttributesRequestBuilderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAttributesRequestBuilderTests.swift; sourceTree = ""; }; 04A228C42686D67347C85BEA /* Pods-TestAppiOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-TestAppiOS.release.xcconfig"; path = "Target Support Files/Pods-TestAppiOS/Pods-TestAppiOS.release.xcconfig"; sourceTree = ""; }; 0B13510405D14B13EFD1B58A /* Pods_FunctionalTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_FunctionalTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 1CCD27C52458CB2300E912B2 /* ExperienceEvent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExperienceEvent.swift; sourceTree = ""; }; @@ -429,6 +449,19 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + DA0A03000000000000000000 /* DeviceAttributes */ = { + isa = PBXGroup; + children = ( + DA0A01000000000000000000 /* DeviceAttributesConstants.swift */, + DA0A01010000000000000000 /* Event+DeviceAttributes.swift */, + DA0A01020000000000000000 /* DeviceAttributesRequestBuilder.swift */, + DA0A01030000000000000000 /* DeviceAttributesNetworkService.swift */, + DA0A010A0000000000000000 /* DeviceAttributesNetworkResult.swift */, + DA0A01050000000000000000 /* DeviceAttributesHitProcessor.swift */, + ); + path = DeviceAttributes; + sourceTree = ""; + }; 1CCD27CD24592B2800E912B2 /* xdm */ = { isa = PBXGroup; children = ( @@ -586,6 +619,7 @@ children = ( 1CCD27CD24592B2800E912B2 /* xdm */, D42FB8D52462159300E9321C /* public */, + DA0A03000000000000000000 /* DeviceAttributes */, D42FB8D02461086200E9321C /* EdgeNetworkHandlers */, D43BAB0225BB758300B08CC0 /* EdgeConsentStatus.swift */, BF947F63243565CC0057A6CC /* EdgeConstants.swift */, @@ -620,6 +654,10 @@ D45F2E8125EE1987000AC350 /* EdgePublicAPITests.swift */, BF947F9F244569190057A6CC /* EdgeRequestTests.swift */, BF74551028BC649A00FF3AEC /* EdgeStateTests.swift */, + DA0A01060000000000000000 /* DeviceAttributesEdgeExtensionTests.swift */, + DA0A01070000000000000000 /* DeviceAttributesEdgeStateTests.swift */, + DA0A01080000000000000000 /* DeviceAttributesHitProcessorTests.swift */, + DA0A01090000000000000000 /* DeviceAttributesRequestBuilderTests.swift */, 1CCD27C82458CB8000E912B2 /* ExperienceEventTests.swift */, BF0F92502756A3EF00378913 /* ImplementationDetailsTests.swift */, BF947F73243BA0E10057A6CC /* KonductorConfigTests.swift */, @@ -1298,6 +1336,12 @@ buildActionMask = 2147483647; files = ( D4EC0DBB25E73FF10026EBAA /* EdgeState.swift in Sources */, + DA0A02000000000000000000 /* DeviceAttributesConstants.swift in Sources */, + DA0A02010000000000000000 /* Event+DeviceAttributes.swift in Sources */, + DA0A02020000000000000000 /* DeviceAttributesRequestBuilder.swift in Sources */, + DA0A02030000000000000000 /* DeviceAttributesNetworkService.swift in Sources */, + DA0A020A0000000000000000 /* DeviceAttributesNetworkResult.swift in Sources */, + DA0A02050000000000000000 /* DeviceAttributesHitProcessor.swift in Sources */, BFDF25AD2BDB077E002114B6 /* SharedStateReader.swift in Sources */, BF0F924F27476E6C00378913 /* ImplementationDetails.swift in Sources */, D4C6B437251A76CB0038F4F9 /* XDMProtocols.swift in Sources */, @@ -1362,6 +1406,10 @@ BF0F92522756A57800378913 /* ImplementationDetailsTests.swift in Sources */, BF947F74243BA0E10057A6CC /* KonductorConfigTests.swift in Sources */, BF74551128BC649A00FF3AEC /* EdgeStateTests.swift in Sources */, + DA0A02060000000000000000 /* DeviceAttributesEdgeExtensionTests.swift in Sources */, + DA0A02070000000000000000 /* DeviceAttributesEdgeStateTests.swift in Sources */, + DA0A02080000000000000000 /* DeviceAttributesHitProcessorTests.swift in Sources */, + DA0A02090000000000000000 /* DeviceAttributesRequestBuilderTests.swift in Sources */, D4F74FE92447A92800379258 /* MockURLSession.swift in Sources */, D4145F4025D1D3200019EA4C /* EdgeHitTests.swift in Sources */, 216989B32555376A00B2752C /* EdgeHitProcessorTests.swift in Sources */, @@ -1594,7 +1642,7 @@ "@executable_path/Frameworks", "@loader_path/Frameworks", ); - MARKETING_VERSION = 5.2.0; + MARKETING_VERSION = 5.3.0; OTHER_LDFLAGS = "$(inherited)"; PRODUCT_BUNDLE_IDENTIFIER = com.adobe.aep.edge; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; @@ -1630,7 +1678,7 @@ "@executable_path/Frameworks", "@loader_path/Frameworks", ); - MARKETING_VERSION = 5.2.0; + MARKETING_VERSION = 5.3.0; OTHER_LDFLAGS = "$(inherited)"; PRODUCT_BUNDLE_IDENTIFIER = com.adobe.aep.edge; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; diff --git a/Documentation/event-reference.md b/Documentation/event-reference.md index 5764fa1c..d2d9121d 100644 --- a/Documentation/event-reference.md +++ b/Documentation/event-reference.md @@ -20,6 +20,12 @@ The following events are handled by the Edge extension client-side. +For the isolated `mobile/device-attributes` endpoint, Edge builds the SDK-owned +`xdm.identityMap` from Edge Identity shared state. If it contains multiple ECIDs, +only the first (current) ECID is sent because this endpoint requires exactly one +ECID. The current entry's metadata and other identity namespaces are preserved. +The shared-state identity map and ordinary `interact` requests are unchanged. + ### Edge consent response content This event contains the latest consent preferences synced with the SDK. The Edge Network extension reads the current data collection consent settings stored in the `collect` property and adjusts its internal queueing behavior based on the value as follows: diff --git a/Sources/DeviceAttributes/DeviceAttributesConstants.swift b/Sources/DeviceAttributes/DeviceAttributesConstants.swift new file mode 100644 index 00000000..e80981c2 --- /dev/null +++ b/Sources/DeviceAttributes/DeviceAttributesConstants.swift @@ -0,0 +1,56 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +import Foundation + +// Constants owned by the consent-independent device-attributes path. +// Declared as an extension so the shared `EdgeConstants.swift` is left untouched. + +extension EdgeConstants { + enum DeviceAttributes { + /// Event type of the device attributes request (`requestContent`) and response (`responseContent`) events. + static let EVENT_TYPE = "com.adobe.eventType.edgeDeviceAttributes" + /// Name of the device attributes response event. + static let EVENT_NAME_RESPONSE = "Device Attributes Response" + /// Suffix appended to the Edge extension name to label the dedicated device-attributes queue. + static let DATA_QUEUE_SUFFIX = ".deviceAttributes" + /// HTTP status codes treated as a successful device-attributes request. + static let SUCCESS_RESPONSE_CODES: Set = [200, 202] + + enum EventDataKeys { + static let STATUS = "status" + static let REASON = "reason" + static let HTTP_STATUS = "httpStatus" + static let REQUEST_EVENT_ID = EdgeConstants.EventDataKeys.REQUEST_EVENT_ID + } + + enum Status { + static let SUCCESS = "success" + static let FAILED = "failed" + static let DROPPED = "dropped" + } + + enum Reason { + static let MISSING_CONFIG = "missingConfig" + static let INVALID_PAYLOAD = "invalidPayload" + static let QUEUE_UNAVAILABLE = "queueUnavailable" + static let NETWORK = "network" + static let IDENTITY_CHANGED = "identityChanged" + } + + enum ResponseKeys { + static let TITLE = "title" + static let REPORT = "report" + static let ERRORS = "errors" + } + } +} diff --git a/Sources/DeviceAttributes/DeviceAttributesHitProcessor.swift b/Sources/DeviceAttributes/DeviceAttributesHitProcessor.swift new file mode 100644 index 00000000..8c5573b6 --- /dev/null +++ b/Sources/DeviceAttributes/DeviceAttributesHitProcessor.swift @@ -0,0 +1,196 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +import AEPCore +import AEPServices +import Foundation + +/// Processes hits from the consent-independent device-attributes queue. +/// Fully separate from `EdgeHitProcessor`: it does not use `NetworkResponseHandler` and never dispatches Edge +/// response/error events. The response body is not parsed: the outcome is decided by the status code only, and response +/// handles such as `locationHint:result` and `state:store` are ignored, so the Edge location hint and stored payloads are +/// never updated by this flow. Every device attributes request event yields exactly one device attributes response event. Before each send attempt +/// the ECID queued with the hit is compared with the latest Edge Identity ECID; a hit whose ECID has changed is dropped. +class DeviceAttributesHitProcessor: HitProcessing { + private let SELF_TAG = "DeviceAttributesHitProcessor" + private let networkService: DeviceAttributesNetworkService + private let sharedStateReader: SharedStateReader + private let getImplementationDetails: () -> [String: Any]? + private let getLocationHint: () -> String? + private let getLatestIdentityMap: () -> [String: Any]? + private let dispatch: (Event) -> Void + private let storeDataStoreName: String + private let entityRetryIntervalMapping = ThreadSafeDictionary() + + /// - Parameters: + /// - networkService: sender for the device-attributes request + /// - sharedStateReader: used to read the Assurance integration id + /// - getImplementationDetails: returns the current `implementationDetails` + /// - getLocationHint: returns the current Edge Network location hint + /// - getLatestIdentityMap: returns the latest Edge Identity XDM shared state (containing `identityMap`), or nil if unavailable + /// - dispatch: dispatches the device attributes response event + /// - storeDataStoreName: data store holding the `state:store` payloads sent as `meta.state` + init(networkService: DeviceAttributesNetworkService = DeviceAttributesNetworkService(), + sharedStateReader: SharedStateReader, + getImplementationDetails: @escaping () -> [String: Any]?, + getLocationHint: @escaping () -> String?, + getLatestIdentityMap: @escaping () -> [String: Any]?, + dispatch: @escaping (Event) -> Void, + storeDataStoreName: String = EdgeConstants.DataStoreKeys.STORE_NAME) { + self.networkService = networkService + self.sharedStateReader = sharedStateReader + self.getImplementationDetails = getImplementationDetails + self.getLocationHint = getLocationHint + self.getLatestIdentityMap = getLatestIdentityMap + self.dispatch = dispatch + self.storeDataStoreName = storeDataStoreName + } + + // MARK: HitProcessing + + func retryInterval(for entity: DataEntity) -> TimeInterval { + return entityRetryIntervalMapping[entity.uniqueIdentifier] ?? EdgeConstants.Defaults.RETRY_INTERVAL + } + + func processHit(entity: DataEntity, completion: @escaping (Bool) -> Void) { + guard let data = entity.data, let edgeEntity = try? JSONDecoder().decode(EdgeDataEntity.self, from: data) else { + Log.error(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Dropping undecodable device attributes hit '\(entity.uniqueIdentifier)'.") + dispatch(Event.createDeviceAttributesDroppedResponse(requestEventId: entity.uniqueIdentifier)) + complete(entity: entity, completion: completion) + return + } + + let event = edgeEntity.event + let snapshotIdentity = AnyCodable.toAnyDictionary(dictionary: edgeEntity.identityMap) + + // Checked on every attempt so hits waiting in retry backoff or restored after relaunch are covered. + guard let latestIdentity = getLatestIdentityMap() else { + Log.debug(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - Latest Identity shared state is unavailable, will retry device attributes hit '\(entity.uniqueIdentifier)'.") + entityRetryIntervalMapping[entity.uniqueIdentifier] = nil + completion(false) + return + } + + guard ecid(from: snapshotIdentity) == ecid(from: latestIdentity) else { + Log.debug(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - ECID changed since device attributes hit '\(entity.uniqueIdentifier)' was queued, dropping.") + finish(entity: entity, + event: event, + response: event.createDeviceAttributesResponse(status: EdgeConstants.DeviceAttributes.Status.DROPPED, + reason: EdgeConstants.DeviceAttributes.Reason.IDENTITY_CHANGED), + completion: completion) + return + } + + sendRequest(entity: entity, edgeEntity: edgeEntity, snapshotIdentity: snapshotIdentity, completion: completion) + } + + // MARK: Private + + /// Builds and sends the device-attributes request for a hit that passed the ECID check. + private func sendRequest(entity: DataEntity, + edgeEntity: EdgeDataEntity, + snapshotIdentity: [String: Any]?, + completion: @escaping (Bool) -> Void) { + let event = edgeEntity.event + let edgeConfig = edgeEntity.configuration.asAnyDictionary.compactMapValues { $0 as? String } + guard let datastreamId = edgeConfig[EdgeConstants.SharedState.Configuration.CONFIG_ID], !datastreamId.isEmpty else { + Log.warning(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Missing datastream id, dropping device attributes hit '\(entity.uniqueIdentifier)'.") + finish(entity: entity, + event: event, + response: event.createDeviceAttributesResponse(status: EdgeConstants.DeviceAttributes.Status.DROPPED, + reason: EdgeConstants.DeviceAttributes.Reason.MISSING_CONFIG), + completion: completion) + return + } + + let identityMap = snapshotIdentity?[EdgeConstants.SharedState.Identity.IDENTITY_MAP] as? [String: Any] + let requestBuilder = DeviceAttributesRequestBuilder(dataStoreName: storeDataStoreName) + let endpoint = EdgeEndpoint(requestType: .deviceAttributes, + environmentType: EdgeEnvironmentType(optionalRawValue: edgeConfig[EdgeConstants.SharedState.Configuration.EDGE_ENVIRONMENT]), + optionalDomain: edgeConfig[EdgeConstants.SharedState.Configuration.EDGE_DOMAIN], + optionalPath: nil, + locationHint: getLocationHint()) + guard let body = requestBuilder.buildRequestBody(eventData: event.data, + implementationDetails: getImplementationDetails(), + identityMap: identityMap), + let url = networkService.buildUrl(endpoint: endpoint, datastreamId: datastreamId, requestId: UUID().uuidString) else { + Log.warning(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Unable to build device attributes request, dropping hit '\(entity.uniqueIdentifier)'.") + finish(entity: entity, + event: event, + response: event.createDeviceAttributesResponse(status: EdgeConstants.DeviceAttributes.Status.DROPPED, + reason: EdgeConstants.DeviceAttributes.Reason.INVALID_PAYLOAD), + completion: completion) + return + } + + networkService.send(url: url, body: body, headers: getRequestHeaders(event)) { [weak self] result in + guard let self = self else { + completion(false) + return + } + self.handleNetworkResult(result, entity: entity, event: event, completion: completion) + } + } + + private func handleNetworkResult(_ result: DeviceAttributesNetworkResult, + entity: DataEntity, + event: Event, + completion: @escaping (Bool) -> Void) { + switch result { + case let .success(httpStatus): + finish(entity: entity, + event: event, + response: event.createDeviceAttributesResponse(status: EdgeConstants.DeviceAttributes.Status.SUCCESS, httpStatus: httpStatus), + completion: completion) + case let .retry(interval): + entityRetryIntervalMapping[entity.uniqueIdentifier] = interval + completion(false) + case let .failed(httpStatus): + finish(entity: entity, + event: event, + response: event.createDeviceAttributesResponse(status: EdgeConstants.DeviceAttributes.Status.FAILED, + reason: EdgeConstants.DeviceAttributes.Reason.NETWORK, + httpStatus: httpStatus), + completion: completion) + } + } + + /// Dispatches the device attributes response event and removes the hit from the queue. + private func finish(entity: DataEntity, event: Event, response: Event, completion: @escaping (Bool) -> Void) { + dispatch(response) + complete(entity: entity, completion: completion) + } + + private func complete(entity: DataEntity, completion: @escaping (Bool) -> Void) { + entityRetryIntervalMapping[entity.uniqueIdentifier] = nil + completion(true) + } + + /// Returns `identityMap.ECID[0].id` from an Edge Identity XDM shared state. Index 0 is Edge Identity's current ECID; + /// a legacy ECID, if any, follows it and is not compared. + private func ecid(from identityState: [String: Any]?) -> String? { + let identityMap = identityState?[EdgeConstants.SharedState.Identity.IDENTITY_MAP] as? [String: Any] + let ecids = identityMap?[EdgeConstants.JsonKeys.ECID] as? [[String: Any]] + return ecids?.first?["id"] as? String + } + + /// Adds the Assurance integration id header when Assurance is enabled. + private func getRequestHeaders(_ event: Event) -> [String: String] { + var requestHeaders: [String: String] = [:] + if let assuranceIntegrationId = sharedStateReader.getAssuranceIntegrationId(event: event) { + requestHeaders[EdgeConstants.NetworkKeys.HEADER_KEY_AEP_VALIDATION_TOKEN] = assuranceIntegrationId + } + return requestHeaders + } +} diff --git a/Sources/DeviceAttributes/DeviceAttributesNetworkResult.swift b/Sources/DeviceAttributes/DeviceAttributesNetworkResult.swift new file mode 100644 index 00000000..a33b9fcd --- /dev/null +++ b/Sources/DeviceAttributes/DeviceAttributesNetworkResult.swift @@ -0,0 +1,23 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +import Foundation + +/// Outcome of a device-attributes network request. +enum DeviceAttributesNetworkResult: Equatable { + /// The request was accepted (HTTP 200 or 202). The response body is not used. + case success(httpStatus: Int) + /// The request failed with a recoverable error and should be retried after `interval` seconds. + case retry(interval: TimeInterval) + /// The request failed with an unrecoverable error; `httpStatus` is nil when no response code was received. + case failed(httpStatus: Int?) +} diff --git a/Sources/DeviceAttributes/DeviceAttributesNetworkService.swift b/Sources/DeviceAttributes/DeviceAttributesNetworkService.swift new file mode 100644 index 00000000..10a9f2ee --- /dev/null +++ b/Sources/DeviceAttributes/DeviceAttributesNetworkService.swift @@ -0,0 +1,121 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +import AEPServices +import Foundation + +/// Network sender for the `mobile/device-attributes` endpoint. Independent of `EdgeNetworkService`: +/// the outcome is decided by the status code only (the body is read only to log problem details) and has no interact error/207 semantics. +class DeviceAttributesNetworkService { + private let SELF_TAG = "DeviceAttributesNetworkService" + + /// Same recoverable set as `EdgeNetworkService`, so retry behavior matches the interact path. + private let recoverableResponseCodes = Set(NetworkServiceConstants.RECOVERABLE_ERROR_CODES + + [HttpResponseCodes.tooManyRequests.rawValue, + HttpResponseCodes.badGateway.rawValue, + HttpResponseCodes.insufficientStorage.rawValue]) + + private let defaultHeaders = [EdgeConstants.NetworkKeys.HEADER_KEY_ACCEPT: EdgeConstants.NetworkKeys.HEADER_VALUE_APPLICATION_JSON, + EdgeConstants.NetworkKeys.HEADER_KEY_CONTENT_TYPE: EdgeConstants.NetworkKeys.HEADER_VALUE_APPLICATION_JSON] + + /// Builds the device-attributes URL: `?configId=&requestId=`. + /// Returns nil when the endpoint has no valid host (e.g. an invalid `edge.domain`); before iOS 17 `URLComponents` drops an invalid host instead of returning nil. + func buildUrl(endpoint: EdgeEndpoint, datastreamId: String, requestId: String) -> URL? { + guard let url = endpoint.url, url.host?.isEmpty == false, + var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } + urlComponents.queryItems = [ + URLQueryItem(name: EdgeConstants.NetworkKeys.REQUEST_PARAM_CONFIG_ID, value: datastreamId), + URLQueryItem(name: EdgeConstants.NetworkKeys.REQUEST_PARAM_REQUEST_ID, value: requestId) + ] + return urlComponents.url + } + + /// Sends the device-attributes request and reports the classified outcome. + /// - Parameters: + /// - url: request URL + /// - body: JSON request body + /// - headers: additional request headers, merged over the default JSON headers + /// - completion: invoked with the classified `DeviceAttributesNetworkResult` + func send(url: URL, body: String, headers: [String: String], completion: @escaping (DeviceAttributesNetworkResult) -> Void) { + let requestHeaders = defaultHeaders.merging(headers) { _, new in new } + let networkRequest = NetworkRequest(url: url, + httpMethod: .post, + connectPayload: body, + httpHeaders: requestHeaders, + connectTimeout: EdgeConstants.NetworkKeys.DEFAULT_CONNECT_TIMEOUT, + readTimeout: EdgeConstants.NetworkKeys.DEFAULT_READ_TIMEOUT) + Log.debug(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Sending device attributes request to URL \(url.absoluteString) with body: \(body)") + + ServiceProvider.shared.networkService.connectAsync(networkRequest: networkRequest) { connection in + completion(self.classify(connection: connection, url: url)) + } + } + + /// Classifies the `connection` into success, retry or failure. + func classify(connection: HttpConnection, url: URL) -> DeviceAttributesNetworkResult { + if let error = connection.error { + if let urlError = error as? URLError, urlError.isRecoverable { + let retryInterval = EdgeConstants.Defaults.RETRY_INTERVAL + Log.debug(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - Device attributes request with url \(url.absoluteString) failed with recoverable URL error " + + "(\(urlError.errorCode)). Will retry in \(retryInterval) seconds.") + return .retry(interval: retryInterval) + } + Log.warning(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - Device attributes request with url \(url.absoluteString) failed with unrecoverable error " + + "(\(error.localizedDescription)).") + return .failed(httpStatus: connection.responseCode) + } + + guard let responseCode = connection.responseCode else { + Log.warning(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Device attributes request with url \(url.absoluteString) failed with unknown error.") + return .failed(httpStatus: nil) + } + + if EdgeConstants.DeviceAttributes.SUCCESS_RESPONSE_CODES.contains(responseCode) { + Log.debug(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Device attributes request was successful (\(responseCode)).") + return .success(httpStatus: responseCode) + } + + if recoverableResponseCodes.contains(responseCode) { + var retryInterval = EdgeConstants.Defaults.RETRY_INTERVAL + // Only integer Retry-After values are supported, matching the interact path. + if let retryHeader = connection.responseHttpHeader(forKey: EdgeConstants.NetworkKeys.HEADER_KEY_RETRY_AFTER), + let retryAfter = TimeInterval(retryHeader), retryAfter > 0 { + retryInterval = retryAfter + } + Log.debug(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - Device attributes request returned recoverable code \(responseCode). Will retry in \(retryInterval) seconds.") + return .retry(interval: retryInterval) + } + + logUnrecoverableResponse(responseCode: responseCode, body: connection.responseString) + return .failed(httpStatus: responseCode) + } + + /// Logs an unrecoverable response, including the problem-JSON `title` and `report.errors` when present (e.g. HTTP 400). + private func logUnrecoverableResponse(responseCode: Int, body: String?) { + typealias Keys = EdgeConstants.DeviceAttributes.ResponseKeys + var details = "" + if let body = body, + let json = try? JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any] { + if let title = json[Keys.TITLE] as? String { + details += " title: \(title)" + } + if let errors = (json[Keys.REPORT] as? [String: Any])?[Keys.ERRORS] { + details += " errors: \(errors)" + } + } + Log.warning(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - Device attributes request returned unrecoverable code \(responseCode).\(details)") + } +} diff --git a/Sources/DeviceAttributes/DeviceAttributesRequestBuilder.swift b/Sources/DeviceAttributes/DeviceAttributesRequestBuilder.swift new file mode 100644 index 00000000..8c3d8ecf --- /dev/null +++ b/Sources/DeviceAttributes/DeviceAttributesRequestBuilder.swift @@ -0,0 +1,87 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +import AEPCore +import AEPServices +import Foundation + +/// Builds the flat request body for the `mobile/device-attributes` endpoint. +/// Request event data (e.g. `app`, `tokens`, `timezone`) is passed through as-is; the SDK owns `xdm` and `meta`. +class DeviceAttributesRequestBuilder { + private let SELF_TAG = "DeviceAttributesRequestBuilder" + + /// Read-only access to stored `state:store` payloads used for `meta.state`. + private let storeResponsePayloadManager: StoreResponsePayloadManager + + init(dataStoreName: String = EdgeConstants.DataStoreKeys.STORE_NAME) { + storeResponsePayloadManager = StoreResponsePayloadManager(dataStoreName) + } + + /// Builds the device-attributes request body. `xdm` and `meta` in the event data are ignored. + /// The SDK adds `xdm` (implementationDetails + identityMap) and `meta.state` when available. + /// - Parameters: + /// - eventData: the device attributes request event data forming the base of the request body + /// - implementationDetails: the SDK `implementationDetails` to attach under `xdm` + /// - identityMap: the identity map to attach under `xdm`, retaining only the current ECID + /// - Returns: the request body, or nil if there is nothing to send + func buildPayload(eventData: [String: Any]?, + implementationDetails: [String: Any]?, + identityMap: [String: Any]?) -> [String: AnyCodable]? { + guard let data = eventData, !data.isEmpty else { return nil } + + let producerData = data.filter { $0.key != EdgeConstants.JsonKeys.XDM && $0.key != EdgeConstants.JsonKeys.META } + if producerData.count != data.count { + Log.warning(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Ignoring producer-supplied SDK-owned xdm/meta fields for device attributes.") + } + var payload: [String: AnyCodable] = AnyCodable.from(dictionary: producerData) ?? [:] + + var xdm = [String: Any]() + if let implementationDetails = implementationDetails { + xdm[EdgeConstants.JsonKeys.IMPLEMENTATION_DETAILS] = implementationDetails + } + if let identityMap = identityMap { + var requestIdentityMap = identityMap + if let ecids = identityMap["ECID"] as? [[String: Any]], ecids.count > 1 { + // Edge Identity's current ECID is first; this endpoint does not accept additional legacy ECIDs. + requestIdentityMap["ECID"] = [ecids[0]] + } + xdm[EdgeConstants.SharedState.Identity.IDENTITY_MAP] = requestIdentityMap + } + if !xdm.isEmpty { + payload[EdgeConstants.JsonKeys.XDM] = AnyCodable(xdm) + } + + // meta.state uses the same StateMetadata shape sent to the interact endpoint (entries include maxAge). + let storedPayloads = storeResponsePayloadManager.getActivePayloadList() + if !storedPayloads.isEmpty, + let stateData = try? JSONEncoder().encode(StateMetadata(payload: storedPayloads)), + let stateDict = try? JSONSerialization.jsonObject(with: stateData) as? [String: Any] { + payload[EdgeConstants.JsonKeys.META] = AnyCodable(["state": stateDict]) + } + + return payload.isEmpty ? nil : payload + } + + /// Builds the device-attributes request body and encodes it as compact JSON. + /// - Returns: the JSON request body, or nil if there is nothing to send or encoding fails + func buildRequestBody(eventData: [String: Any]?, + implementationDetails: [String: Any]?, + identityMap: [String: Any]?) -> String? { + guard let payload = buildPayload(eventData: eventData, + implementationDetails: implementationDetails, + identityMap: identityMap), + let data = try? JSONEncoder().encode(payload) else { + return nil + } + return String(data: data, encoding: .utf8) + } +} diff --git a/Sources/DeviceAttributes/Event+DeviceAttributes.swift b/Sources/DeviceAttributes/Event+DeviceAttributes.swift new file mode 100644 index 00000000..8bbcd949 --- /dev/null +++ b/Sources/DeviceAttributes/Event+DeviceAttributes.swift @@ -0,0 +1,47 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +import AEPCore +import Foundation + +extension Event { + /// Returns true if this `Event` has the dedicated device-attributes event type (`EdgeConstants.DeviceAttributes.EVENT_TYPE`) and the standard + /// `EventSource.requestContent` source. Such events are routed to the separate device-attributes queue + /// and are sent regardless of collect consent. + var isDeviceAttributesRequestEvent: Bool { + return type == EdgeConstants.DeviceAttributes.EVENT_TYPE && source == EventSource.requestContent + } + + /// Creates the device attributes response event for this request event, linked to it via `parentID`. + func createDeviceAttributesResponse(status: String, reason: String? = nil, httpStatus: Int? = nil) -> Event { + typealias Keys = EdgeConstants.DeviceAttributes.EventDataKeys + var data: [String: Any] = [Keys.STATUS: status] + if let reason = reason { data[Keys.REASON] = reason } + if let httpStatus = httpStatus { data[Keys.HTTP_STATUS] = httpStatus } + return createChainedEvent(name: EdgeConstants.DeviceAttributes.EVENT_NAME_RESPONSE, + type: EdgeConstants.DeviceAttributes.EVENT_TYPE, + source: EventSource.responseContent, + data: data) + } + + /// Creates the `dropped` device attributes response event for a hit that can't be decoded. With no request event to + /// link to, it carries the request event id in `requestEventId`. + static func createDeviceAttributesDroppedResponse(requestEventId: String) -> Event { + typealias Keys = EdgeConstants.DeviceAttributes.EventDataKeys + return Event(name: EdgeConstants.DeviceAttributes.EVENT_NAME_RESPONSE, + type: EdgeConstants.DeviceAttributes.EVENT_TYPE, + source: EventSource.responseContent, + data: [Keys.STATUS: EdgeConstants.DeviceAttributes.Status.DROPPED, + Keys.REASON: EdgeConstants.DeviceAttributes.Reason.INVALID_PAYLOAD, + Keys.REQUEST_EVENT_ID: requestEventId]) + } +} diff --git a/Sources/Edge.swift b/Sources/Edge.swift index 042dde04..c0280733 100644 --- a/Sources/Edge.swift +++ b/Sources/Edge.swift @@ -38,7 +38,9 @@ public class Edge: NSObject, Extension { // set default on init for register/unregister use-case networkResponseHandler = NetworkResponseHandler(updateLocationHint: setLocationHint) if let hitQueue = setupHitQueue() { - state = EdgeState(hitQueue: hitQueue, edgeProperties: EdgeProperties()) + state = EdgeState(hitQueue: hitQueue, + deviceAttributesHitQueue: setupDeviceAttributesHitQueue(dataQueueService: ServiceProvider.shared.dataQueueService), + edgeProperties: EdgeProperties()) } } @@ -61,17 +63,21 @@ public class Edge: NSObject, Extension { registerListener(type: EventType.genericIdentity, source: EventSource.requestReset, listener: handleIdentitiesReset) + registerListener(type: EdgeConstants.DeviceAttributes.EVENT_TYPE, + source: EventSource.requestContent, + listener: handleDeviceAttributesRequest) } public func onUnregistered() { state?.hitQueue.close() + state?.deviceAttributesHitQueue?.close() print("Extension unregistered from MobileCore: \(EdgeConstants.FRIENDLY_NAME)") } public func readyForEvent(_ event: Event) -> Bool { guard canProcessEvents(event: event) else { return false } - if event.isExperienceEvent || event.isUpdateConsentEvent { + if event.isExperienceEvent || event.isUpdateConsentEvent || event.isDeviceAttributesRequestEvent { let configurationSharedState = getSharedState(extensionName: EdgeConstants.SharedState.Configuration.STATE_OWNER_NAME, event: event) let identitySharedState = getXDMSharedState(extensionName: EdgeConstants.SharedState.Identity.STATE_OWNER_NAME, @@ -254,6 +260,92 @@ public class Edge: NSObject, Extension { return EdgeBatchingHitQueue(dataQueue: dataQueue, processor: hitProcessor) } + // MARK: - Device attributes (consent-independent) + + /// Handles device attributes request events. They are queued on the dedicated device attributes queue, which is not + /// subject to collect consent, and always result in exactly one device attributes response event. + /// - Parameter event: the device attributes request event + func handleDeviceAttributesRequest(_ event: Event) { + guard let deviceAttributesHitQueue = state?.deviceAttributesHitQueue else { + Log.error(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Device attributes queue is unavailable, dropping event \(event.id.uuidString).") + dispatchDeviceAttributesResponse(for: event, status: EdgeConstants.DeviceAttributes.Status.FAILED, reason: EdgeConstants.DeviceAttributes.Reason.QUEUE_UNAVAILABLE) + return + } + + guard let data = event.data, !data.isEmpty else { + Log.warning(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Device attributes event \(event.id.uuidString) contains no data, dropping.") + dispatchDeviceAttributesResponse(for: event, status: EdgeConstants.DeviceAttributes.Status.DROPPED, reason: EdgeConstants.DeviceAttributes.Reason.INVALID_PAYLOAD) + return + } + + // get Configuration shared state, this should be resolved based on readyForEvent check + let edgeConfig = sharedStateReader.getEdgeConfig(event: event) + guard let configId = edgeConfig[EdgeConstants.SharedState.Configuration.CONFIG_ID], !configId.isEmpty else { + Log.warning(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - Unable to process device attributes event '\(event.id.uuidString)', configuration 'edge.configId' is missing or empty.") + dispatchDeviceAttributesResponse(for: event, status: EdgeConstants.DeviceAttributes.Status.DROPPED, reason: EdgeConstants.DeviceAttributes.Reason.MISSING_CONFIG) + return + } + + // get IdentityMap from Identity shared state, this should be resolved based on readyForEvent check + guard let identityState = getXDMSharedState(extensionName: EdgeConstants.SharedState.Identity.STATE_OWNER_NAME, + event: event)?.value else { + Log.warning(label: EdgeConstants.LOG_TAG, + "\(SELF_TAG) - Unable to process device attributes event '\(event.id.uuidString)', Identity shared state is nil.") + dispatchDeviceAttributesResponse(for: event, status: EdgeConstants.DeviceAttributes.Status.DROPPED, reason: EdgeConstants.DeviceAttributes.Reason.INVALID_PAYLOAD) + return + } + + let edgeEntity = EdgeDataEntity(event: event, + configuration: AnyCodable.from(dictionary: edgeConfig) ?? [:], + identityMap: AnyCodable.from(dictionary: identityState) ?? [:]) + guard let entityData = try? JSONEncoder().encode(edgeEntity) else { + Log.warning(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Failed to encode device attributes event '\(event.id.uuidString)', dropping.") + dispatchDeviceAttributesResponse(for: event, status: EdgeConstants.DeviceAttributes.Status.DROPPED, reason: EdgeConstants.DeviceAttributes.Reason.INVALID_PAYLOAD) + return + } + + let entity = DataEntity(uniqueIdentifier: event.id.uuidString, timestamp: event.timestamp, data: entityData) + guard deviceAttributesHitQueue.queue(entity: entity) else { + Log.error(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Failed to persist device attributes event \(event.id.uuidString).") + dispatchDeviceAttributesResponse(for: event, status: EdgeConstants.DeviceAttributes.Status.FAILED, reason: EdgeConstants.DeviceAttributes.Reason.QUEUE_UNAVAILABLE) + return + } + Log.debug(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Queued device attributes event \(event.id.uuidString).") + } + + private func dispatchDeviceAttributesResponse(for event: Event, status: String, reason: String) { + dispatch(event: event.createDeviceAttributesResponse(status: status, reason: reason)) + } + + /// Sets up the `PersistentHitQueue` for device attributes hits. It is independent of the primary queue and of collect consent. + func setupDeviceAttributesHitQueue(dataQueueService: DataQueuing) -> HitQueuing? { + guard let dataQueue = dataQueueService.getDataQueue(label: name + EdgeConstants.DeviceAttributes.DATA_QUEUE_SUFFIX, + config: DataQueueConfig(journalMode: .wal)) else { + Log.error(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Failed to create the device attributes DataQueue.") + return nil + } + + let hitProcessor = DeviceAttributesHitProcessor(sharedStateReader: sharedStateReader, + getImplementationDetails: getImplementationDetails, + getLocationHint: getLocationHint, + getLatestIdentityMap: getLatestIdentityMap, + dispatch: { [weak self] event in self?.dispatch(event: event) }) + return PersistentHitQueue(dataQueue: dataQueue, processor: hitProcessor) + } + + /// Returns the latest set Edge Identity XDM shared state, independent of any event, or nil if it is not available. + private func getLatestIdentityMap() -> [String: Any]? { + guard let identityState = getXDMSharedState(extensionName: EdgeConstants.SharedState.Identity.STATE_OWNER_NAME, + event: nil, + barrier: false, + resolution: .any), + identityState.status == .set else { + return nil + } + return identityState.value + } + /// Retrieves the `ConsentStatus` from the Consent XDM Shared state for current `event`. /// - Returns: `ConsentStatus` value from shared state or, if not found, current consent value private func getConsentForEvent(_ event: Event) -> ConsentStatus? { diff --git a/Sources/EdgeConstants.swift b/Sources/EdgeConstants.swift index 6d4b6d82..6e39a843 100644 --- a/Sources/EdgeConstants.swift +++ b/Sources/EdgeConstants.swift @@ -15,7 +15,7 @@ import Foundation enum EdgeConstants { static let EXTENSION_NAME = "com.adobe.edge" - static let EXTENSION_VERSION = "5.2.0" + static let EXTENSION_VERSION = "5.3.0" static let FRIENDLY_NAME = "AEPEdge" static let LOG_TAG = FRIENDLY_NAME diff --git a/Sources/EdgeNetworkHandlers/EdgeNetworkService.swift b/Sources/EdgeNetworkHandlers/EdgeNetworkService.swift index 536cca14..12da0ca7 100644 --- a/Sources/EdgeNetworkHandlers/EdgeNetworkService.swift +++ b/Sources/EdgeNetworkHandlers/EdgeNetworkService.swift @@ -17,9 +17,11 @@ import Foundation /// Edge Network request type: /// - interact - makes request and expects a response /// - consent - sets user consent and expects a response +/// - deviceAttributes - registers device attributes, independent of collect consent (see `DeviceAttributesHitProcessor`) enum EdgeRequestType: String { case interact case consent = "privacy/set-consent" + case deviceAttributes = "mobile/device-attributes" } /// Convenience enum for the known error codes diff --git a/Sources/EdgeState.swift b/Sources/EdgeState.swift index a6c216b8..d3a79e86 100644 --- a/Sources/EdgeState.swift +++ b/Sources/EdgeState.swift @@ -21,6 +21,8 @@ class EdgeState { private var _implementationDetails: [String: Any]? private var _consentStatus: ConsentStatus private(set) var hitQueue: HitQueuing + /// Device attributes queue. Never receives collect consent changes; started once bootup completes. + private(set) var deviceAttributesHitQueue: HitQueuing? private(set) var hasBooted = false var currentCollectConsent: ConsentStatus { @@ -38,10 +40,11 @@ class EdgeState { #endif /// Creates a new `EdgeState` and initializes the required properties and sets the initial collect consent - init(hitQueue: HitQueuing, edgeProperties: EdgeProperties) { + init(hitQueue: HitQueuing, deviceAttributesHitQueue: HitQueuing? = nil, edgeProperties: EdgeProperties) { self.edgeProperties = edgeProperties self.queue = DispatchQueue(label: "com.adobe.edgestate.queue") self.hitQueue = hitQueue + self.deviceAttributesHitQueue = deviceAttributesHitQueue self._consentStatus = EdgeConstants.Defaults.COLLECT_CONSENT_PENDING hitQueue.handleCollectConsentChange(status: currentCollectConsent) } @@ -86,6 +89,8 @@ class EdgeState { createSharedState(edgeProperties.toEventData(), nil) hasBooted = true + // Started after persisted properties and implementationDetails are loaded, so restored hits use them. + deviceAttributesHitQueue?.beginProcessing() Log.debug(label: EdgeConstants.LOG_TAG, "\(SELF_TAG) - Edge has successfully booted up") } diff --git a/Tests/UnitTests/DeviceAttributesEdgeExtensionTests.swift b/Tests/UnitTests/DeviceAttributesEdgeExtensionTests.swift new file mode 100644 index 00000000..81fdef18 --- /dev/null +++ b/Tests/UnitTests/DeviceAttributesEdgeExtensionTests.swift @@ -0,0 +1,508 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +@testable import AEPCore +@testable import AEPEdge +@testable import AEPServices +import AEPTestUtils +import XCTest + +class DeviceAttributesEdgeExtensionTests: XCTestCase, AnyCodableAsserts { + private let experienceEvent = Event(name: "Experience event", type: EventType.edge, source: EventSource.requestContent, data: ["xdm": ["data": "example"]]) + private var mockRuntime: TestableExtensionRuntime! + private var edge: Edge! + private var mockDataQueue: MockDataQueue! + private var mockDeviceAttributesDataQueue: MockDataQueue! + + override func setUp() { + ServiceProvider.shared.namedKeyValueService = MockDataStore() + mockRuntime = TestableExtensionRuntime() + mockDataQueue = MockDataQueue() + mockDeviceAttributesDataQueue = MockDataQueue() + + edge = Edge(runtime: mockRuntime) + edge.state = EdgeState(hitQueue: PersistentHitQueue(dataQueue: mockDataQueue, processor: MockHitProcessor()), + deviceAttributesHitQueue: PersistentHitQueue(dataQueue: mockDeviceAttributesDataQueue, processor: MockHitProcessor()), + edgeProperties: EdgeProperties()) + edge.onRegistered() + } + + override func tearDown() { + mockRuntime.resetDispatchedEventAndCreatedSharedStates() + } + + // MARK: Helpers + + private final class DeviceAttributesDataQueueService: NSObject, DataQueuing { + let deviceAttributesQueue: DataQueue? + private(set) var requestedLabels: [String] = [] + + init(deviceAttributesQueue: DataQueue?) { + self.deviceAttributesQueue = deviceAttributesQueue + } + + func getDataQueue(label: String) -> DataQueue? { + requestedLabels.append(label) + return label == "com.adobe.edge.deviceAttributes" ? deviceAttributesQueue : nil + } + + func getDataQueue(label: String, config: DataQueueConfig) -> DataQueue? { + return getDataQueue(label: label) + } + } + + private final class RejectingHitQueue: HitQueuing { + let processor: HitProcessing = MockHitProcessor() + private(set) var enqueueAttempts = 0 + func queue(entity: DataEntity) -> Bool { + enqueueAttempts += 1 + return false + } + func beginProcessing() {} + func suspend() {} + func clear() {} + func count() -> Int { return 0 } + func close() {} + } + + private final class RecordingHitQueue: HitQueuing { + let processor: HitProcessing = MockHitProcessor() + private(set) var entities: [DataEntity] = [] + private(set) var beginProcessingCount = 0 + private(set) var clearCount = 0 + func queue(entity: DataEntity) -> Bool { + entities.append(entity) + return true + } + func beginProcessing() { beginProcessingCount += 1 } + func suspend() {} + func clear() { + clearCount += 1 + entities.removeAll() + } + func count() -> Int { return entities.count } + func close() {} + } + + /// Records requests and replies synchronously with `response`. + private final class RecordingNetworking: Networking { + let response: HttpConnection + private(set) var requests: [NetworkRequest] = [] + init(response: HttpConnection) { + self.response = response + } + func connectAsync(networkRequest: NetworkRequest, completionHandler: ((HttpConnection) -> Void)?) { + requests.append(networkRequest) + completionHandler?(response) + } + } + + private func makeRequest(data: [String: Any]? = ["timezone": "Europe/London"]) -> Event { + return Event(name: "device attributes", + type: EdgeConstants.DeviceAttributes.EVENT_TYPE, + source: EventSource.requestContent, + data: data) + } + + private func simulateConfigAndIdentity(identity: [String: Any] = [:]) { + mockRuntime.simulateSharedState(for: EdgeConstants.SharedState.Configuration.STATE_OWNER_NAME, + data: ([EdgeConstants.SharedState.Configuration.CONFIG_ID: "config"], .set)) + mockRuntime.simulateXDMSharedState(for: EdgeConstants.SharedState.Identity.STATE_OWNER_NAME, data: (identity, .set)) + } + + private func deviceAttributesResponses() -> [Event] { + return mockRuntime.dispatchedEvents.filter { + $0.type == EdgeConstants.DeviceAttributes.EVENT_TYPE && $0.source == EventSource.responseContent + } + } + + private func assertDeviceAttributesResponse(for request: Event, status: String, reason: String, + file: StaticString = #filePath, line: UInt = #line) throws { + let results = deviceAttributesResponses() + XCTAssertEqual(1, results.count, file: file, line: line) + let result = try XCTUnwrap(results.first, file: file, line: line) + XCTAssertEqual(request.id, result.parentID, file: file, line: line) + XCTAssertNil(result.responseID, file: file, line: line) + XCTAssertEqual(status, result.data?["status"] as? String, file: file, line: line) + XCTAssertEqual(reason, result.data?["reason"] as? String, file: file, line: line) + XCTAssertEqual(0, mockDeviceAttributesDataQueue.count(), file: file, line: line) + XCTAssertEqual(0, mockDataQueue.count(), file: file, line: line) + } + + // MARK: Event classification and wiring + + func testIsDeviceAttributesRequestEvent_trueOnlyForDeviceAttributesTypeAndRequestContentSource() { + XCTAssertTrue(makeRequest().isDeviceAttributesRequestEvent) + + let wrongSource = Event(name: "wrong source", type: EdgeConstants.DeviceAttributes.EVENT_TYPE, source: EventSource.responseContent, data: nil) + XCTAssertFalse(wrongSource.isDeviceAttributesRequestEvent) + + XCTAssertFalse(experienceEvent.isDeviceAttributesRequestEvent) + XCTAssertTrue(experienceEvent.isExperienceEvent) + } + + func testOnRegistered_registersDeviceAttributesListener() { + XCTAssertNotNil(mockRuntime.getListener(type: EdgeConstants.DeviceAttributes.EVENT_TYPE, source: EventSource.requestContent)) + } + + func testSetupDeviceAttributesHitQueue_usesDedicatedLabelAndProcessor() throws { + let service = DeviceAttributesDataQueueService(deviceAttributesQueue: MockDataQueue()) + let deviceAttributesQueue = try XCTUnwrap(edge.setupDeviceAttributesHitQueue(dataQueueService: service) as? PersistentHitQueue) + + XCTAssertEqual(["com.adobe.edge.deviceAttributes"], service.requestedLabels) + XCTAssertTrue(deviceAttributesQueue.processor is DeviceAttributesHitProcessor) + } + + func testInit_createsPrimaryAndDeviceAttributesQueues() throws { + let state = try XCTUnwrap(Edge(runtime: mockRuntime).state) + + XCTAssertTrue(state.hitQueue is EdgeBatchingHitQueue) + let deviceAttributesQueue = try XCTUnwrap(state.deviceAttributesHitQueue as? PersistentHitQueue) + XCTAssertTrue(deviceAttributesQueue.processor is DeviceAttributesHitProcessor) + } + + // MARK: Queueing + + func testHandleDeviceAttributesRequest_queuesOnDeviceAttributesQueueOnly_regardlessOfCollectConsentNo() throws { + simulateConfigAndIdentity(identity: ["identityMap": ["ECID": [["id": "ecid"]]]]) + mockRuntime.simulateXDMSharedState(for: EdgeConstants.SharedState.Consent.SHARED_OWNER_NAME, + data: (["consents": ["collect": ["val": "n"]]], .set)) + edge.state?.updateCurrentConsent(status: ConsentStatus.no) + edge.state?.hitQueue.suspend() + edge.state?.deviceAttributesHitQueue?.suspend() + + let request = makeRequest(data: ["app": ["identifier": "com.example.app"]]) + mockRuntime.simulateComingEvents(request) + + XCTAssertEqual(1, mockDeviceAttributesDataQueue.count()) + XCTAssertEqual(0, mockDataQueue.count()) + XCTAssertTrue(deviceAttributesResponses().isEmpty) + + let entity = try XCTUnwrap(mockDeviceAttributesDataQueue.peek()) + XCTAssertEqual(request.id.uuidString, entity.uniqueIdentifier) + XCTAssertEqual(request.timestamp, entity.timestamp) + let decoded = try JSONDecoder().decode(EdgeDataEntity.self, from: try XCTUnwrap(entity.data)) + XCTAssertEqual(request.id, decoded.event.id) + assertExactMatch(expected: #"{"edge.configId":"config"}"#, actual: decoded.configuration) + assertExactMatch(expected: #"{"identityMap":{"ECID":[{"id":"ecid"}]}}"#, actual: decoded.identityMap) + } + + func testDeviceAttributesRequestUsesDedicatedQueueForEveryCollectConsent() { + let primaryQueue = RecordingHitQueue() + let deviceAttributesQueue = RecordingHitQueue() + edge.state = EdgeState(hitQueue: primaryQueue, deviceAttributesHitQueue: deviceAttributesQueue, edgeProperties: EdgeProperties()) + simulateConfigAndIdentity() + XCTAssertTrue(edge.readyForEvent(experienceEvent)) + + for (index, consent) in [ConsentStatus.no, .pending, .yes].enumerated() { + edge.state?.updateCurrentConsent(status: consent) + let request = makeRequest() + XCTAssertTrue(edge.readyForEvent(request)) + mockRuntime.simulateComingEvents(request) + XCTAssertEqual(index + 1, deviceAttributesQueue.count()) + XCTAssertEqual(request.id.uuidString, deviceAttributesQueue.entities.last?.uniqueIdentifier) + XCTAssertEqual(0, primaryQueue.count()) + } + XCTAssertEqual(0, deviceAttributesQueue.clearCount) + XCTAssertTrue(deviceAttributesResponses().isEmpty) + } + + // MARK: Readiness and bootup + + func testReadyForEvent_deviceAttributesRequiresConfigurationAndIdentity() { + let request = makeRequest() + XCTAssertFalse(edge.readyForEvent(request)) + + mockRuntime.simulateSharedState(for: EdgeConstants.SharedState.Configuration.STATE_OWNER_NAME, + data: ([EdgeConstants.SharedState.Configuration.CONFIG_ID: "config"], .set)) + XCTAssertFalse(edge.readyForEvent(request)) + + mockRuntime.simulateXDMSharedState(for: EdgeConstants.SharedState.Identity.STATE_OWNER_NAME, data: ([:], .set)) + XCTAssertTrue(edge.readyForEvent(request)) + } + + func testReadyForEvent_bootsStateAndStartsDeviceAttributesQueueOnce() { + let deviceAttributesQueue = RecordingHitQueue() + edge.state = EdgeState(hitQueue: RecordingHitQueue(), deviceAttributesHitQueue: deviceAttributesQueue, edgeProperties: EdgeProperties()) + XCTAssertEqual(0, deviceAttributesQueue.beginProcessingCount) + + simulateConfigAndIdentity() + XCTAssertTrue(edge.readyForEvent(makeRequest())) + XCTAssertTrue(edge.readyForEvent(experienceEvent)) + + XCTAssertEqual(true, edge.state?.hasBooted) + XCTAssertEqual(1, deviceAttributesQueue.beginProcessingCount) + } + + func testReadyForEvent_missingState_blocksDeviceAttributesLikeOtherEvents() { + simulateConfigAndIdentity() + edge.state = nil + XCTAssertFalse(edge.readyForEvent(makeRequest())) + XCTAssertFalse(edge.readyForEvent(experienceEvent)) + } + + // MARK: Identity reset + + func testHandleIdentitiesReset_doesNotTouchDeviceAttributesQueue() throws { + let primaryQueue = RecordingHitQueue() + let deviceAttributesQueue = RecordingHitQueue() + edge.state = EdgeState(hitQueue: primaryQueue, deviceAttributesHitQueue: deviceAttributesQueue, edgeProperties: EdgeProperties()) + let deviceAttributesEntity = DataEntity(uniqueIdentifier: UUID().uuidString, timestamp: Date(), data: Data()) + XCTAssertTrue(deviceAttributesQueue.queue(entity: deviceAttributesEntity)) + + let reset = Event(name: "Reset Event", type: EventType.genericIdentity, source: EventSource.requestReset, data: nil) + mockRuntime.simulateComingEvents(reset) + + XCTAssertEqual(0, deviceAttributesQueue.clearCount) + XCTAssertEqual([deviceAttributesEntity.uniqueIdentifier], deviceAttributesQueue.entities.map { $0.uniqueIdentifier }) + XCTAssertEqual(1, primaryQueue.count()) + let resetEntity = try XCTUnwrap(primaryQueue.entities.first) + XCTAssertEqual(reset.id.uuidString, resetEntity.uniqueIdentifier) + XCTAssertTrue(deviceAttributesResponses().isEmpty) + } + + func testDeviceAttributesQueueAcceptsNewIdentityRequestsAfterReset() throws { + edge.state?.hitQueue.suspend() + edge.state?.deviceAttributesHitQueue?.suspend() + simulateConfigAndIdentity(identity: ["identityMap": ["ECID": [["id": "old-ecid"]]]]) + edge.handleDeviceAttributesRequest(makeRequest()) + + let reset = Event(name: "Reset Event", type: EventType.genericIdentity, source: EventSource.requestReset, data: nil) + edge.handleIdentitiesReset(reset) + XCTAssertEqual(1, mockDeviceAttributesDataQueue.count()) + XCTAssertEqual(1, mockDataQueue.count()) + + mockRuntime.simulateXDMSharedState(for: EdgeConstants.SharedState.Identity.STATE_OWNER_NAME, + data: (["identityMap": ["ECID": [["id": "new-ecid"]]]], .set)) + let newRequest = makeRequest(data: ["timezone": "Asia/Kolkata"]) + edge.handleDeviceAttributesRequest(newRequest) + + XCTAssertEqual(2, mockDeviceAttributesDataQueue.count()) + XCTAssertEqual(1, mockDataQueue.count()) + _ = mockDeviceAttributesDataQueue.remove() + let entity = try XCTUnwrap(mockDeviceAttributesDataQueue.peek()) + XCTAssertEqual(newRequest.id.uuidString, entity.uniqueIdentifier) + let decoded = try JSONDecoder().decode(EdgeDataEntity.self, from: try XCTUnwrap(entity.data)) + assertExactMatch(expected: #"{"identityMap":{"ECID":[{"id":"new-ecid"}]}}"#, actual: decoded.identityMap) + } + + // MARK: Failed and dropped responses + + func testDeviceAttributesQueueCreationFailurePreservesOrdinaryQueueing() throws { + let failingService = DeviceAttributesDataQueueService(deviceAttributesQueue: nil) + XCTAssertNil(edge.setupDeviceAttributesHitQueue(dataQueueService: failingService)) + let primaryQueue = RecordingHitQueue() + edge.state = EdgeState(hitQueue: primaryQueue, + deviceAttributesHitQueue: edge.setupDeviceAttributesHitQueue(dataQueueService: failingService), + edgeProperties: EdgeProperties()) + + let request = makeRequest() + simulateConfigAndIdentity() + XCTAssertTrue(edge.readyForEvent(request)) + edge.handleDeviceAttributesRequest(request) + edge.handleExperienceEventRequest(experienceEvent) + + XCTAssertEqual(1, primaryQueue.count()) + try assertDeviceAttributesResponse(for: request, status: "failed", reason: "queueUnavailable") + } + + func testDeviceAttributesMissingQueueProducesCorrelatedFailure() throws { + edge.state = nil + let request = makeRequest() + mockRuntime.simulateComingEvents(request) + try assertDeviceAttributesResponse(for: request, status: "failed", reason: "queueUnavailable") + } + + func testDeviceAttributesFailedEnqueueProducesCorrelatedFailure() throws { + simulateConfigAndIdentity() + let primary = try XCTUnwrap(edge.state?.hitQueue) + let rejectingQueue = RejectingHitQueue() + edge.state = EdgeState(hitQueue: primary, deviceAttributesHitQueue: rejectingQueue, edgeProperties: EdgeProperties()) + let request = makeRequest() + mockRuntime.simulateComingEvents(request) + XCTAssertEqual(1, rejectingQueue.enqueueAttempts) + try assertDeviceAttributesResponse(for: request, status: "failed", reason: "queueUnavailable") + } + + func testOrdinaryFailedEnqueueDoesNotProduceDeviceAttributesResponse() throws { + simulateConfigAndIdentity() + let deviceAttributesQueue = try XCTUnwrap(edge.state?.deviceAttributesHitQueue) + let rejectingQueue = RejectingHitQueue() + edge.state = EdgeState(hitQueue: rejectingQueue, deviceAttributesHitQueue: deviceAttributesQueue, edgeProperties: EdgeProperties()) + mockRuntime.simulateComingEvents(experienceEvent) + XCTAssertEqual(1, rejectingQueue.enqueueAttempts) + XCTAssertTrue(deviceAttributesResponses().isEmpty) + } + + func testDeviceAttributesEmptyPayloadProducesCorrelatedDrop() throws { + simulateConfigAndIdentity() + for data in [nil, [:]] as [[String: Any]?] { + mockRuntime.resetDispatchedEventAndCreatedSharedStates() + let request = makeRequest(data: data) + mockRuntime.simulateComingEvents(request) + try assertDeviceAttributesResponse(for: request, status: "dropped", reason: "invalidPayload") + } + } + + func testDeviceAttributesMissingConfigurationProducesCorrelatedDrop() throws { + mockRuntime.simulateXDMSharedState(for: EdgeConstants.SharedState.Identity.STATE_OWNER_NAME, data: ([:], .set)) + let configurations: [[String: Any]] = [[:], [EdgeConstants.SharedState.Configuration.CONFIG_ID: ""]] + for config in configurations { + mockRuntime.resetDispatchedEventAndCreatedSharedStates() + mockRuntime.simulateSharedState(for: EdgeConstants.SharedState.Configuration.STATE_OWNER_NAME, data: (config, .set)) + let request = makeRequest() + mockRuntime.simulateComingEvents(request) + try assertDeviceAttributesResponse(for: request, status: "dropped", reason: "missingConfig") + } + } + + func testDeviceAttributesMissingIdentityProducesCorrelatedDrop() throws { + mockRuntime.simulateSharedState(for: EdgeConstants.SharedState.Configuration.STATE_OWNER_NAME, + data: ([EdgeConstants.SharedState.Configuration.CONFIG_ID: "config"], .set)) + let request = makeRequest() + mockRuntime.simulateComingEvents(request) + try assertDeviceAttributesResponse(for: request, status: "dropped", reason: "invalidPayload") + } + + func testDeviceAttributesUnencodablePayloadProducesCorrelatedDrop() throws { + simulateConfigAndIdentity() + let request = makeRequest(data: ["invalid": Double.nan]) + mockRuntime.simulateComingEvents(request) + try assertDeviceAttributesResponse(for: request, status: "dropped", reason: "invalidPayload") + } + + // MARK: Decode failure + + func testDecodeFailure_producesUnchainedDropOnlyForDeviceAttributesQueue() throws { + let primaryProcessor = try XCTUnwrap(Edge(runtime: mockRuntime).state?.hitQueue.processor) + let deviceAttributesQueue = try XCTUnwrap(edge.setupDeviceAttributesHitQueue(dataQueueService: DeviceAttributesDataQueueService(deviceAttributesQueue: MockDataQueue()))) + let corruptedData: [Data?] = [nil, Data("{".utf8), Data("{}".utf8)] + var requestIds: [String] = [] + + for data in corruptedData { + let ordinary = DataEntity(uniqueIdentifier: UUID().uuidString, timestamp: Date(), data: data) + primaryProcessor.processHit(entity: ordinary) { finished in XCTAssertTrue(finished) } + let deviceAttributesEntity = DataEntity(uniqueIdentifier: UUID().uuidString, timestamp: Date(), data: data) + requestIds.append(deviceAttributesEntity.uniqueIdentifier) + deviceAttributesQueue.processor.processHit(entity: deviceAttributesEntity) { finished in XCTAssertTrue(finished) } + } + + let results = deviceAttributesResponses() + XCTAssertEqual(corruptedData.count, results.count) + XCTAssertEqual(results.count, mockRuntime.dispatchedEvents.count) + for (result, requestId) in zip(results, requestIds) { + XCTAssertNil(result.parentID) + XCTAssertNil(result.responseID) + XCTAssertEqual(["status": "dropped", "reason": "invalidPayload", "requestEventId": requestId] as NSDictionary, + result.data as NSDictionary?) + } + } + + // MARK: Device attributes response handles + + func testDeviceAttributesHit_responseDoesNotUpdateEdgeLocationHintOrStore() throws { + let identity: [String: Any] = ["identityMap": ["ECID": [["id": "ecid", "authenticatedState": "ambiguous", "primary": false]]]] + simulateConfigAndIdentity(identity: identity) + let state = try XCTUnwrap(edge.state) + state.setLocationHint(hint: "va6", ttlSeconds: 1800, createSharedState: { _, _ in }) + XCTAssertEqual("va6", state.getLocationHint()) + let edgeStore = StoreResponsePayloadManager(EdgeConstants.DataStoreKeys.STORE_NAME) + edgeStore.saveStorePayloads([StoreResponsePayload(payload: StorePayload(key: "kndctr_cookie", value: "edge-value", maxAge: 1800))]) + + let responseBody = #""" + {"requestId": "id", "handle": [ + {"type": "locationHint:result", "payload": [{"scope": "EdgeNetwork", "hint": "or2", "ttlSeconds": 1800}]}, + {"type": "state:store", "payload": [{"key": "kndctr_new", "value": "new-value", "maxAge": 1800}]} + ]} + """# + let url = URL(string: "https://edge.adobedc.net/ee/v1/mobile/device-attributes")! + let networking = RecordingNetworking(response: HttpConnection(data: responseBody.data(using: .utf8), + response: HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil), + error: nil)) + let previousNetworkService = ServiceProvider.shared.networkService + ServiceProvider.shared.networkService = networking + defer { ServiceProvider.shared.networkService = previousNetworkService } + + let queue = try XCTUnwrap(edge.setupDeviceAttributesHitQueue(dataQueueService: DeviceAttributesDataQueueService(deviceAttributesQueue: MockDataQueue()))) + let request = makeRequest() + let edgeEntity = EdgeDataEntity(event: request, + configuration: AnyCodable.from(dictionary: [EdgeConstants.SharedState.Configuration.CONFIG_ID: "config"]) ?? [:], + identityMap: AnyCodable.from(dictionary: identity) ?? [:]) + let entity = DataEntity(uniqueIdentifier: request.id.uuidString, timestamp: Date(), data: try JSONEncoder().encode(edgeEntity)) + let sharedStateCount = mockRuntime.createdSharedStates.count + var finished: Bool? + queue.processor.processHit(entity: entity) { finished = $0 } + XCTAssertEqual(true, finished) + + // The request still uses the current Edge location hint + XCTAssertEqual("/ee/va6/v1/mobile/device-attributes", try XCTUnwrap(networking.requests.first).url.path) + + // The response handles change neither the Edge location hint nor the Edge store + XCTAssertEqual("va6", state.getLocationHint()) + XCTAssertEqual(["kndctr_cookie"], edgeStore.getActivePayloadList().map { $0.key }) + XCTAssertEqual("edge-value", edgeStore.getActivePayloadList().first?.value) + XCTAssertEqual(sharedStateCount, mockRuntime.createdSharedStates.count) + let results = deviceAttributesResponses() + XCTAssertEqual(1, results.count) + XCTAssertEqual(request.id, results.first?.parentID) + XCTAssertEqual(["status": "success", "httpStatus": 200] as NSDictionary, results.first?.data as NSDictionary?) + XCTAssertEqual(results.count, mockRuntime.dispatchedEvents.count) + } + + // MARK: Response event contract + + func testDeviceAttributesResponsesRetainRequestCorrelation() { + typealias Status = EdgeConstants.DeviceAttributes.Status + let request = makeRequest() + let listener = EventListenerContainer(listener: { _ in }, type: EdgeConstants.DeviceAttributes.EVENT_TYPE, + source: EventSource.responseContent, triggerEventId: nil, timeoutTask: nil) + for (status, expectedStatus) in [(Status.SUCCESS, "success"), (Status.FAILED, "failed"), (Status.DROPPED, "dropped")] { + let result = request.createDeviceAttributesResponse(status: status) + XCTAssertTrue(listener.shouldNotify(result)) + XCTAssertEqual("Device Attributes Response", result.name) + XCTAssertEqual("com.adobe.eventType.edgeDeviceAttributes", result.type) + XCTAssertEqual("com.adobe.eventSource.responseContent", result.source) + XCTAssertEqual(request.id, result.parentID) + XCTAssertNil(result.responseID) + XCTAssertEqual(["status": expectedStatus] as NSDictionary, result.data as NSDictionary?) + } + let result = request.createDeviceAttributesResponse(status: Status.FAILED, reason: EdgeConstants.DeviceAttributes.Reason.NETWORK, httpStatus: 404) + XCTAssertEqual(["status": "failed", "reason": "network", "httpStatus": 404] as NSDictionary, result.data as NSDictionary?) + } + + func testDeviceAttributesResponseConstantsPreserveWireValues() { + typealias Keys = EdgeConstants.DeviceAttributes.EventDataKeys + typealias Status = EdgeConstants.DeviceAttributes.Status + typealias Reason = EdgeConstants.DeviceAttributes.Reason + + XCTAssertEqual("com.adobe.eventType.edgeDeviceAttributes", EdgeConstants.DeviceAttributes.EVENT_TYPE) + XCTAssertEqual(["status", "reason", "httpStatus", "requestEventId"], + [Keys.STATUS, Keys.REASON, Keys.HTTP_STATUS, Keys.REQUEST_EVENT_ID]) + XCTAssertEqual(["success", "failed", "dropped"], [Status.SUCCESS, Status.FAILED, Status.DROPPED]) + XCTAssertEqual(["missingConfig", "invalidPayload", "queueUnavailable", "network", "identityChanged"], + [Reason.MISSING_CONFIG, Reason.INVALID_PAYLOAD, Reason.QUEUE_UNAVAILABLE, Reason.NETWORK, Reason.IDENTITY_CHANGED]) + XCTAssertEqual("Device Attributes Response", EdgeConstants.DeviceAttributes.EVENT_NAME_RESPONSE) + } + + func testDeviceAttributesDecodeDropPreservesUnchainedWireContract() { + let requestId = UUID().uuidString + let result = Event.createDeviceAttributesDroppedResponse(requestEventId: requestId) + + XCTAssertEqual("Device Attributes Response", result.name) + XCTAssertEqual("com.adobe.eventType.edgeDeviceAttributes", result.type) + XCTAssertEqual("com.adobe.eventSource.responseContent", result.source) + XCTAssertNil(result.parentID) + XCTAssertNil(result.responseID) + XCTAssertEqual(["status": "dropped", "reason": "invalidPayload", "requestEventId": requestId] as NSDictionary, + result.data as NSDictionary?) + } +} diff --git a/Tests/UnitTests/DeviceAttributesEdgeStateTests.swift b/Tests/UnitTests/DeviceAttributesEdgeStateTests.swift new file mode 100644 index 00000000..5f1e8d6e --- /dev/null +++ b/Tests/UnitTests/DeviceAttributesEdgeStateTests.swift @@ -0,0 +1,124 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +@testable import AEPCore +@testable import AEPEdge +import AEPServices +import AEPTestUtils +import XCTest + +class DeviceAttributesEdgeStateTests: XCTestCase { + private final class RecordingHitQueue: HitQueuing { + enum Operation: Equatable { + case beginProcessing + case suspend + case clear + case close + } + + let processor: HitProcessing = MockHitProcessor() + private(set) var operations: [Operation] = [] + private var entities: [DataEntity] = [] + var onBeginProcessing: (() -> Void)? + + func queue(entity: DataEntity) -> Bool { + entities.append(entity) + return true + } + + func beginProcessing() { + operations.append(.beginProcessing) + onBeginProcessing?() + } + func suspend() { operations.append(.suspend) } + func clear() { + operations.append(.clear) + entities.removeAll() + } + func count() -> Int { return entities.count } + func close() { operations.append(.close) } + } + + private let bootEvent = Event(name: "Experience event", type: EventType.edge, source: EventSource.requestContent, data: nil) + + override func setUp() { + ServiceProvider.shared.namedKeyValueService = MockDataStore() + } + + func testInit_doesNotStartDeviceAttributesQueue() { + let primaryQueue = RecordingHitQueue() + let deviceAttributesQueue = RecordingHitQueue() + + let state = EdgeState(hitQueue: primaryQueue, deviceAttributesHitQueue: deviceAttributesQueue, edgeProperties: EdgeProperties()) + + XCTAssertEqual(.pending, state.currentCollectConsent) + XCTAssertEqual([.suspend], primaryQueue.operations) + XCTAssertEqual([], deviceAttributesQueue.operations) + } + + func testBootup_startsDeviceAttributesQueueOnceAfterImplementationDetailsAndPropertiesAreLoaded() { + let deviceAttributesQueue = RecordingHitQueue() + let state = EdgeState(hitQueue: RecordingHitQueue(), deviceAttributesHitQueue: deviceAttributesQueue, edgeProperties: EdgeProperties()) + var implementationDetailsAtStart: [String: Any]? + var sharedStateCreatedAtStart = false + var sharedStateCreated = false + deviceAttributesQueue.onBeginProcessing = { + implementationDetailsAtStart = state.implementationDetails + sharedStateCreatedAtStart = sharedStateCreated + } + let hubState: [String: Any] = ["wrapper": ["type": "N"], "version": "5.0.0"] + + for _ in 0..<2 { + state.bootupIfNeeded(event: bootEvent, + getSharedState: { name, _, _ in + name == EdgeConstants.SharedState.Hub.SHARED_OWNER_NAME ? SharedStateResult(status: .set, value: hubState) : nil + }, + createSharedState: { _, _ in sharedStateCreated = true }) + } + + XCTAssertTrue(state.hasBooted) + XCTAssertEqual([.beginProcessing], deviceAttributesQueue.operations) + XCTAssertNotNil(implementationDetailsAtStart) + XCTAssertTrue(sharedStateCreatedAtStart) + } + + func testCollectConsentChanges_doNotAffectDeviceAttributesQueue() { + let primaryQueue = RecordingHitQueue() + let deviceAttributesQueue = RecordingHitQueue() + let state = EdgeState(hitQueue: primaryQueue, deviceAttributesHitQueue: deviceAttributesQueue, edgeProperties: EdgeProperties()) + state.bootupIfNeeded(event: bootEvent, getSharedState: { _, _, _ in nil }, createSharedState: { _, _ in }) + let entity = DataEntity(uniqueIdentifier: UUID().uuidString, timestamp: Date(), data: Data()) + XCTAssertTrue(deviceAttributesQueue.queue(entity: entity)) + + for status in [ConsentStatus.pending, .no, .yes] { + state.updateCurrentConsent(status: status) + } + + XCTAssertEqual(.yes, state.currentCollectConsent) + XCTAssertEqual([.beginProcessing], deviceAttributesQueue.operations) + XCTAssertEqual(1, deviceAttributesQueue.count()) + XCTAssertTrue(primaryQueue.operations.contains(.clear)) + } + + func testMissingDeviceAttributesQueue_doesNotChangePrimaryConsentLifecycle() { + let primaryQueue = RecordingHitQueue() + let state = EdgeState(hitQueue: primaryQueue, deviceAttributesHitQueue: nil, edgeProperties: EdgeProperties()) + + state.updateCurrentConsent(status: .yes) + state.updateCurrentConsent(status: .pending) + state.updateCurrentConsent(status: .no) + + XCTAssertNil(state.deviceAttributesHitQueue) + XCTAssertEqual(.no, state.currentCollectConsent) + XCTAssertEqual([.suspend, .beginProcessing, .suspend, .clear, .beginProcessing], primaryQueue.operations) + } +} diff --git a/Tests/UnitTests/DeviceAttributesHitProcessorTests.swift b/Tests/UnitTests/DeviceAttributesHitProcessorTests.swift new file mode 100644 index 00000000..ef2a98ff --- /dev/null +++ b/Tests/UnitTests/DeviceAttributesHitProcessorTests.swift @@ -0,0 +1,476 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +@testable import AEPCore +@testable import AEPEdge +import AEPServices +import AEPTestUtils +import XCTest + +class DeviceAttributesHitProcessorTests: XCTestCase, AnyCodableAsserts { + /// Records requests and replies synchronously with the queued responses (the last one repeats). + private final class StubNetworking: Networking { + var responses: [HttpConnection] = [] + private(set) var requests: [NetworkRequest] = [] + + func connectAsync(networkRequest: NetworkRequest, completionHandler: ((HttpConnection) -> Void)?) { + requests.append(networkRequest) + let response = responses.count > 1 ? responses.removeFirst() : responses.first + completionHandler?(response ?? HttpConnection(data: nil, response: nil, error: nil)) + } + } + + private let testStoreName = "DeviceAttributesHitProcessorTests" + private let defaultConfig: [String: Any] = ["edge.configId": "test-config-id"] + private let defaultIdentityMap: [String: Any] = ["identityMap": ["ECID": [["id": "test-ecid", "authenticatedState": "ambiguous", "primary": false]]]] + private let defaultEventData: [String: Any] = ["timezone": "Europe/London", "tokens": ["pushNotification": "token"]] + private let successBody = #""" + { + "requestId": "server-request-id", + "handle": [ + { "type": "locationHint:result", "payload": [ + { "scope": "Target", "hint": "35", "ttlSeconds": 1800 }, + { "scope": "EdgeNetwork", "hint": "or2", "ttlSeconds": 1800 } + ] }, + { "type": "state:store", "payload": [ { "key": "kndctr_cookie", "value": "cookie-value", "maxAge": 1800 } ] }, + { "type": "personalization:decisions", "payload": [ { "id": "ignored" } ] } + ] + } + """# + + private var stubNetworking: StubNetworking! + private var dispatchedEvents: [Event] = [] + private var currentLocationHint: String? + private var implementationDetails: [String: Any]? = ["name": "https://ns.adobe.com/experience/mobilesdk/ios", "environment": "app", "version": "5.0.0"] + private var assuranceIntegrationId: String? + private var latestIdentity: [String: Any]? + private var processor: DeviceAttributesHitProcessor! + + override func setUp() { + ServiceProvider.shared.namedKeyValueService = MockDataStore() + stubNetworking = StubNetworking() + ServiceProvider.shared.networkService = stubNetworking + dispatchedEvents = [] + currentLocationHint = nil + assuranceIntegrationId = nil + latestIdentity = defaultIdentityMap + processor = makeProcessor() + } + + // MARK: Response classification + + func testProcessHit_200_dispatchesSuccessAndRemovesHit() throws { + stubNetworking.responses = [response(200, body: successBody)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 200) + } + + func testProcessHit_202_dispatchesSuccess() throws { + stubNetworking.responses = [response(202, body: nil)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 202) + } + + func testProcessHit_unsupportedOrUnrecoverableCodes_dispatchFailedNetwork() throws { + for code in [204, 207, 400, 401, 403, 404, 500] { + setUp() + stubNetworking.responses = [response(code, body: nil)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity), "code \(code)") + + try assertSingleResult(for: event, status: "failed", reason: "network", httpStatus: code) + } + } + + func testProcessHit_400ProblemJson_dispatchesFailedNetwork() throws { + let problem = #""" + {"type": "https://ns.adobe.com/aep/errors/EXEG-0003-400", "status": 400, "title": "Invalid request", + "report": {"requestId": "id", "errors": ["Missing timezone"]}} + """# + stubNetworking.responses = [response(400, body: problem)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + try assertSingleResult(for: event, status: "failed", reason: "network", httpStatus: 400) + } + + func testProcessHit_recoverableCodes_retryWithoutResultEvent() { + for code in [408, 429, 502, 503, 504, 507] { + setUp() + stubNetworking.responses = [response(code, body: nil)] + let (_, entity) = makeEntity() + + XCTAssertFalse(process(entity), "code \(code)") + + XCTAssertTrue(dispatchedEvents.isEmpty, "code \(code)") + XCTAssertEqual(EdgeConstants.Defaults.RETRY_INTERVAL, processor.retryInterval(for: entity), "code \(code)") + } + } + + func testProcessHit_recoverableCodeWithRetryAfter_usesHeaderInterval() { + stubNetworking.responses = [response(503, body: nil, headers: ["Retry-After": "30"])] + let (_, entity) = makeEntity() + + XCTAssertFalse(process(entity)) + + XCTAssertEqual(30, processor.retryInterval(for: entity)) + } + + func testProcessHit_recoverableUrlError_retriesWithoutResultEvent() { + stubNetworking.responses = [HttpConnection(data: nil, response: nil, error: URLError(.notConnectedToInternet))] + let (_, entity) = makeEntity() + + XCTAssertFalse(process(entity)) + + XCTAssertTrue(dispatchedEvents.isEmpty) + XCTAssertEqual(EdgeConstants.Defaults.RETRY_INTERVAL, processor.retryInterval(for: entity)) + } + + func testProcessHit_unrecoverableError_dispatchesFailedWithoutHttpStatus() throws { + stubNetworking.responses = [HttpConnection(data: nil, response: nil, error: URLError(.badURL))] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + try assertSingleResult(for: event, status: "failed", reason: "network", httpStatus: nil) + } + + func testProcessHit_noResponse_dispatchesFailedWithoutHttpStatus() throws { + stubNetworking.responses = [HttpConnection(data: nil, response: nil, error: nil)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + try assertSingleResult(for: event, status: "failed", reason: "network", httpStatus: nil) + } + + func testProcessHit_retryThenSuccess_dispatchesExactlyOneResult() throws { + stubNetworking.responses = [response(503, body: nil), response(503, body: nil), response(200, body: successBody)] + let (event, entity) = makeEntity() + + XCTAssertFalse(process(entity)) + XCTAssertFalse(process(entity)) + XCTAssertTrue(process(entity)) + + XCTAssertEqual(3, stubNetworking.requests.count) + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 200) + XCTAssertEqual(EdgeConstants.Defaults.RETRY_INTERVAL, processor.retryInterval(for: entity)) + } + + // MARK: Request + + func testProcessHit_sendsFlatBodyToDeviceAttributesEndpoint() throws { + assuranceIntegrationId = "assurance-id" + stubNetworking.responses = [response(200, body: nil)] + let (_, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + let request = try XCTUnwrap(stubNetworking.requests.first) + XCTAssertEqual(.post, request.httpMethod) + let components = try XCTUnwrap(URLComponents(url: request.url, resolvingAgainstBaseURL: false)) + XCTAssertEqual("edge.adobedc.net", components.host) + XCTAssertEqual("/ee/v1/mobile/device-attributes", components.path) + XCTAssertEqual("test-config-id", components.queryItems?.first { $0.name == "configId" }?.value) + XCTAssertFalse((components.queryItems?.first { $0.name == "requestId" }?.value ?? "").isEmpty) + XCTAssertEqual("assurance-id", request.httpHeaders["X-Adobe-AEP-Validation-Token"]) + XCTAssertEqual("application/json", request.httpHeaders["Content-Type"]) + + let body = try XCTUnwrap(String(data: request.connectPayload, encoding: .utf8)) + let expectedJSON = #""" + { + "timezone": "Europe/London", + "tokens": { "pushNotification": "token" }, + "xdm": { + "implementationDetails": { "name": "https://ns.adobe.com/experience/mobilesdk/ios", "environment": "app", "version": "5.0.0" }, + "identityMap": { "ECID": [ { "id": "test-ecid", "authenticatedState": "ambiguous", "primary": false } ] } + } + } + """# + assertExactMatch(expected: expectedJSON, actual: body) + XCTAssertFalse(body.contains("\n")) + } + + func testProcessHit_usesLocationHintEnvironmentAndCustomDomain() throws { + currentLocationHint = "va6" + stubNetworking.responses = [response(200, body: nil)] + let (_, entity) = makeEntity(config: ["edge.configId": "test-config-id", "edge.environment": "pre-prod", "edge.domain": "custom.example.com"]) + + XCTAssertTrue(process(entity)) + + let request = try XCTUnwrap(stubNetworking.requests.first) + XCTAssertEqual("custom.example.com", request.url.host) + XCTAssertEqual("/ee-pre-prd/va6/v1/mobile/device-attributes", request.url.path) + } + + func testProcessHit_doesNotSendAssuranceHeaderWhenUnavailable() throws { + stubNetworking.responses = [response(200, body: nil)] + let (_, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + XCTAssertNil(try XCTUnwrap(stubNetworking.requests.first).httpHeaders["X-Adobe-AEP-Validation-Token"]) + } + + // MARK: Response handles + + func testProcessHit_responseHandles_areIgnored() throws { + for code in [200, 400] { + setUp() + currentLocationHint = "va6" + StoreResponsePayloadManager(testStoreName) + .saveStorePayloads([StoreResponsePayload(payload: StorePayload(key: "existing", value: "existing-value", maxAge: 1800))]) + stubNetworking.responses = [response(code, body: successBody)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + // The request uses the stored hint; the response locationHint:result ("or2") and state:store handles are ignored + XCTAssertEqual("/ee/va6/v1/mobile/device-attributes", try XCTUnwrap(stubNetworking.requests.first).url.path) + XCTAssertEqual("va6", currentLocationHint) + let stored = StoreResponsePayloadManager(testStoreName).getActivePayloadList() + XCTAssertEqual(["existing"], stored.map { $0.key }, "HTTP \(code)") + XCTAssertEqual("existing-value", stored.first?.value) + // Only the device attributes response event is dispatched (no Edge response, error or complete events) + if code == 200 { + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 200) + } else { + try assertSingleResult(for: event, status: "failed", reason: "network", httpStatus: 400) + } + } + } + + func testProcessHit_successWithMalformedOrEmptyBody_stillSucceeds() throws { + for body in ["", "not json", "{}", #"{"handle": "invalid"}"#, #"{"handle": [{"type": "state:store", "payload": "invalid"}]}"#] { + setUp() + stubNetworking.responses = [response(200, body: body)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + XCTAssertTrue(StoreResponsePayloadManager(testStoreName).getActivePayloadList().isEmpty, body) + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 200) + } + } + + // MARK: ECID check + + func testProcessHit_sameEcid_isSent() throws { + stubNetworking.responses = [response(200, body: nil)] + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + XCTAssertEqual(1, stubNetworking.requests.count) + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 200) + } + + func testProcessHit_changedEcid_dispatchesDroppedIdentityChangedWithoutRequest() throws { + latestIdentity = identityState(ecids: ["new-ecid"]) + let (event, entity) = makeEntity() + + XCTAssertTrue(process(entity)) + + XCTAssertTrue(stubNetworking.requests.isEmpty) + try assertSingleResult(for: event, status: "dropped", reason: "identityChanged", httpStatus: nil) + } + + func testProcessHit_latestIdentityUnavailable_retriesWithoutRequestOrResult() { + latestIdentity = nil + let (_, entity) = makeEntity() + + XCTAssertFalse(process(entity)) + + XCTAssertTrue(stubNetworking.requests.isEmpty) + XCTAssertTrue(dispatchedEvents.isEmpty) + } + + func testProcessHit_ecidChangesBetweenRetries_isDroppedOnNextAttempt() throws { + stubNetworking.responses = [response(503, body: nil)] + let (event, entity) = makeEntity() + + XCTAssertFalse(process(entity)) + XCTAssertTrue(dispatchedEvents.isEmpty) + latestIdentity = identityState(ecids: ["new-ecid"]) + XCTAssertTrue(process(entity)) + + XCTAssertEqual(1, stubNetworking.requests.count) + try assertSingleResult(for: event, status: "dropped", reason: "identityChanged", httpStatus: nil) + } + + func testProcessHit_ecidChangesDuringRequest_dispatchesResponse() throws { + let (event, entity) = makeEntity() + ServiceProvider.shared.networkService = OnRequestNetworking(response: response(200, body: successBody)) { [weak self] in + self?.latestIdentity = self?.identityState(ecids: ["new-ecid"]) + } + + XCTAssertTrue(process(entity)) + + XCTAssertTrue(StoreResponsePayloadManager(testStoreName).getActivePayloadList().isEmpty) + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 200) + } + + func testProcessHit_legacyEcidAtIndexOne_doesNotAffectComparison() throws { + for (snapshot, latest) in [(["test-ecid", "legacy-ecid"], ["test-ecid", "other-legacy-ecid"]), + (["test-ecid", "legacy-ecid"], ["test-ecid"]), + (["test-ecid"], ["test-ecid", "legacy-ecid"])] { + setUp() + latestIdentity = identityState(ecids: latest) + stubNetworking.responses = [response(200, body: successBody)] + let (event, entity) = makeEntity(identityMap: identityState(ecids: snapshot)) + + XCTAssertTrue(process(entity)) + + XCTAssertEqual(1, stubNetworking.requests.count) + try assertSingleResult(for: event, status: "success", reason: nil, httpStatus: 200) + } + } + + // MARK: Drops + + func testProcessHit_missingDatastreamId_dispatchesDroppedMissingConfig() throws { + for config in [[:], ["edge.configId": ""]] as [[String: Any]] { + setUp() + let (event, entity) = makeEntity(config: config) + + XCTAssertTrue(process(entity)) + + XCTAssertTrue(stubNetworking.requests.isEmpty) + try assertSingleResult(for: event, status: "dropped", reason: "missingConfig", httpStatus: nil) + } + } + + func testProcessHit_emptyPayload_dispatchesDroppedInvalidPayload() throws { + implementationDetails = nil + latestIdentity = [:] + processor = makeProcessor() + let (event, entity) = makeEntity(eventData: ["xdm": ["producer": "value"]], identityMap: [:]) + + XCTAssertTrue(process(entity)) + + XCTAssertTrue(stubNetworking.requests.isEmpty) + try assertSingleResult(for: event, status: "dropped", reason: "invalidPayload", httpStatus: nil) + } + + func testProcessHit_invalidDomain_dispatchesDroppedInvalidPayloadWithoutRequest() throws { + // A host containing a space is invalid: `URLComponents` returns a nil URL (iOS 17+) or drops the host (earlier), so `buildUrl` returns nil + let (event, entity) = makeEntity(config: ["edge.configId": "test-config-id", "edge.domain": "invalid domain.com"]) + + XCTAssertTrue(process(entity)) + + XCTAssertTrue(stubNetworking.requests.isEmpty) + try assertSingleResult(for: event, status: "dropped", reason: "invalidPayload", httpStatus: nil) + } + + func testProcessHit_undecodableEntity_dispatchesUnchainedDrop() throws { + for data in [nil, Data("{".utf8), Data("{}".utf8)] { + setUp() + let entity = DataEntity(uniqueIdentifier: "stored-request-id", timestamp: Date(), data: data) + + XCTAssertTrue(process(entity)) + + XCTAssertTrue(stubNetworking.requests.isEmpty) + XCTAssertEqual(1, dispatchedEvents.count) + let result = try XCTUnwrap(dispatchedEvents.first) + XCTAssertNil(result.parentID) + XCTAssertEqual("Device Attributes Response", result.name) + XCTAssertEqual(EdgeConstants.DeviceAttributes.EVENT_TYPE, result.type) + XCTAssertEqual(EventSource.responseContent, result.source) + XCTAssertEqual(["status": "dropped", "reason": "invalidPayload", "requestEventId": "stored-request-id"] as NSDictionary, + result.data as NSDictionary?) + } + } + + // MARK: Helpers + + /// Runs `onRequest` while the request is in flight, then replies with `response`. + private final class OnRequestNetworking: Networking { + let response: HttpConnection + let onRequest: () -> Void + init(response: HttpConnection, onRequest: @escaping () -> Void) { + self.response = response + self.onRequest = onRequest + } + func connectAsync(networkRequest: NetworkRequest, completionHandler: ((HttpConnection) -> Void)?) { + onRequest() + completionHandler?(response) + } + } + + private func makeProcessor() -> DeviceAttributesHitProcessor { + return DeviceAttributesHitProcessor( + sharedStateReader: SharedStateReader(getSharedState: { [weak self] name, _, _ in + guard name == EdgeConstants.SharedState.Assurance.STATE_OWNER_NAME, let id = self?.assuranceIntegrationId else { return nil } + return SharedStateResult(status: .set, value: ["integrationid": id]) + }), + getImplementationDetails: { [weak self] in self?.implementationDetails }, + getLocationHint: { [weak self] in self?.currentLocationHint }, + getLatestIdentityMap: { [weak self] in self?.latestIdentity }, + dispatch: { [weak self] event in self?.dispatchedEvents.append(event) }, + storeDataStoreName: testStoreName) + } + + private func makeEntity(eventData: [String: Any]? = nil, + config: [String: Any]? = nil, + identityMap: [String: Any]? = nil) -> (Event, DataEntity) { + let event = Event(name: "Device Attributes Request", + type: EdgeConstants.DeviceAttributes.EVENT_TYPE, + source: EventSource.requestContent, + data: eventData ?? defaultEventData) + let edgeEntity = EdgeDataEntity(event: event, + configuration: AnyCodable.from(dictionary: config ?? defaultConfig) ?? [:], + identityMap: AnyCodable.from(dictionary: identityMap ?? defaultIdentityMap) ?? [:]) + let data = try? JSONEncoder().encode(edgeEntity) + return (event, DataEntity(uniqueIdentifier: event.id.uuidString, timestamp: Date(), data: data)) + } + + private func process(_ entity: DataEntity) -> Bool { + var result: Bool? + processor.processHit(entity: entity) { result = $0 } + XCTAssertNotNil(result, "processHit should complete synchronously with the stub network service") + return result ?? false + } + + private func response(_ code: Int, body: String?, headers: [String: String]? = nil) -> HttpConnection { + let url = URL(string: "https://edge.adobedc.net/ee/v1/mobile/device-attributes")! + return HttpConnection(data: body?.data(using: .utf8), + response: HTTPURLResponse(url: url, statusCode: code, httpVersion: nil, headerFields: headers), + error: nil) + } + + /// Edge Identity XDM shared state with the given ECIDs; index 0 is the current ECID, later entries are legacy ECIDs. + private func identityState(ecids: [String]) -> [String: Any] { + return ["identityMap": ["ECID": ecids.map { ["id": $0, "authenticatedState": "ambiguous", "primary": false] }]] + } + + private func assertSingleResult(for request: Event, status: String, reason: String?, httpStatus: Int?, + file: StaticString = #filePath, line: UInt = #line) throws { + XCTAssertEqual(1, dispatchedEvents.count, file: file, line: line) + let result = try XCTUnwrap(dispatchedEvents.first, file: file, line: line) + XCTAssertEqual("Device Attributes Response", result.name, file: file, line: line) + XCTAssertEqual(EdgeConstants.DeviceAttributes.EVENT_TYPE, result.type, file: file, line: line) + XCTAssertEqual(EventSource.responseContent, result.source, file: file, line: line) + XCTAssertEqual(request.id, result.parentID, file: file, line: line) + var expected: [String: Any] = ["status": status] + if let reason = reason { expected["reason"] = reason } + if let httpStatus = httpStatus { expected["httpStatus"] = httpStatus } + XCTAssertEqual(expected as NSDictionary, result.data as NSDictionary?, file: file, line: line) + } +} diff --git a/Tests/UnitTests/DeviceAttributesRequestBuilderTests.swift b/Tests/UnitTests/DeviceAttributesRequestBuilderTests.swift new file mode 100644 index 00000000..f435dab4 --- /dev/null +++ b/Tests/UnitTests/DeviceAttributesRequestBuilderTests.swift @@ -0,0 +1,187 @@ +// +// Copyright 2026 Adobe. All rights reserved. +// This file is licensed to you under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. You may obtain a copy +// of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +// OF ANY KIND, either express or implied. See the License for the specific language +// governing permissions and limitations under the License. +// + +@testable import AEPEdge +import AEPServices +import AEPTestUtils +import XCTest + +class DeviceAttributesRequestBuilderTests: XCTestCase, AnyCodableAsserts { + private let testDataStoreName = "DeviceAttributesRequestBuilderTests" + private let identityMap: [String: Any] = ["ECID": [["id": "ecid"]]] + private let implementationDetails: [String: Any] = [ + "name": "https://ns.adobe.com/experience/mobilesdk/ios", + "environment": "app", + "version": "5.0.0+1.0.0" + ] + + override func setUp() { + ServiceProvider.shared.namedKeyValueService = MockDataStore() + } + + func testBuildPayload_usesSdkXdmAndMetaInsteadOfProducerValues() throws { + StoreResponsePayloadManager(testDataStoreName) + .saveStorePayloads([StoreResponsePayload(payload: StorePayload(key: "key", value: "value", maxAge: 3600))]) + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + let eventData: [String: Any] = ["app": ["identifier": "com.example.app"], + "timezone": "America/Los_Angeles", + "xdm": ["identityMap": ["ECID": [["id": "producer-ecid"]]], "producerField": true], + "meta": ["configOverrides": ["datastreamIdOverride": "producer-datastream"]]] + + let payload = try XCTUnwrap(builder.buildPayload(eventData: eventData, + implementationDetails: implementationDetails, + identityMap: identityMap)) + + let expectedJSON = #""" + { + "app": { "identifier": "com.example.app" }, + "timezone": "America/Los_Angeles", + "xdm": { + "implementationDetails": { + "name": "https://ns.adobe.com/experience/mobilesdk/ios", + "environment": "app", + "version": "5.0.0+1.0.0" + }, + "identityMap": { "ECID": [ { "id": "ecid" } ] } + }, + "meta": { + "state": { + "entries": [ { "key": "key", "value": "value", "maxAge": 3600 } ] + } + } + } + """# + assertExactMatch(expected: expectedJSON, actual: payload) + } + + func testBuildPayload_preservesAppEmptyTokenAndTimezoneWithoutEventsEnvelope() throws { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + let attributes: [String: Any] = [ + "app": ["id": "com.example.app", "platform": "apnsSandbox"], + "timezone": "Europe/London", + "tokens": [ + "pushNotification": "", + "liveActivityStart": [["attributeType": "A", "value": "start"]], + "liveActivityUpdate": [] + ] + ] + let payload = try XCTUnwrap(builder.buildPayload(eventData: attributes, implementationDetails: nil, identityMap: nil)) + let decoded = try XCTUnwrap(try JSONSerialization.jsonObject(with: JSONEncoder().encode(payload)) as? [String: Any]) + + XCTAssertEqual(attributes["app"] as? NSDictionary, decoded["app"] as? NSDictionary) + XCTAssertEqual(attributes["tokens"] as? NSDictionary, decoded["tokens"] as? NSDictionary) + XCTAssertEqual("Europe/London", decoded["timezone"] as? String) + XCTAssertNil(decoded["events"]) + XCTAssertNil(decoded["xdm"]) + XCTAssertNil(decoded["meta"]) + } + + func testBuildPayload_discardsProducerXdmAndMetaWithoutSdkEnrichment() throws { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + let attributes: [String: Any] = [ + "app": ["id": "com.example.app", "newAttribute": ["enabled": true]], + "timezone": "Europe/London", + "newBackendAttribute": ["values": [1, 2], "label": "dynamic"] + ] + var producerData = attributes + producerData["xdm"] = ["identityMap": ["ECID": [["id": "producer-ecid"]]]] + producerData["meta"] = ["configOverrides": ["datastreamIdOverride": "producer-datastream"]] + + let payload = try XCTUnwrap(builder.buildPayload(eventData: producerData, implementationDetails: nil, identityMap: nil)) + let decoded = try XCTUnwrap(try JSONSerialization.jsonObject(with: JSONEncoder().encode(payload)) as? [String: Any]) + + XCTAssertEqual(attributes as NSDictionary, decoded as NSDictionary) + } + + func testBuildPayload_onlyProducerSdkFieldsAndNoEnrichment_returnsNil() { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + XCTAssertNil(builder.buildPayload(eventData: ["xdm": ["producerField": "value"], "meta": ["producerField": "value"]], + implementationDetails: nil, + identityMap: nil)) + } + + func testBuildPayload_nilOrEmptyEventData_returnsNil() { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + XCTAssertNil(builder.buildPayload(eventData: nil, implementationDetails: implementationDetails, identityMap: identityMap)) + XCTAssertNil(builder.buildPayload(eventData: [:], implementationDetails: implementationDetails, identityMap: identityMap)) + } + + func testBuildPayload_expiredStorePayloadsAreNotSent() throws { + StoreResponsePayloadManager(testDataStoreName) + .saveStorePayloads([StoreResponsePayload(payload: StorePayload(key: "expired", value: "value", maxAge: -1))]) + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + + let payload = try XCTUnwrap(builder.buildPayload(eventData: ["timezone": "UTC"], implementationDetails: nil, identityMap: nil)) + + XCTAssertNil(payload["meta"]) + } + + func testBuildRequestBody_isCompactJson() throws { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + + let body = try XCTUnwrap(builder.buildRequestBody(eventData: ["timezone": "UTC", "app": ["id": "com.example.app"]], + implementationDetails: nil, + identityMap: identityMap)) + + XCTAssertFalse(body.contains("\n")) + let expectedJSON = #"{"timezone": "UTC", "app": {"id": "com.example.app"}, "xdm": {"identityMap": {"ECID": [{"id": "ecid"}]}}}"# + assertExactMatch(expected: expectedJSON, actual: body) + } + + func testBuildRequestBody_unencodableData_returnsNil() { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + XCTAssertNil(builder.buildRequestBody(eventData: ["invalid": Double.nan], implementationDetails: nil, identityMap: nil)) + } + + func testBuildRequestBody_multipleEcids_retainsCurrentMetadataAndOtherNamespacesWithoutMutatingInput() throws { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + let current: [String: Any] = ["id": "current-ecid", "authenticatedState": "ambiguous", "primary": false] + let email: [[String: Any]] = [["id": "test@example.com", "authenticatedState": "authenticated", "primary": true]] + let identities: [String: Any] = [ + "ECID": [current, ["id": "legacy-ecid"], ["id": "another-ecid"]], + "Email": email + ] + let original = identities as NSDictionary + + let body = try XCTUnwrap(builder.buildRequestBody(eventData: ["timezone": "Europe/Rome"], + implementationDetails: nil, + identityMap: identities)) + let data = try XCTUnwrap(body.data(using: .utf8)) + let decoded = try XCTUnwrap(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + let xdm = try XCTUnwrap(decoded["xdm"] as? [String: Any]) + let requestIdentities = try XCTUnwrap(xdm["identityMap"] as? [String: Any]) + let ecids = try XCTUnwrap(requestIdentities["ECID"] as? [[String: Any]]) + + XCTAssertEqual(ecids.count, 1) + XCTAssertEqual(ecids[0] as NSDictionary, current as NSDictionary) + XCTAssertEqual(requestIdentities["Email"] as? NSArray, email as NSArray) + XCTAssertEqual(identities as NSDictionary, original) + XCTAssertEqual((identities["ECID"] as? [[String: Any]])?.count, 3) + } + + func testBuildPayload_singleEcid_preservesIdentityMap() throws { + let builder = DeviceAttributesRequestBuilder(dataStoreName: testDataStoreName) + let identities: [String: Any] = [ + "ECID": [["id": "current-ecid", "authenticatedState": "ambiguous", "primary": false]], + "Email": [["id": "test@example.com"]] + ] + + let payload = try XCTUnwrap(builder.buildPayload(eventData: ["timezone": "Europe/Rome"], + implementationDetails: nil, + identityMap: identities)) + let data = try JSONEncoder().encode(payload) + let decoded = try XCTUnwrap(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + let xdm = try XCTUnwrap(decoded["xdm"] as? [String: Any]) + + XCTAssertEqual(xdm["identityMap"] as? NSDictionary, identities as NSDictionary) + } +}