diff --git a/CHANGELOG.md b/CHANGELOG.md index c61ec39..d1fbbe8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Next Version +- Added `KeyAccessTracking` to report keys that were never read while decoding, with their paths - Updated to Swift tools version 5.9, with minimum platforms of macOS 10.15, iOS 13, tvOS 13 and watchOS 6 - `URL` decoding rejects invalid URL strings again on macOS 14, iOS 17 and later, where `URL(string:)` started percent-encoding them - `DecodingError` is now `Sendable` diff --git a/README.md b/README.md index e5b7b60..31d3850 100644 --- a/README.md +++ b/README.md @@ -219,3 +219,25 @@ It's also possible to have an array of `JSONPrimitiveConvertible` values, for ex let urlsDictionary = ["urls": ["www.google.com", "www.yahoo.com"]] let urls: [URL] = try! urlsDictionary.json(atKeyPath: "urls") // [www.google.com, www.yahoo.com] ``` + +## Unused key tracking + +`KeyAccessTracking` can report keys that were present in your JSON but never read while decoding it, which is useful for warning about typos or unsupported keys. It's opt-in and does nothing unless you decode inside `KeyAccessTracking.record`. + +```swift +let json: JSONDictionary = ["name": "App", "child": ["name": "Child", "nmae": "typo"], "extra": 1] + +let (parent, unusedKeys) = try KeyAccessTracking.record(root: json) { + try Parent(jsonDictionary: json) +} +unusedKeys.map { $0.description } // ["child.nmae", "extra"] +``` + +Every `JSONObjectConvertible` decoded with `json(atKeyPath:)` gets its own scope, and unused keys are reported with their path, including array indexes like `children[1].key`. Keys are marked as read when they are accessed with `json(atKeyPath:)`, whether or not they decode successfully. + +- `KeyAccessTracking.markRead("key")` marks keys you read some other way, like `jsonDictionary["key"]`. +- `KeyAccessTracking.markAllRead()` marks every key of the current object as read, for objects whose keys are data. +- `KeyAccessTracking.scope(dictionary, at: ["sources", .index(1)]) { ... }` gives an object you decode yourself its own scope, at a path relative to the current one. +- Each `UnusedKey` has a `path` of `JSONPathComponent`s (`.key` or `.index`) and the unused `key`. Its `description` is the full path, like `sources[1].buildphase`. +- The current scope is a task local, so separate recordings never mix and child tasks continue their parent's recording. Threads that don't inherit task locals, like `DispatchQueue.concurrentPerform`, can continue it by capturing `KeyAccessTracking.currentContext` and running their decoding inside `KeyAccessTracking.withContext(context) { ... }`. + diff --git a/Sources/JSONUtilities/Dictionary+JSONKey.swift b/Sources/JSONUtilities/Dictionary+JSONKey.swift index 16ab81f..fe7df43 100644 --- a/Sources/JSONUtilities/Dictionary+JSONKey.swift +++ b/Sources/JSONUtilities/Dictionary+JSONKey.swift @@ -110,19 +110,26 @@ extension Dictionary where Key: JSONKey { // MARK: JSONObjectConvertible public func json(atKeyPath keyPath: KeyPath) throws -> T { - return try T(jsonDictionary: JSONDictionaryForKey(atKeyPath: keyPath)) + let jsonDictionary = try JSONDictionaryForKey(atKeyPath: keyPath) + return try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents) { + try T(jsonDictionary: jsonDictionary) + } } public func json(atKeyPath keyPath: KeyPath) -> T? { - return try? T(jsonDictionary: JSONDictionaryForKey(atKeyPath: keyPath)) + return try? json(atKeyPath: keyPath) as T } // MARK: [JSONObjectConvertible] public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [T] { + var index = -1 return try decodeArray(atKeyPath: keyPath, invalidItemBehaviour: invalidItemBehaviour) { keyPath, jsonArray, value in + index += 1 let jsonDictionary: JSONDictionary = try getValue(atKeyPath: keyPath, array: jsonArray, value: value) - return try T(jsonDictionary: jsonDictionary) + return try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents + [.index(index)]) { + try T(jsonDictionary: jsonDictionary) + } } } @@ -219,9 +226,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [T]] where T.RawValue: JSONRawType { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [T]] = [:] - for key in jsonDictionary.keys { - let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = array + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = array + } } return dictionary } @@ -235,9 +245,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [T]] { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [T]] = [:] - for key in jsonDictionary.keys { - let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = array + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = array + } } return dictionary } @@ -251,9 +264,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [T]] { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [T]] = [:] - for key in jsonDictionary.keys { - let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = array + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = array + } } return dictionary } @@ -267,9 +283,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [T]] { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [T]] = [:] - for key in jsonDictionary.keys { - let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = array + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let array: [T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = array + } } return dictionary } @@ -283,9 +302,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [String: T]] where T.RawValue: JSONRawType { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [String: T]] = [:] - for key in jsonDictionary.keys { - let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = subDictionary + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = subDictionary + } } return dictionary } @@ -299,9 +321,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [String: T]] { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [String: T]] = [:] - for key in jsonDictionary.keys { - let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = subDictionary + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = subDictionary + } } return dictionary } @@ -315,9 +340,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [String: T]] { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [String: T]] = [:] - for key in jsonDictionary.keys { - let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = subDictionary + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = subDictionary + } } return dictionary } @@ -331,9 +359,12 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [String: [String: T]] { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [String: [String: T]] = [:] - for key in jsonDictionary.keys { - let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) - dictionary[key] = subDictionary + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for key in jsonDictionary.keys { + let subDictionary: [String: T] = try jsonDictionary.json(atKeyPath: .key(key), invalidItemBehaviour: invalidItemBehaviour) + dictionary[key] = subDictionary + } } return dictionary } @@ -410,11 +441,15 @@ extension Dictionary where Key: JSONKey { public func json(atKeyPath keyPath: KeyPath, invalidItemBehaviour: InvalidItemBehaviour = .remove) throws -> [[T]] { + var outerIndex = -1 return try decodeArray(atKeyPath: keyPath) { (keyPath, jsonArray, value) -> [T] in + outerIndex += 1 if let array = value as? JSONArray { - return try array.map { - let jsonDictionary: JSONDictionary = try getValue(atKeyPath: keyPath, array: array, value: $0) - return try T(jsonDictionary: jsonDictionary) + return try array.enumerated().map { innerIndex, item in + let jsonDictionary: JSONDictionary = try getValue(atKeyPath: keyPath, array: array, value: item) + return try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents + [.index(outerIndex), .index(innerIndex)]) { + try T(jsonDictionary: jsonDictionary) + } } } else { throw DecodingError(dictionary: self, keyPath: keyPath, expectedType: JSONArray.self, value: value, array: jsonArray, reason: .incorrectType) @@ -464,9 +499,12 @@ extension Dictionary where Key: JSONKey { let jsonDictionary: JSONDictionary = try json(atKeyPath: keyPath) var dictionary: [K: T] = [:] - for (key, _) in jsonDictionary { - if let jsonKey = K(rawValue: key), let item = try invalidItemBehaviour.decodeItem(decode: { try decode(jsonDictionary, KeyPath.key(key)) }) { - dictionary[jsonKey] = item + // the keys of this dictionary are data, so give it a scope with all keys read + try KeyAccessTracking.scope(jsonDictionary, at: keyPath.pathComponents, allKeysRead: true) { () throws -> Void in + for (key, _) in jsonDictionary { + if let jsonKey = K(rawValue: key), let item = try invalidItemBehaviour.decodeItem(decode: { try decode(jsonDictionary, KeyPath.key(key)) }) { + dictionary[jsonKey] = item + } } } diff --git a/Sources/JSONUtilities/Dictionary+KeyPath.swift b/Sources/JSONUtilities/Dictionary+KeyPath.swift index 068e69c..7f0c67b 100644 --- a/Sources/JSONUtilities/Dictionary+KeyPath.swift +++ b/Sources/JSONUtilities/Dictionary+KeyPath.swift @@ -19,6 +19,7 @@ extension Dictionary { guard let dictionary = self as? JSONDictionary else { return nil } + KeyAccessTracking.didRead(keyPath.firstKey) return keyPath.getValue(dictionary: dictionary) } } diff --git a/Sources/JSONUtilities/KeyAccessTracking.swift b/Sources/JSONUtilities/KeyAccessTracking.swift new file mode 100644 index 0000000..779bb53 --- /dev/null +++ b/Sources/JSONUtilities/KeyAccessTracking.swift @@ -0,0 +1,241 @@ +// +// KeyAccessTracking.swift +// JSONUtilities +// + +import Foundation + +/// One step in the path to a JSON value: a dictionary key, or an array index +public enum JSONPathComponent: Hashable, Comparable, Sendable, CustomStringConvertible, ExpressibleByStringLiteral, ExpressibleByIntegerLiteral { + case key(String) + case index(Int) + + public init(stringLiteral value: String) { + self = .key(value) + } + + public init(integerLiteral value: Int) { + self = .index(value) + } + + /// `key` for a key, or `[index]` for an index + public var description: String { + switch self { + case let .key(key): return key + case let .index(index): return "[\(index)]" + } + } + + /// Keys sort before indexes, keys sort alphabetically and indexes numerically + public static func < (lhs: JSONPathComponent, rhs: JSONPathComponent) -> Bool { + switch (lhs, rhs) { + case let (.key(lhs), .key(rhs)): return lhs < rhs + case let (.index(lhs), .index(rhs)): return lhs < rhs + case (.key, .index): return true + case (.index, .key): return false + } + } + + /// Formats a path like `targets.App.sources[1]` + public static func format(_ path: [JSONPathComponent]) -> String { + var string = "" + for component in path { + switch component { + case let .key(key): + if !string.isEmpty { string += "." } + string += key + case .index: + string += component.description + } + } + return string + } +} + +/// A key that was present in a decoded JSON object but never read while decoding it. +public struct UnusedKey: Hashable, Comparable, Sendable, CustomStringConvertible { + + /// The path to the object that contains the key, e.g. `[.key("targets"), .key("App")]` or `[.key("sources"), .index(1)]` + public let path: [JSONPathComponent] + + /// The unused key itself + public let key: String + + public init(path: [JSONPathComponent], key: String) { + self.path = path + self.key = key + } + + /// The full path to the key, e.g. `targets.App.resources` or `sources[1].buildphase` + public var description: String { + return JSONPathComponent.format(path + [.key(key)]) + } + + /// Sorts by path, with array indexes in numeric order + public static func < (lhs: UnusedKey, rhs: UnusedKey) -> Bool { + return (lhs.path + [.key(lhs.key)]).lexicographicallyPrecedes(rhs.path + [.key(rhs.key)]) + } +} + +/// Records which keys are read while decoding JSON objects, so that keys that were never read can be reported. +/// +/// Recording is opt-in and only happens inside `KeyAccessTracking.record`. Outside of it, every call here is a no-op. +/// +/// While recording, every `JSONObjectConvertible` decoded through the `json(atKeyPath:)` functions gets its own scope. +/// Each key read through `json(atKeyPath:)` is marked as read in the innermost scope. When a scope finishes decoding +/// successfully, the keys of its dictionary that were never read are reported as `UnusedKey`s. +/// +/// The current scope is a task local value, so separate recordings never interfere with each other, and child tasks +/// continue the recording of their parent. Threads that aren't child tasks, like those of +/// `DispatchQueue.concurrentPerform`, don't inherit it: capture `currentContext` and continue it with `withContext`. +public enum KeyAccessTracking { + + // MARK: Public API + + /// Runs `body` while recording key reads, and returns its result along with all keys that were never read. + /// + /// - Parameters: + /// - root: An optional root dictionary to track. Its unused keys are reported with an empty path. + /// - body: The decoding to perform. + /// - Returns: The result of `body`, and the unused keys sorted by path. + public static func record(root: JSONDictionary? = nil, _ body: () throws -> R) rethrows -> (R, [UnusedKey]) { + let session = Session() + let rootScope = Scope(session: session, path: [], dictionary: root ?? [:], allKeysRead: root == nil) + let result = try $current.withValue(rootScope, operation: body) + rootScope.reportUnusedKeys() + return (result, session.unusedKeys) + } + + /// Whether key reads are currently being recorded + public static var isRecording: Bool { + return current != nil + } + + /// The path of the current scope, or nil when not recording + public static var currentPath: [JSONPathComponent]? { + return current?.path + } + + /// A handle to the current scope, for continuing the recording on threads that don't inherit it + public struct Context: @unchecked Sendable { + fileprivate let scope: Scope + } + + /// The current scope, or nil when not recording. Pass it to `withContext` on another thread. + public static var currentContext: Context? { + return current.map(Context.init) + } + + /// Runs `body` in the given context, so that its decoding is recorded as part of that context's scope. + public static func withContext(_ context: Context?, _ body: () throws -> R) rethrows -> R { + guard let context = context else { return try body() } + return try $current.withValue(context.scope, operation: body) + } + + /// Decodes a nested object in its own scope, with a path relative to the current scope. + /// The library does this for every object it decodes. Use it for objects you decode yourself. + /// + /// - Parameters: + /// - dictionary: The dictionary being decoded + /// - component: The path of this object relative to the current scope, e.g. `"settings"` + /// - allKeysRead: Pass true when the keys of this dictionary are data rather than known keys + public static func scope(_ dictionary: JSONDictionary, at component: JSONPathComponent, allKeysRead: Bool = false, _ body: () throws -> R) rethrows -> R { + return try scope(dictionary, at: [component], allKeysRead: allKeysRead, body) + } + + /// Decodes a nested object in its own scope, with a path relative to the current scope, + /// e.g. `["sources", .index(1)]` for an array element. + public static func scope(_ dictionary: JSONDictionary, at path: [JSONPathComponent], allKeysRead: Bool = false, _ body: () throws -> R) rethrows -> R { + guard let parent = current else { return try body() } + + let scope = Scope(session: parent.session, path: parent.path + path, dictionary: dictionary, allKeysRead: allKeysRead) + let result = try $current.withValue(scope, operation: body) + scope.reportUnusedKeys() + return result + } + + /// Marks keys of the current scope as read. Use this for keys read without `json(atKeyPath:)`, + /// for example `jsonDictionary["key"]`, or keys consumed before decoding. + public static func markRead(_ keys: String...) { + current?.markRead(keys) + } + + /// Marks keys of the current scope as read. + public static func markRead(_ keys: S) where S.Element == String { + current?.markRead(keys) + } + + /// Marks every key of the current scope as read. + /// Use this when the keys of the object being decoded are data, for example a dictionary of settings. + public static func markAllRead() { + current?.markAllRead() + } + + // MARK: Internal + + /// Called by `Dictionary.subscript(keyPath:)` for every top level key read + static func didRead(_ key: String) { + current?.markRead(CollectionOfOne(key)) + } + + // MARK: Private + + @TaskLocal private static var current: Scope? + + fileprivate final class Session: @unchecked Sendable { + private let lock = NSLock() + private var keys: [UnusedKey] = [] + + func add(_ newKeys: [UnusedKey]) { + lock.lock() + keys.append(contentsOf: newKeys) + lock.unlock() + } + + var unusedKeys: [UnusedKey] { + lock.lock() + defer { lock.unlock() } + return keys.sorted() + } + } + + // Reads can come from several threads at once when a context is shared, so state is behind a lock + fileprivate final class Scope: @unchecked Sendable { + let session: Session + let path: [JSONPathComponent] + private let dictionary: JSONDictionary + private let lock = NSLock() + private var readKeys: Set = [] + private var allKeysRead: Bool + + init(session: Session, path: [JSONPathComponent], dictionary: JSONDictionary, allKeysRead: Bool) { + self.session = session + self.path = path + self.dictionary = dictionary + self.allKeysRead = allKeysRead + } + + func markRead(_ keys: S) where S.Element == String { + lock.lock() + readKeys.formUnion(keys) + lock.unlock() + } + + func markAllRead() { + lock.lock() + allKeysRead = true + lock.unlock() + } + + func reportUnusedKeys() { + lock.lock() + let unused = allKeysRead ? [] : dictionary.keys + .filter { !readKeys.contains($0) } + .map { UnusedKey(path: path, key: $0) } + lock.unlock() + if !unused.isEmpty { + session.add(unused) + } + } + } +} diff --git a/Sources/JSONUtilities/KeyPath.swift b/Sources/JSONUtilities/KeyPath.swift index 0eaa35a..4a024a3 100644 --- a/Sources/JSONUtilities/KeyPath.swift +++ b/Sources/JSONUtilities/KeyPath.swift @@ -34,6 +34,22 @@ public enum KeyPath: JSONKey { } } + /// The first key of the key path, which is the key read on the dictionary itself + var firstKey: String { + switch self { + case let .key(key): return key + case let .keyPath(keys): return keys.first ?? "" + } + } + + /// The key path as path components for key access tracking + var pathComponents: [JSONPathComponent] { + switch self { + case let .key(key): return [.key(key)] + case let .keyPath(keys): return keys.map(JSONPathComponent.key) + } + } + func getValue(dictionary: JSONDictionary) -> Any? { switch self { diff --git a/Tests/JSONUtilitiesTests/KeyAccessTrackingTests.swift b/Tests/JSONUtilitiesTests/KeyAccessTrackingTests.swift new file mode 100644 index 0000000..2882a33 --- /dev/null +++ b/Tests/JSONUtilitiesTests/KeyAccessTrackingTests.swift @@ -0,0 +1,221 @@ +// +// KeyAccessTrackingTests.swift +// JSONUtilities +// + +import Foundation +import XCTest +@testable import JSONUtilities + +private struct TrackedChild: JSONObjectConvertible { + let name: String + + init(jsonDictionary: JSONDictionary) throws { + name = try jsonDictionary.json(atKeyPath: "name") + } +} + +private struct TrackedParent: JSONObjectConvertible { + let name: String + let child: TrackedChild? + let children: [TrackedChild] + let childMap: [String: TrackedChild] + let nestedArrays: [[TrackedChild]] + let freeForm: JSONDictionary? + let nestedValue: String? + + init(jsonDictionary: JSONDictionary) throws { + name = try jsonDictionary.json(atKeyPath: "name") + child = jsonDictionary.json(atKeyPath: "child") + children = jsonDictionary.json(atKeyPath: "children") ?? [] + childMap = jsonDictionary.json(atKeyPath: "childMap") ?? [:] + nestedArrays = jsonDictionary.json(atKeyPath: "nestedArrays") ?? [] + freeForm = jsonDictionary.json(atKeyPath: "freeForm") + nestedValue = jsonDictionary.json(atKeyPath: "nested.value") + } +} + +private struct MarkingObject: JSONObjectConvertible { + + init(jsonDictionary: JSONDictionary) throws { + KeyAccessTracking.markRead("consumedElsewhere") + if jsonDictionary["isFreeForm"] as? Bool == true { + KeyAccessTracking.markAllRead() + } + } +} + +class KeyAccessTrackingTests: XCTestCase { + + func testNotRecordingByDefault() throws { + XCTAssertFalse(KeyAccessTracking.isRecording) + XCTAssertNil(KeyAccessTracking.currentPath) + let parent = try TrackedParent(jsonDictionary: ["name": "parent", "unknown": 1]) + XCTAssertEqual(parent.name, "parent") + XCTAssertFalse(KeyAccessTracking.isRecording) + } + + func testAllKeysRead() throws { + let dictionary: JSONDictionary = [ + "name": "parent", + "child": ["name": "child"], + "children": [["name": "a"]], + ] + let (parent, unusedKeys) = try KeyAccessTracking.record(root: dictionary) { + try TrackedParent(jsonDictionary: dictionary) + } + XCTAssertEqual(parent.children.count, 1) + XCTAssertEqual(unusedKeys, []) + XCTAssertFalse(KeyAccessTracking.isRecording) + } + + func testReportsUnusedKeysWithPaths() throws { + let dictionary: JSONDictionary = [ + "name": "parent", + "typo": 1, + "child": ["name": "child", "extra": 1], + "children": [["name": "a"], ["name": "b", "oops": true]], + "childMap": ["x": ["name": "x", "bad": 1]], + "nestedArrays": [[["name": "a"]], [["name": "b", "deep": 1]]], + "freeForm": ["anything": 1, "goes": 2], + "nested": ["value": "v", "other": 1], + ] + let (parent, unusedKeys) = try KeyAccessTracking.record(root: dictionary) { + try TrackedParent(jsonDictionary: dictionary) + } + XCTAssertEqual(parent.nestedValue, "v") + XCTAssertEqual(unusedKeys.map { $0.description }, [ + "child.extra", + "childMap.x.bad", + "children[1].oops", + "nestedArrays[1][0].deep", + "typo", + ]) + XCTAssertEqual(unusedKeys.last, UnusedKey(path: [], key: "typo")) + } + + func testWithoutRootOnlyNestedObjectsAreChecked() throws { + let dictionary: JSONDictionary = ["parent": ["name": "parent", "typo": 1], "ignored": 1] + let (_, unusedKeys) = try KeyAccessTracking.record { + try dictionary.json(atKeyPath: "parent") as TrackedParent + } + XCTAssertEqual(unusedKeys.map { $0.description }, ["parent.typo"]) + } + + func testUnusedKeysSortIndexesNumerically() throws { + let children: [JSONDictionary] = (0..<12).map { ["name": "\($0)", "extra": 1] } + let dictionary: JSONDictionary = ["name": "parent", "children": children] + let (_, unusedKeys) = try KeyAccessTracking.record(root: dictionary) { + try TrackedParent(jsonDictionary: dictionary) + } + XCTAssertEqual(unusedKeys.map { $0.description }, (0..<12).map { "children[\($0)].extra" }) + XCTAssertEqual(unusedKeys[1].path, [.key("children"), .index(1)]) + } + + func testScopeWithPathComponents() throws { + let source: JSONDictionary = ["name": "a", "typo": 1] + let (_, unusedKeys) = try KeyAccessTracking.record { + try KeyAccessTracking.scope(source, at: ["targets", "App", "sources", 1]) { + XCTAssertEqual(KeyAccessTracking.currentPath, [.key("targets"), .key("App"), .key("sources"), .index(1)]) + return try TrackedChild(jsonDictionary: source) + } + } + XCTAssertEqual(unusedKeys, [UnusedKey(path: ["targets", "App", "sources", 1], key: "typo")]) + XCTAssertEqual(unusedKeys.map { $0.description }, ["targets.App.sources[1].typo"]) + } + + func testFailedDecodesAreNotReported() throws { + let dictionary: JSONDictionary = [ + "name": "parent", + "children": [["name": "a"], ["missingName": true]], + ] + let (parent, unusedKeys) = try KeyAccessTracking.record(root: dictionary) { + try TrackedParent(jsonDictionary: dictionary) + } + XCTAssertEqual(parent.children.count, 1) + XCTAssertEqual(unusedKeys, []) + } + + func testMarkReadAndMarkAllRead() throws { + let dictionary: JSONDictionary = [ + "marked": ["consumedElsewhere": 1, "unknown": 1], + "freeForm": ["isFreeForm": true, "anything": 1], + ] + let (_, unusedKeys) = try KeyAccessTracking.record { + _ = try dictionary.json(atKeyPath: "marked") as MarkingObject + _ = try dictionary.json(atKeyPath: "freeForm") as MarkingObject + } + XCTAssertEqual(unusedKeys.map { $0.description }, ["marked.unknown"]) + } + + func testScopeOutsideRecordingIsNoOp() throws { + let child = try KeyAccessTracking.scope(["name": "a", "unknown": 1], at: "child") { + try TrackedChild(jsonDictionary: ["name": "a", "unknown": 1]) + } + XCTAssertEqual(child.name, "a") + KeyAccessTracking.markRead("anything") + KeyAccessTracking.markAllRead() + XCTAssertNil(KeyAccessTracking.currentPath) + } + + func testConcurrentScopesWithContext() throws { + var items: JSONDictionary = [:] + for index in 0..<50 { + items["item\(index)"] = ["name": "item\(index)", "unknown\(index)": true] + } + let dictionary: JSONDictionary = ["items": items] + + let (names, unusedKeys) = try KeyAccessTracking.record(root: dictionary) { () -> [String] in + let itemsDictionary: JSONDictionary = try dictionary.json(atKeyPath: "items") + return try KeyAccessTracking.scope(itemsDictionary, at: "items", allKeysRead: true) { + let context = KeyAccessTracking.currentContext + XCTAssertNotNil(context) + let keys = Array(itemsDictionary.keys) + let lock = NSLock() + var names: [String] = [] + DispatchQueue.concurrentPerform(iterations: keys.count) { index in + let key = keys[index] + let child = try? KeyAccessTracking.withContext(context) { + try itemsDictionary.json(atKeyPath: .key(key)) as TrackedChild + } + lock.lock() + names.append(child?.name ?? "") + lock.unlock() + } + return names + } + } + + XCTAssertEqual(names.count, 50) + XCTAssertEqual(unusedKeys.count, 50) + XCTAssertEqual(Set(unusedKeys.map { $0.description }), Set((0..<50).map { "items.item\($0).unknown\($0)" })) + } + + func testSeparateRecordingsDontInterfere() { + let lock = NSLock() + var results: [Int: [String]] = [:] + DispatchQueue.concurrentPerform(iterations: 20) { index in + let dictionary: JSONDictionary = ["name": "parent", "unknown\(index)": true, "child": ["name": "child", "extra\(index)": 1]] + let (_, unusedKeys) = try! KeyAccessTracking.record(root: dictionary) { + try TrackedParent(jsonDictionary: dictionary) + } + lock.lock() + results[index] = unusedKeys.map { $0.description } + lock.unlock() + } + for index in 0..<20 { + XCTAssertEqual(results[index], ["child.extra\(index)", "unknown\(index)"]) + } + } + + func testNestedRecordingsAreSeparate() throws { + let outer: JSONDictionary = ["name": "outer", "outerUnknown": 1] + let inner: JSONDictionary = ["name": "inner", "innerUnknown": 1] + let (innerKeys, outerKeys) = try KeyAccessTracking.record(root: outer) { () -> [UnusedKey] in + _ = try TrackedParent(jsonDictionary: outer) + return try KeyAccessTracking.record(root: inner) { try TrackedParent(jsonDictionary: inner) }.1 + } + XCTAssertEqual(innerKeys.map { $0.description }, ["innerUnknown"]) + XCTAssertEqual(outerKeys.map { $0.description }, ["outerUnknown"]) + } +}