|
| 1 | +/* |
| 2 | + This source file is part of the Swift.org open source project |
| 3 | + |
| 4 | + Copyright (c) 2020 Apple Inc. and the Swift project authors |
| 5 | + Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | + |
| 7 | + See http://swift.org/LICENSE.txt for license information |
| 8 | + See http://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | + */ |
| 10 | + |
| 11 | +import Basics |
| 12 | +import Dispatch |
| 13 | +import struct Foundation.Date |
| 14 | +import class Foundation.JSONDecoder |
| 15 | +import struct Foundation.NSRange |
| 16 | +import class Foundation.NSRegularExpression |
| 17 | +import struct Foundation.URL |
| 18 | +import PackageModel |
| 19 | +import TSCBasic |
| 20 | + |
| 21 | +struct GitHubPackageMetadataProvider: PackageMetadataProvider { |
| 22 | + let httpClient: HTTPClient |
| 23 | + let defaultHttpClient: Bool |
| 24 | + let decoder: JSONDecoder |
| 25 | + let queue: DispatchQueue |
| 26 | + |
| 27 | + init(httpClient: HTTPClient? = nil) { |
| 28 | + self.httpClient = httpClient ?? .init() |
| 29 | + self.defaultHttpClient = httpClient == nil |
| 30 | + self.decoder = JSONDecoder() |
| 31 | + #if os(Linux) |
| 32 | + self.decoder.dateDecodingStrategy = .iso8601 |
| 33 | + #else |
| 34 | + if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { |
| 35 | + self.decoder.dateDecodingStrategy = .iso8601 |
| 36 | + } else { |
| 37 | + self.decoder.dateDecodingStrategy = .customISO8601 |
| 38 | + } |
| 39 | + #endif |
| 40 | + self.queue = DispatchQueue(label: "org.swift.swiftpm.GitHubPackageMetadataProvider", attributes: .concurrent) |
| 41 | + } |
| 42 | + |
| 43 | + func get(_ reference: PackageReference, callback: @escaping (Result<PackageCollectionsModel.PackageBasicMetadata, Error>) -> Void) { |
| 44 | + guard reference.kind == .remote else { |
| 45 | + return callback(.failure(Errors.unprocessable(reference))) |
| 46 | + } |
| 47 | + guard let baseURL = self.apiURL(reference.path) else { |
| 48 | + return callback(.failure(Errors.unprocessable(reference))) |
| 49 | + } |
| 50 | + |
| 51 | + let metadataURL = baseURL |
| 52 | + let tagsURL = baseURL.appendingPathComponent("tags") |
| 53 | + let contributorsURL = baseURL.appendingPathComponent("contributors") |
| 54 | + let readmeURL = baseURL.appendingPathComponent("readme") |
| 55 | + |
| 56 | + self.queue.async { |
| 57 | + let sync = DispatchGroup() |
| 58 | + var results = [URL: Result<HTTPClientResponse, Error>]() |
| 59 | + let resultsLock = Lock() |
| 60 | + |
| 61 | + // get the main data |
| 62 | + sync.enter() |
| 63 | + let options = self.makeRequestOptions(validResponseCodes: [200]) |
| 64 | + httpClient.get(metadataURL, options: options) { result in |
| 65 | + defer { sync.leave() } |
| 66 | + resultsLock.withLock { |
| 67 | + results[metadataURL] = result |
| 68 | + } |
| 69 | + // if successful, fan out multiple API calls |
| 70 | + if case .success = result { |
| 71 | + [tagsURL, contributorsURL, readmeURL].forEach { url in |
| 72 | + sync.enter() |
| 73 | + httpClient.get(url, options: options) { result in |
| 74 | + defer { sync.leave() } |
| 75 | + resultsLock.withLock { |
| 76 | + results[url] = result |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + sync.wait() |
| 84 | + |
| 85 | + // process results |
| 86 | + |
| 87 | + do { |
| 88 | + // check for main request error state |
| 89 | + switch results[metadataURL] { |
| 90 | + case .none: |
| 91 | + throw Errors.invalidResponse(metadataURL) |
| 92 | + case .some(.failure(let error)) where error as? HTTPClientError == .badResponseStatusCode(404): |
| 93 | + throw NotFoundError("\(baseURL)") |
| 94 | + case .some(.failure(let error)): |
| 95 | + throw error |
| 96 | + case .some(.success(let metadataResponse)): |
| 97 | + guard let metadata = try metadataResponse.decodeBody(GetRepositoryResponse.self, using: self.decoder) else { |
| 98 | + throw Errors.invalidResponse(metadataURL) |
| 99 | + } |
| 100 | + let tags = try results[tagsURL]?.success?.decodeBody([Tag].self, using: self.decoder) ?? [] |
| 101 | + let contributors = try results[contributorsURL]?.success?.decodeBody([Contributor].self, using: self.decoder) |
| 102 | + let readme = try results[readmeURL]?.success?.decodeBody(Readme.self, using: self.decoder) |
| 103 | + |
| 104 | + callback(.success(.init( |
| 105 | + description: metadata.description, |
| 106 | + versions: tags.compactMap { TSCUtility.Version(string: $0.name) }, |
| 107 | + watchersCount: metadata.watchersCount, |
| 108 | + readmeURL: readme?.downloadURL, |
| 109 | + authors: contributors?.map { .init(username: $0.login, url: $0.url, service: .init(name: "GitHub")) }, |
| 110 | + processedAt: Date() |
| 111 | + ))) |
| 112 | + } |
| 113 | + } catch { |
| 114 | + return callback(.failure(error)) |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + internal func apiURL(_ url: String) -> Foundation.URL? { |
| 120 | + do { |
| 121 | + let regex = try NSRegularExpression(pattern: "([^/@]+)[:/]([^:/]+)/([^/]+)\\.git$", options: .caseInsensitive) |
| 122 | + if let match = regex.firstMatch(in: url, options: [], range: NSRange(location: 0, length: url.count)) { |
| 123 | + if let hostRange = Range(match.range(at: 1), in: url), |
| 124 | + let ownerRange = Range(match.range(at: 2), in: url), |
| 125 | + let repoRange = Range(match.range(at: 3), in: url) { |
| 126 | + let host = String(url[hostRange]) |
| 127 | + let owner = String(url[ownerRange]) |
| 128 | + let repo = String(url[repoRange]) |
| 129 | + |
| 130 | + return URL(string: "https://api.\(host)/\(owner)/\(repo)") |
| 131 | + } |
| 132 | + } |
| 133 | + return nil |
| 134 | + } catch { |
| 135 | + return nil |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private func makeRequestOptions(validResponseCodes: [Int]) -> HTTPClientRequest.Options { |
| 140 | + var options = HTTPClientRequest.Options() |
| 141 | + options.addUserAgent = true |
| 142 | + options.validResponseCodes = validResponseCodes |
| 143 | + if defaultHttpClient { |
| 144 | + // TODO: make these defaults configurable? |
| 145 | + options.timeout = httpClient.configuration.requestTimeout ?? .seconds(1) |
| 146 | + options.retryStrategy = httpClient.configuration.retryStrategy ?? .exponentialBackoff(maxAttempts: 3, baseDelay: .milliseconds(50)) |
| 147 | + options.circuitBreakerStrategy = httpClient.configuration.circuitBreakerStrategy ?? .hostErrors(maxErrors: 5, age: .seconds(5)) |
| 148 | + } else { |
| 149 | + options.timeout = httpClient.configuration.requestTimeout |
| 150 | + options.retryStrategy = httpClient.configuration.retryStrategy |
| 151 | + options.circuitBreakerStrategy = httpClient.configuration.circuitBreakerStrategy |
| 152 | + } |
| 153 | + return options |
| 154 | + } |
| 155 | + |
| 156 | + enum Errors: Error, Equatable { |
| 157 | + case unprocessable(PackageReference) |
| 158 | + case invalidResponse(URL) |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +extension GitHubPackageMetadataProvider { |
| 163 | + fileprivate struct GetRepositoryResponse: Codable { |
| 164 | + let name: String |
| 165 | + let fullName: String |
| 166 | + let description: String? |
| 167 | + let isPrivate: Bool |
| 168 | + let isFork: Bool |
| 169 | + let defaultBranch: String |
| 170 | + let updatedAt: Date |
| 171 | + let sshURL: Foundation.URL |
| 172 | + let cloneURL: Foundation.URL |
| 173 | + let tagsURL: Foundation.URL |
| 174 | + let contributorsURL: Foundation.URL |
| 175 | + let language: String? |
| 176 | + let license: License? |
| 177 | + let watchersCount: Int |
| 178 | + let forksCount: Int |
| 179 | + |
| 180 | + private enum CodingKeys: String, CodingKey { |
| 181 | + case name |
| 182 | + case fullName = "full_name" |
| 183 | + case description |
| 184 | + case isPrivate = "private" |
| 185 | + case isFork = "fork" |
| 186 | + case defaultBranch = "default_branch" |
| 187 | + case updatedAt = "updated_at" |
| 188 | + case sshURL = "ssh_url" |
| 189 | + case cloneURL = "clone_url" |
| 190 | + case tagsURL = "tags_url" |
| 191 | + case contributorsURL = "contributors_url" |
| 192 | + case language |
| 193 | + case license |
| 194 | + case watchersCount = "watchers_count" |
| 195 | + case forksCount = "forks_count" |
| 196 | + } |
| 197 | + } |
| 198 | +} |
| 199 | + |
| 200 | +extension GitHubPackageMetadataProvider { |
| 201 | + fileprivate struct License: Codable { |
| 202 | + let key: String |
| 203 | + let name: String |
| 204 | + } |
| 205 | + |
| 206 | + fileprivate struct Tag: Codable { |
| 207 | + let name: String |
| 208 | + let tarballURL: Foundation.URL |
| 209 | + let commit: Commit |
| 210 | + |
| 211 | + private enum CodingKeys: String, CodingKey { |
| 212 | + case name |
| 213 | + case tarballURL = "tarball_url" |
| 214 | + case commit |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + fileprivate struct Commit: Codable { |
| 219 | + let sha: String |
| 220 | + let url: Foundation.URL |
| 221 | + } |
| 222 | + |
| 223 | + fileprivate struct Contributor: Codable { |
| 224 | + let login: String |
| 225 | + let url: Foundation.URL |
| 226 | + let contributions: Int |
| 227 | + } |
| 228 | + |
| 229 | + fileprivate struct Readme: Codable { |
| 230 | + let url: Foundation.URL |
| 231 | + let htmlURL: Foundation.URL |
| 232 | + let downloadURL: Foundation.URL |
| 233 | + |
| 234 | + private enum CodingKeys: String, CodingKey { |
| 235 | + case url |
| 236 | + case htmlURL = "html_url" |
| 237 | + case downloadURL = "download_url" |
| 238 | + } |
| 239 | + } |
| 240 | +} |
0 commit comments