1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Dispatch
import struct Foundation.URL
import PackageModel
import protocol TSCBasic.Closable
public struct PackageIndexAndCollections: Closable {
private let index: PackageIndexProtocol
private let collections: PackageCollectionsProtocol
private let observabilityScope: ObservabilityScope
public init(
indexConfiguration: PackageIndexConfiguration = .init(),
collectionsConfiguration: PackageCollections.Configuration = .init(),
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) {
let index = PackageIndex(
configuration: indexConfiguration,
callbackQueue: .sharedConcurrent,
observabilityScope: observabilityScope
)
let metadataProvider = PackageIndexMetadataProvider(
index: index,
alternativeContainer: (
provider: GitHubPackageMetadataProvider(
configuration: .init(authTokens: collectionsConfiguration.authTokens),
observabilityScope: observabilityScope
),
managed: true
)
)
self.index = index
self.collections = PackageCollections(
configuration: collectionsConfiguration,
customMetadataProvider: metadataProvider,
fileSystem: fileSystem,
observabilityScope: observabilityScope
)
self.observabilityScope = observabilityScope
}
init(index: PackageIndexProtocol, collections: PackageCollectionsProtocol, observabilityScope: ObservabilityScope) {
self.index = index
self.collections = collections
self.observabilityScope = observabilityScope
}
public func close() throws {
if let index = self.index as? Closable {
try index.close()
}
if let collections = self.collections as? Closable {
try collections.close()
}
}
// MARK: - Package collection specific APIs
public func listCollections(
identifiers: Set<PackageCollectionsModel.CollectionIdentifier>? = nil
) async throws -> [PackageCollectionsModel.Collection] {
try await self.collections.listCollections(identifiers: identifiers)
}
/// - SeeAlso: `PackageCollectionsProtocol.listCollections`
@available(*, noasync, message: "Use the async alternative")
public func listCollections(
identifiers: Set<PackageCollectionsModel.CollectionIdentifier>? = nil,
callback: @escaping (Result<[PackageCollectionsModel.Collection], Error>) -> Void
) {
self.collections.listCollections(identifiers: identifiers, callback: callback)
}
public func refreshCollections() async throws -> [PackageCollectionsModel.CollectionSource] {
try await self.collections.refreshCollections()
}
/// - SeeAlso: `PackageCollectionsProtocol.refreshCollections`
@available(*, noasync, message: "Use the async alternative")
public func refreshCollections(callback: @escaping (Result<[PackageCollectionsModel.CollectionSource], Error>) -> Void) {
self.collections.refreshCollections(callback: callback)
}
public func refreshCollection(_ source: PackageCollectionsModel.CollectionSource) async throws -> PackageCollectionsModel.Collection {
try await self.collections.refreshCollection(source)
}
/// - SeeAlso: `PackageCollectionsProtocol.refreshCollection`
@available(*, noasync, message: "Use the async alternative")
public func refreshCollection(
_ source: PackageCollectionsModel.CollectionSource,
callback: @escaping (Result<PackageCollectionsModel.Collection, Error>) -> Void
) {
self.collections.refreshCollection(source, callback: callback)
}
public func addCollection(
_ source: PackageCollectionsModel.CollectionSource,
order: Int? = nil,
trustConfirmationProvider: ((PackageCollectionsModel.Collection, @escaping (Bool) -> Void) -> Void)? = nil
) async throws -> PackageCollectionsModel.Collection {
try await self.collections.addCollection(
source,
order: order,
trustConfirmationProvider: trustConfirmationProvider
)
}
/// - SeeAlso: `PackageCollectionsProtocol.addCollection`
@available(*, noasync, message: "Use the async alternative")
public func addCollection(
_ source: PackageCollectionsModel.CollectionSource,
order: Int? = nil,
trustConfirmationProvider: ((PackageCollectionsModel.Collection, @escaping (Bool) -> Void) -> Void)? = nil,
callback: @escaping (Result<PackageCollectionsModel.Collection, Error>) -> Void
) {
self.collections.addCollection(source, order: order, trustConfirmationProvider: trustConfirmationProvider, callback: callback)
}
public func removeCollection(
_ source: PackageCollectionsModel.CollectionSource
) async throws {
try await self.collections.removeCollection(source)
}
/// - SeeAlso: `PackageCollectionsProtocol.removeCollection`
@available(*, noasync, message: "Use the async alternative")
public func removeCollection(
_ source: PackageCollectionsModel.CollectionSource,
callback: @escaping (Result<Void, Error>) -> Void
) {
self.collections.removeCollection(source, callback: callback)
}
public func getCollection(
_ source: PackageCollectionsModel.CollectionSource
) async throws -> PackageCollectionsModel.Collection {
try await self.collections.getCollection(source)
}
/// - SeeAlso: `PackageCollectionsProtocol.getCollection`
@available(*, noasync, message: "Use the async alternative")
public func getCollection(
_ source: PackageCollectionsModel.CollectionSource,
callback: @escaping (Result<PackageCollectionsModel.Collection, Error>) -> Void
) {
self.collections.getCollection(source, callback: callback)
}
public func listPackages(
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil
) async throws -> PackageCollectionsModel.PackageSearchResult {
try await self.collections.listPackages(collections: collections)
}
/// - SeeAlso: `PackageCollectionsProtocol.listPackages`
@available(*, noasync, message: "Use the async alternative")
public func listPackages(
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil,
callback: @escaping (Result<PackageCollectionsModel.PackageSearchResult, Error>) -> Void
) {
self.collections.listPackages(collections: collections, callback: callback)
}
public func listTargets(
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil
) async throws -> PackageCollectionsModel.TargetListResult {
try await self.collections.listTargets(collections: collections)
}
/// - SeeAlso: `PackageCollectionsProtocol.listTargets`
@available(*, noasync, message: "Use the async alternative")
public func listTargets(
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil,
callback: @escaping (Result<PackageCollectionsModel.TargetListResult, Error>) -> Void
) {
self.collections.listTargets(collections: collections, callback: callback)
}
public func findTargets(
_ query: String,
searchType: PackageCollectionsModel.TargetSearchType? = nil,
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil
) async throws -> PackageCollectionsModel.TargetSearchResult {
try await self.collections.findTargets(
query,
searchType: searchType,
collections: collections
)
}
/// - SeeAlso: `PackageCollectionsProtocol.findTargets`
@available(*, noasync, message: "Use the async alternative")
public func findTargets(
_ query: String,
searchType: PackageCollectionsModel.TargetSearchType? = nil,
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil,
callback: @escaping (Result<PackageCollectionsModel.TargetSearchResult, Error>) -> Void
) {
self.collections.findTargets(query, searchType: searchType, collections: collections, callback: callback)
}
// MARK: - Package index specific APIs
/// Indicates if package index is configured.
public func isIndexEnabled() -> Bool {
self.index.isEnabled
}
public func listPackagesInIndex(
offset: Int,
limit: Int
) async throws -> PackageCollectionsModel.PaginatedPackageList {
try await self.index.listPackages(offset: offset, limit: limit)
}
/// - SeeAlso: `PackageIndexProtocol.listPackages`
@available(*, noasync, message: "Use the async alternative")
public func listPackagesInIndex(
offset: Int,
limit: Int,
callback: @escaping (Result<PackageCollectionsModel.PaginatedPackageList, Error>) -> Void
) {
self.index.listPackages(offset: offset, limit: limit, callback: callback)
}
// MARK: - APIs that make use of both package index and collections
public func getPackageMetadata(
identity: PackageIdentity,
location: String? = nil,
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil
) async throws -> PackageCollectionsModel.PackageMetadata {
try await safe_async {
self.getPackageMetadata(
identity: identity,
location: location,
collections: collections,
callback: $0
)
}
}
/// Returns metadata for the package identified by the given `PackageIdentity`, using package index (if configured)
/// and collections data.
///
/// A failure is returned if the package is not found.
///
/// - Parameters:
/// - identity: The package identity
/// - location: The package location (optional for deduplication)
/// - collections: Optional. If specified, only these collections are used to construct the result.
/// - callback: The closure to invoke when result becomes available
@available(*, noasync, message: "Use the async alternative")
public func getPackageMetadata(
identity: PackageIdentity,
location: String? = nil,
collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil,
callback: @escaping (Result<PackageCollectionsModel.PackageMetadata, Error>) -> Void
) {
// Package index not available - fallback to collections
guard self.index.isEnabled else {
return self.collections.getPackageMetadata(identity: identity, location: location, collections: collections, callback: callback)
}
// Get metadata using both package index and collections
let sync = DispatchGroup()
let results = ThreadSafeKeyValueStore<Source, Result<PackageCollectionsModel.PackageMetadata, Error>>()
sync.enter()
// This uses package index only
self.index.getPackageMetadata(identity: identity, location: location) { result in
defer { sync.leave() }
results[.index] = result
}
sync.enter()
// This uses either package index or "alternative" (e.g., GitHub) as metadata provider,
// then merge the supplementary metadata with data coming from collections. The package
// must belong to at least one collection.
self.collections.getPackageMetadata(identity: identity, location: location, collections: collections) { result in
defer { sync.leave() }
results[.collections] = result
}
sync.notify(queue: .sharedConcurrent) {
guard let indexResult = results[.index], let collectionsResult = results[.collections] else {
return callback(.failure(InternalError("Should contain results from package index and collections")))
}
switch (indexResult, collectionsResult) {
case (.success(let metadataResult), _):
// Metadata from `PackageIndex`
callback(.success(
PackageCollectionsModel.PackageMetadata(
package: metadataResult.package,
collections: collectionsResult.success?.collections ?? [],
provider: metadataResult.provider
)
))
case (.failure(let indexError), .success(let metadataResult)):
self.observabilityScope.emit(warning: "PackageIndex.getPackageMetadata failed: \(indexError)")
// Metadata from `PackageCollections`, which is a combination of
// package index/alternative (e.g., GitHub) and collection data.
callback(.success(metadataResult))
case (.failure(let indexError), .failure(let collectionsError)):
// Failed to get metadata through `PackageIndex` and `PackageCollections`.
// Return index's error.
self.observabilityScope.emit(warning: "PackageCollections.getPackageMetadata failed: \(collectionsError)")
callback(.failure(indexError))
}
}
}
public func findPackages(
_ query: String,
in searchIn: SearchIn = .both(collections: nil)
) async throws -> PackageCollectionsModel.PackageSearchResult {
try await safe_async {
self.findPackages(
query,
in: searchIn,
callback: $0
)
}
}
/// Finds and returns packages that match the query.
///
/// - Parameters:
/// - query: The search query
/// - in: Indicates whether to search in the index only, collections only, or both.
/// The optional `Set<CollectionIdentifier>` in some enum cases restricts search within those collections only.
/// - callback: The closure to invoke when result becomes available
@available(*, noasync, message: "Use the async alternative")
public func findPackages(
_ query: String,
in searchIn: SearchIn = .both(collections: nil),
callback: @escaping (Result<PackageCollectionsModel.PackageSearchResult, Error>) -> Void
) {
switch searchIn {
case .index:
guard self.index.isEnabled else {
self.observabilityScope.emit(debug: "Package index is not enabled. Returning empty result.")
return callback(.success(.init(items: [])))
}
self.index.findPackages(query, callback: callback)
case .collections(let collections):
self.collections.findPackages(query, collections: collections, callback: callback)
case .both(let collections):
// Find packages in both package index and collections
let sync = DispatchGroup()
let results = ThreadSafeKeyValueStore<Source, Result<PackageCollectionsModel.PackageSearchResult, Error>>()
sync.enter()
self.index.findPackages(query) { result in
defer { sync.leave() }
results[.index] = result
}
sync.enter()
self.collections.findPackages(query, collections: collections) { result in
defer { sync.leave() }
results[.collections] = result
}
sync.notify(queue: .sharedConcurrent) {
guard let indexResult = results[.index], let collectionsResult = results[.collections] else {
return callback(.failure(InternalError("Should contain results from package index and collections")))
}
switch (indexResult, collectionsResult) {
case (.success(let indexSearchResult), .success(let collectionsSearchResult)):
let indexItems = Dictionary(uniqueKeysWithValues: indexSearchResult.items.map {
(SearchResultItemKey(identity: $0.package.identity, location: $0.package.location), $0)
})
let collectionItems = Dictionary(uniqueKeysWithValues: collectionsSearchResult.items.map {
(SearchResultItemKey(identity: $0.package.identity, location: $0.package.location), $0)
})
// An array of combined results, with index items listed first.
var items = [PackageCollectionsModel.PackageSearchResult.Item]()
// Iterating through the dictionary would simplify the code, but we want to keep the ordering of the search result.
indexSearchResult.items.forEach {
var item = $0
let key = SearchResultItemKey(identity: $0.package.identity, location: $0.package.location)
// This item is found in collections too
if let collectionsMatch = collectionItems[key] {
item.collections = collectionsMatch.collections
}
items.append(item)
}
collectionsSearchResult.items.forEach {
let key = SearchResultItemKey(identity: $0.package.identity, location: $0.package.location)
// This item is found in index as well, but skipping since it has already been handled in the loop above.
guard indexItems[key] == nil else {
return
}
items.append($0)
}
callback(.success(PackageCollectionsModel.PackageSearchResult(items: items)))
case (.success(let indexSearchResult), .failure(let collectionsError)):
self.observabilityScope.emit(warning: "PackageCollections.findPackages failed: \(collectionsError)")
// Collections query failed, try another way to find the collections that an item belongs to.
self.collections.listPackages(collections: collections) { collectionsResult in
switch collectionsResult {
case .failure:
callback(.success(indexSearchResult))
case .success(let collectionsSearchResult):
let items = indexSearchResult.items.map { item in
PackageCollectionsModel.PackageSearchResult.Item(
package: item.package,
collections: collectionsSearchResult.items.first(where: {
item.package.identity == $0.package.identity && item.package.location == $0.package.location
})?.collections ?? [],
indexes: item.indexes
)
}
callback(.success(PackageCollectionsModel.PackageSearchResult(items: items)))
}
}
case (.failure(let indexError), .success(let searchResult)):
self.observabilityScope.emit(warning: "PackageIndex.findPackages failed: \(indexError)")
callback(.success(searchResult))
case (.failure(let indexError), .failure(let collectionsError)):
// Failed to find packages through `PackageIndex` and `PackageCollections`.
// Return index's error.
self.observabilityScope.emit(warning: "PackageCollections.findPackages failed: \(collectionsError)")
callback(.failure(indexError))
}
}
struct SearchResultItemKey: Hashable {
let identity: PackageIdentity
let location: String
}
}
}
private enum Source: Hashable {
case index
case collections
}
}
struct PackageIndexMetadataProvider: PackageMetadataProvider, Closable {
typealias ProviderContainer = (provider: PackageMetadataProvider, managed: Bool)
let index: PackageIndex
let alternativeContainer: ProviderContainer
var alternative: PackageMetadataProvider {
self.alternativeContainer.provider
}
func get(
identity: PackageIdentity,
location: String,
callback: @escaping (Result<PackageCollectionsModel.PackageBasicMetadata, Error>, PackageMetadataProviderContext?) -> Void
) {
if self.index.isEnabled {
self.index.get(identity: identity, location: location, callback: callback)
} else {
self.alternative.get(identity: identity, location: location, callback: callback)
}
}
func close() throws {
guard self.alternativeContainer.managed else {
return
}
if let alternative = self.alternative as? Closable {
try alternative.close()
}
}
}
extension PackageIndexAndCollections {
public enum SearchIn {
case index
case collections(Set<PackageCollectionsModel.CollectionIdentifier>?)
case both(collections: Set<PackageCollectionsModel.CollectionIdentifier>?)
}
}
|