func findPackage()

in Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift [409:498]


    func findPackage(identifier: PackageIdentity,
                     collectionIdentifiers: [Model.CollectionIdentifier]?,
                     callback: @escaping (Result<(packages: [PackageCollectionsModel.Package], collections: [PackageCollectionsModel.CollectionIdentifier]), Error>) -> Void) {
        let useSearchIndices: Bool
        do {
            useSearchIndices = try self.shouldUseSearchIndices()
        } catch {
            return callback(.failure(error))
        }

        if useSearchIndices {
            var matches = [(collection: Model.CollectionIdentifier, package: PackageIdentity)]()
            var matchingCollections = Set<Model.CollectionIdentifier>()

            do {
                let packageQuery = "SELECT collection_id_blob_base64, repository_url FROM \(Self.packagesFTSName) WHERE id = ?;"
                try self.executeStatement(packageQuery) { statement in
                    try statement.bind([.string(identifier.description)])

                    while let row = try statement.step() {
                        if let collectionData = Data(base64Encoded: row.string(at: 0)),
                            let collection = try? self.decoder.decode(Model.CollectionIdentifier.self, from: collectionData) {
                            matches.append((collection: collection, package: PackageIdentity(urlString: row.string(at: 1))))
                            matchingCollections.insert(collection)
                        }
                    }
                }
            } catch {
                return callback(.failure(error))
            }

            // Optimization: return early if no matches
            guard !matches.isEmpty else {
                return callback(.failure(NotFoundError("\(identifier)")))
            }

            // Optimization: fetch only those collections that contain matching packages
            self.list(identifiers: Array(collectionIdentifiers.map { Set($0).intersection(matchingCollections) } ?? matchingCollections)) { result in
                switch result {
                case .failure(let error):
                    return callback(.failure(error))
                case .success(let collections):
                    let collectionDict = collections.reduce(into: [Model.CollectionIdentifier: Model.Collection]()) { result, collection in
                        result[collection.identifier] = collection
                    }

                    let collections = matches.filter { collectionDict.keys.contains($0.collection) }
                        .compactMap { collectionDict[$0.collection] }
                        // Sort collections by processing date so the latest metadata is first
                        .sorted(by: { lhs, rhs in lhs.lastProcessedAt > rhs.lastProcessedAt })

                    // rdar://79069839 - Package identities are not unique to repository URLs so there can be more than one result.
                    // It's up to the caller to filter out the best-matched package(s). Results are sorted with the latest ones first.
                    let packages = collections.flatMap { collection in
                        collection.packages.filter { $0.identity == identifier }
                    }

                    guard !packages.isEmpty else {
                        return callback(.failure(NotFoundError("\(identifier)")))
                    }

                    callback(.success((packages: packages, collections: collections.map { $0.identifier })))
                }
            }
        } else {
            self.list(identifiers: collectionIdentifiers) { result in
                switch result {
                case .failure(let error):
                    return callback(.failure(error))
                case .success(let collections):
                    // sorting by collection processing date so the latest metadata is first
                    let collectionPackages = collections.sorted(by: { lhs, rhs in lhs.lastProcessedAt > rhs.lastProcessedAt }).compactMap { collection in
                        collection.packages
                            .first(where: { $0.identity == identifier })
                            .flatMap { (collection: collection.identifier, package: $0) }
                    }

                    // rdar://79069839 - Package identities are not unique to repository URLs so there can be more than one result.
                    // It's up to the caller to filter out the best-matched package(s). Results are sorted with the latest ones first.
                    let packages = collectionPackages.map { $0.package }

                    guard !packages.isEmpty else {
                        return callback(.failure(NotFoundError("\(identifier)")))
                    }

                    callback(.success((packages: packages, collections: collectionPackages.map { $0.collection })))
                }
            }
        }
    }