Skip to content

Commit 4ab1f7c

Browse files
authored
package collections small refactoring (#3072)
motivation: nicer code changes: * create an internal alias for the model defintion so code is less verbose * better handling of default http client initialization
1 parent ed2cb1e commit 4ab1f7c

9 files changed

+118
-121
lines changed

Sources/PackageCollections/Model/Collection.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ import TSCUtility
1717

1818
public enum PackageCollectionsModel {}
1919

20+
// make things less verbose internally
21+
internal typealias Model = PackageCollectionsModel
22+
2023
extension PackageCollectionsModel {
2124
/// A `Collection` is a collection of packages.
2225
public struct Collection: Equatable, Codable {
@@ -46,7 +49,7 @@ extension PackageCollectionsModel {
4649

4750
/// Who authored this collection
4851
public let createdBy: Author?
49-
52+
5053
/// When this collection was last processed locally
5154
public let lastProcessedAt: Date
5255

Sources/PackageCollections/Model/Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ extension PackageCollectionsModel.Package {
112112

113113
/// The package version's Swift tools version
114114
public let toolsVersion: ToolsVersion
115-
115+
116116
/// The package version's supported platforms
117117
public let minimumPlatformVersions: [SupportedPlatform]?
118118

Sources/PackageCollections/PackageCollections+Validation.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
import TSCBasic
1212

13-
extension PackageCollectionsModel.CollectionSource {
13+
extension Model.CollectionSource {
1414
func validate() -> [ValidationError]? {
1515
var errors: [ValidationError]?
1616
let appendError = { (error: ValidationError) in

Sources/PackageCollections/PackageCollections.swift

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import TSCBasic
1515
public struct PackageCollections: PackageCollectionsProtocol {
1616
private let configuration: Configuration
1717
private let storageContainer: (storage: Storage, owned: Bool)
18-
private let collectionProviders: [PackageCollectionsModel.CollectionSourceType: PackageCollectionProvider]
18+
private let collectionProviders: [Model.CollectionSourceType: PackageCollectionProvider]
1919
private let metadataProvider: PackageMetadataProvider
2020

2121
private var storage: Storage {
@@ -26,7 +26,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
2626
public init(configuration: Configuration = .init()) {
2727
let storage = Storage(sources: FilePackageCollectionsSourcesStorage(),
2828
collections: SQLitePackageCollectionsStorage())
29-
let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: JSONPackageCollectionProvider()]
29+
let collectionProviders = [Model.CollectionSourceType.json: JSONPackageCollectionProvider()]
3030
let metadataProvider = GitHubPackageMetadataProvider()
3131

3232
self.configuration = configuration
@@ -38,7 +38,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
3838
// internal initializer for testing
3939
init(configuration: Configuration = .init(),
4040
storage: Storage,
41-
collectionProviders: [PackageCollectionsModel.CollectionSourceType: PackageCollectionProvider],
41+
collectionProviders: [Model.CollectionSourceType: PackageCollectionProvider],
4242
metadataProvider: PackageMetadataProvider) {
4343
self.configuration = configuration
4444
self.storageContainer = (storage, false)
@@ -65,7 +65,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
6565
if identifiers.isEmpty {
6666
return callback(.success([]))
6767
}
68-
let collectionOrder = identifiers.enumerated().reduce([PackageCollectionsModel.CollectionIdentifier: Int]()) { partial, element in
68+
let collectionOrder = identifiers.enumerated().reduce([Model.CollectionIdentifier: Int]()) { partial, element in
6969
var dictionary = partial
7070
dictionary[element.element] = element.offset
7171
return dictionary
@@ -94,7 +94,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
9494
return callback(.success([]))
9595
}
9696
let lock = Lock()
97-
var refreshResults = [Result<PackageCollectionsModel.Collection, Error>]()
97+
var refreshResults = [Result<Model.Collection, Error>]()
9898
sources.forEach { source in
9999
self.refreshCollectionFromSource(source: source) { refreshResult in
100100
lock.withLock { refreshResults.append(refreshResult) }
@@ -181,7 +181,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
181181
case .success(let sources):
182182
let identifiers = sources.map { .init(from: $0) }.filter { collections?.contains($0) ?? true }
183183
if identifiers.isEmpty {
184-
return callback(.success(PackageCollectionsModel.PackageSearchResult(items: [])))
184+
return callback(.success(Model.PackageSearchResult(items: [])))
185185
}
186186
self.storage.collections.searchPackages(identifiers: identifiers, query: query, callback: callback)
187187
}
@@ -202,7 +202,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
202202
self.metadataProvider.get(reference) { result in
203203
switch result {
204204
case .failure(let error) where error is NotFoundError:
205-
let metadata = PackageCollectionsModel.PackageMetadata(
205+
let metadata = Model.PackageMetadata(
206206
package: Self.mergedPackageMetadata(package: packageSearchResult.package, basicMetadata: nil),
207207
collections: packageSearchResult.collections
208208
)
@@ -211,7 +211,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
211211
callback(.failure(error))
212212
case .success(let basicMetadata):
213213
// finally merge the results
214-
let metadata = PackageCollectionsModel.PackageMetadata(
214+
let metadata = Model.PackageMetadata(
215215
package: Self.mergedPackageMetadata(package: packageSearchResult.package, basicMetadata: basicMetadata),
216216
collections: packageSearchResult.collections
217217
)
@@ -267,7 +267,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
267267
// This helps avoid network access in normal operations
268268
private func refreshCollectionFromSource(source: PackageCollectionsModel.CollectionSource,
269269
order _: Int? = nil,
270-
callback: @escaping (Result<PackageCollectionsModel.Collection, Error>) -> Void) {
270+
callback: @escaping (Result<Model.Collection, Error>) -> Void) {
271271
if let errors = source.validate() {
272272
return callback(.failure(MultipleErrors(errors)))
273273
}
@@ -293,7 +293,7 @@ public struct PackageCollections: PackageCollectionsProtocol {
293293
case .failure(let error):
294294
callback(.failure(error))
295295
case .success(let sources):
296-
let identifiers = sources.map { PackageCollectionsModel.CollectionIdentifier(from: $0) }
296+
let identifiers = sources.map { Model.CollectionIdentifier(from: $0) }
297297
if identifiers.isEmpty {
298298
return callback(.failure(NotFoundError("\(identifier)")))
299299
}
@@ -302,9 +302,9 @@ public struct PackageCollections: PackageCollectionsProtocol {
302302
}
303303
}
304304

305-
private func targetListResultFromCollections(_ collections: [PackageCollectionsModel.Collection]) -> PackageCollectionsModel.TargetListResult {
306-
var packageCollections = [PackageReference: (package: PackageCollectionsModel.Package, collections: Set<PackageCollectionsModel.CollectionIdentifier>)]()
307-
var targetsPackages = [String: (target: PackageCollectionsModel.Target, packages: Set<PackageReference>)]()
305+
private func targetListResultFromCollections(_ collections: [Model.Collection]) -> Model.TargetListResult {
306+
var packageCollections = [PackageReference: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()
307+
var targetsPackages = [String: (target: Model.Target, packages: Set<PackageReference>)]()
308308

309309
collections.forEach { collection in
310310
collection.packages.forEach { package in
@@ -327,21 +327,21 @@ public struct PackageCollections: PackageCollectionsProtocol {
327327
return targetsPackages.map { _, pair in
328328
let targetPackages = pair.packages
329329
.compactMap { packageCollections[$0] }
330-
.map { pair -> PackageCollectionsModel.TargetListResult.Package in
331-
let versions = pair.package.versions.map { PackageCollectionsModel.TargetListResult.PackageVersion(version: $0.version, packageName: $0.packageName) }
330+
.map { pair -> Model.TargetListResult.Package in
331+
let versions = pair.package.versions.map { Model.TargetListResult.PackageVersion(version: $0.version, packageName: $0.packageName) }
332332
return .init(repository: pair.package.repository,
333333
summary: pair.package.summary,
334334
versions: versions,
335335
collections: Array(pair.collections))
336336
}
337337

338-
return PackageCollectionsModel.TargetListItem(target: pair.target, packages: targetPackages)
338+
return Model.TargetListItem(target: pair.target, packages: targetPackages)
339339
}
340340
}
341341

342-
internal static func mergedPackageMetadata(package: PackageCollectionsModel.Package,
343-
basicMetadata: PackageCollectionsModel.PackageBasicMetadata?) -> PackageCollectionsModel.Package {
344-
var versions = package.versions.map { packageVersion -> PackageCollectionsModel.Package.Version in
342+
internal static func mergedPackageMetadata(package: Model.Package,
343+
basicMetadata: Model.PackageBasicMetadata?) -> Model.Package {
344+
var versions = package.versions.map { packageVersion -> Model.Package.Version in
345345
.init(version: packageVersion.version,
346346
packageName: packageVersion.packageName,
347347
targets: packageVersion.targets,
@@ -371,9 +371,9 @@ public struct PackageCollections: PackageCollectionsProtocol {
371371
}
372372

373373
private struct UnknownProvider: Error {
374-
let sourceType: PackageCollectionsModel.CollectionSourceType
374+
let sourceType: Model.CollectionSourceType
375375

376-
init(_ sourceType: PackageCollectionsModel.CollectionSourceType) {
376+
init(_ sourceType: Model.CollectionSourceType) {
377377
self.sourceType = sourceType
378378
}
379379
}

Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,11 @@ import TSCBasic
2020

2121
struct GitHubPackageMetadataProvider: PackageMetadataProvider {
2222
let httpClient: HTTPClient
23-
let defaultHttpClient: Bool
2423
let decoder: JSONDecoder
2524
let queue: DispatchQueue
2625

2726
init(httpClient: HTTPClient? = nil) {
28-
self.httpClient = httpClient ?? .init()
29-
self.defaultHttpClient = httpClient == nil
27+
self.httpClient = httpClient ?? Self.makeDefaultHTTPClient()
3028
self.decoder = JSONDecoder()
3129
#if os(Linux) || os(Windows)
3230
self.decoder.dateDecodingStrategy = .iso8601
@@ -40,7 +38,7 @@ struct GitHubPackageMetadataProvider: PackageMetadataProvider {
4038
self.queue = DispatchQueue(label: "org.swift.swiftpm.GitHubPackageMetadataProvider", attributes: .concurrent)
4139
}
4240

43-
func get(_ reference: PackageReference, callback: @escaping (Result<PackageCollectionsModel.PackageBasicMetadata, Error>) -> Void) {
41+
func get(_ reference: PackageReference, callback: @escaping (Result<Model.PackageBasicMetadata, Error>) -> Void) {
4442
guard reference.kind == .remote else {
4543
return callback(.failure(Errors.invalidReferenceType(reference)))
4644
}
@@ -143,19 +141,18 @@ struct GitHubPackageMetadataProvider: PackageMetadataProvider {
143141
var options = HTTPClientRequest.Options()
144142
options.addUserAgent = true
145143
options.validResponseCodes = validResponseCodes
146-
if defaultHttpClient {
147-
// TODO: make these defaults configurable?
148-
options.timeout = httpClient.configuration.requestTimeout ?? .seconds(1)
149-
options.retryStrategy = httpClient.configuration.retryStrategy ?? .exponentialBackoff(maxAttempts: 3, baseDelay: .milliseconds(50))
150-
options.circuitBreakerStrategy = httpClient.configuration.circuitBreakerStrategy ?? .hostErrors(maxErrors: 5, age: .seconds(5))
151-
} else {
152-
options.timeout = httpClient.configuration.requestTimeout
153-
options.retryStrategy = httpClient.configuration.retryStrategy
154-
options.circuitBreakerStrategy = httpClient.configuration.circuitBreakerStrategy
155-
}
156144
return options
157145
}
158146

147+
private static func makeDefaultHTTPClient() -> HTTPClient {
148+
var client = HTTPClient()
149+
// TODO: make these defaults configurable?
150+
client.configuration.requestTimeout = .seconds(1)
151+
client.configuration.retryStrategy = .exponentialBackoff(maxAttempts: 3, baseDelay: .milliseconds(50))
152+
client.configuration.circuitBreakerStrategy = .hostErrors(maxErrors: 50, age: .seconds(30))
153+
return client
154+
}
155+
159156
enum Errors: Error, Equatable {
160157
case invalidReferenceType(PackageReference)
161158
case invalidGitUrl(String)

0 commit comments

Comments
 (0)