Skip to content

Commit 1e62d3f

Browse files
Merge pull request #3525 from SwiftPackageIndex/issue-3469-dependency-transition-8
Issue 3469 dependency transition 8
2 parents 741c054 + 0609503 commit 1e62d3f

16 files changed

+321
-201
lines changed

Sources/App/Core/AppEnvironment.swift

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ import FoundationNetworking
2323

2424

2525
struct AppEnvironment: Sendable {
26-
var currentReferenceCache: @Sendable () -> CurrentReferenceCache?
27-
var dbId: @Sendable () -> String?
2826
var fetchDocumentation: @Sendable (_ client: Client, _ url: URI) async throws -> ClientResponse
2927
var fetchHTTPStatusCode: @Sendable (_ url: String) async throws -> HTTPStatus
3028
var fetchLicense: @Sendable (_ client: Client, _ owner: String, _ repository: String) async -> Github.License?
@@ -87,8 +85,6 @@ extension AppEnvironment {
8785
nonisolated(unsafe) static var logger: Logger!
8886

8987
static let live = AppEnvironment(
90-
currentReferenceCache: { .live },
91-
dbId: { Environment.get("DATABASE_ID") },
9288
fetchDocumentation: { client, url in try await client.get(url) },
9389
fetchHTTPStatusCode: { url in try await Networking.fetchHTTPStatusCode(url) },
9490
fetchLicense: { client, owner, repo in await Github.fetchLicense(client:client, owner: owner, repository: repo) },

Sources/App/Core/Dependencies/EnvironmentClient.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ struct EnvironmentClient {
3939
var collectionSigningCertificateChain: @Sendable () -> [URL] = { XCTFail("collectionSigningCertificateChain"); return [] }
4040
var collectionSigningPrivateKey: @Sendable () -> Data?
4141
var current: @Sendable () -> Environment = { XCTFail("current"); return .development }
42+
var currentReferenceCache: @Sendable () -> CurrentReferenceCache?
43+
var dbId: @Sendable () -> String?
4244
var mastodonCredentials: @Sendable () -> Mastodon.Credentials?
4345
var mastodonPost: @Sendable (_ client: Client, _ post: String) async throws -> Void
4446
var random: @Sendable (_ range: ClosedRange<Double>) -> Double = { XCTFail("random"); return Double.random(in: $0) }
@@ -91,6 +93,8 @@ extension EnvironmentClient: DependencyKey {
9193
Environment.get("COLLECTION_SIGNING_PRIVATE_KEY").map { Data($0.utf8) }
9294
},
9395
current: { (try? Environment.detect()) ?? .development },
96+
currentReferenceCache: { .live },
97+
dbId: { Environment.get("DATABASE_ID") },
9498
mastodonCredentials: {
9599
Environment.get("MASTODON_ACCESS_TOKEN")
96100
.map(Mastodon.Credentials.init(accessToken:))

Sources/App/Views/PublicPage.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class PublicPage {
3434
return HTML(
3535
.lang(.english),
3636
.comment("Version: \(environment.appVersion())"),
37-
.comment("DB Id: \(Current.dbId())"),
37+
.comment("DB Id: \(environment.dbId())"),
3838
head(),
3939
body()
4040
)

Sources/App/routes+documentation.swift

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
15+
import Dependencies
1616
import Vapor
1717

1818

@@ -124,7 +124,7 @@ private extension Parameters {
124124
}
125125
}
126126
}
127-
127+
128128

129129
struct DocRedirect {
130130
var owner: String
@@ -152,15 +152,15 @@ extension Request {
152152
target = try await DocumentationTarget.query(on: db, owner: owner, repository: repository,
153153
docVersion: .reference(ref))
154154
}
155-
155+
156156
case .none:
157157
target = try await DocumentationTarget.query(on: db, owner: owner, repository: repository)
158158
}
159159
guard let target else { throw Abort(.notFound) }
160160

161161
return .init(owner: owner, repository: repository, target: target, path: path)
162162
}
163-
163+
164164
func getDocRoute(fragment: DocRoute.Fragment) async throws -> DocRoute {
165165
guard let owner = parameters.get("owner"),
166166
let repository = parameters.get("repository"),
@@ -170,16 +170,18 @@ extension Request {
170170
if fragment.requiresArchive && archive == nil { throw Abort(.badRequest) }
171171
let pathElements = parameters.pathElements(for: fragment, archive: archive)
172172

173+
@Dependency(\.environment) var environment
174+
173175
let docVersion = try await { () -> DocVersion in
174176
if reference == String.current {
175-
if let ref = Current.currentReferenceCache()?[owner: owner, repository: repository] {
177+
if let ref = environment.currentReferenceCache()?[owner: owner, repository: repository] {
176178
return .current(referencing: ref)
177179
}
178180

179181
guard let params = try await DocumentationTarget.query(on: db, owner: owner, repository: repository)?.internal
180182
else { throw Abort(.notFound) }
181183

182-
Current.currentReferenceCache()?[owner: owner, repository: repository] = "\(params.docVersion)"
184+
environment.currentReferenceCache()?[owner: owner, repository: repository] = "\(params.docVersion)"
183185
return .current(referencing: "\(params.docVersion)")
184186
} else {
185187
return .reference(reference)

Tests/AppTests/ApiTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ class ApiTests: AppTestCase {
112112
func test_search_unauthenticated() async throws {
113113
try await withDependencies {
114114
$0.environment.apiSigningKey = { "secret" }
115+
$0.environment.dbId = { nil }
115116
} operation: {
116117
// MUT
117118
try await app.test(.GET, "api/search?query=test",
@@ -344,6 +345,7 @@ class ApiTests: AppTestCase {
344345
// Ensure unauthenticated access raises a 401
345346
try await withDependencies {
346347
$0.environment.builderToken = { "secr3t" }
348+
$0.environment.dbId = { nil }
347349
} operation: {
348350
// setup
349351
let p = try await savePackage(on: app.db, "1")
@@ -640,6 +642,7 @@ class ApiTests: AppTestCase {
640642
func test_post_docReport_non_existing_build() async throws {
641643
try await withDependencies {
642644
$0.environment.builderToken = { "secr3t" }
645+
$0.environment.dbId = { nil }
643646
} operation: {
644647
// setup
645648
let nonExistingBuildId = UUID()
@@ -665,6 +668,7 @@ class ApiTests: AppTestCase {
665668
func test_post_docReport_unauthenticated() async throws {
666669
try await withDependencies {
667670
$0.environment.builderToken = { "secr3t" }
671+
$0.environment.dbId = { nil }
668672
} operation: {
669673
// setup
670674
let p = try await savePackage(on: app.db, "1")
@@ -978,6 +982,7 @@ class ApiTests: AppTestCase {
978982
func test_package_collections_packageURLs_limit() throws {
979983
try withDependencies {
980984
$0.environment.apiSigningKey = { "secret" }
985+
$0.environment.dbId = { nil }
981986
} operation: {
982987
let dto = API.PostPackageCollectionDTO(
983988
// request 21 urls - this should raise a 400
@@ -999,6 +1004,7 @@ class ApiTests: AppTestCase {
9991004
func test_package_collections_unauthorized() throws {
10001005
try withDependencies {
10011006
$0.environment.apiSigningKey = { "secret" }
1007+
$0.environment.dbId = { nil }
10021008
} operation: {
10031009
// MUT - happy path
10041010
let body: ByteBuffer = .init(string: """
@@ -1042,6 +1048,7 @@ class ApiTests: AppTestCase {
10421048
func test_packages_get() async throws {
10431049
try await withDependencies {
10441050
$0.environment.apiSigningKey = { "secret" }
1051+
$0.environment.dbId = { nil }
10451052
} operation: {
10461053
let owner = "owner"
10471054
let repo = "repo"

Tests/AppTests/AuthorControllerTests.swift

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
import XCTest
16+
1517
@testable import App
1618

19+
import Dependencies
1720
import Vapor
18-
import XCTest
21+
1922

2023
class AuthorControllerTests: AppTestCase {
2124

@@ -66,27 +69,33 @@ class AuthorControllerTests: AppTestCase {
6669
}
6770

6871
func test_show_owner() async throws {
69-
// setup
70-
let p = try await savePackage(on: app.db, "1")
71-
try await Repository(package: p, owner: "owner").save(on: app.db)
72-
try await Version(package: p, latest: .defaultBranch).save(on: app.db)
72+
try await withDependencies {
73+
$0.environment.dbId = { nil }
74+
} operation: {
75+
let p = try await savePackage(on: app.db, "1")
76+
try await Repository(package: p, owner: "owner").save(on: app.db)
77+
try await Version(package: p, latest: .defaultBranch).save(on: app.db)
7378

74-
// MUT
75-
try await app.test(.GET, "/owner", afterResponse: { response async in
76-
XCTAssertEqual(response.status, .ok)
77-
})
79+
// MUT
80+
try await app.test(.GET, "/owner", afterResponse: { response async in
81+
XCTAssertEqual(response.status, .ok)
82+
})
83+
}
7884
}
7985

8086
func test_show_owner_empty() async throws {
81-
// setup
82-
let p = try await savePackage(on: app.db, "1")
83-
try await Repository(package: p, owner: "owner").save(on: app.db)
84-
try await Version(package: p, latest: .defaultBranch).save(on: app.db)
87+
try await withDependencies {
88+
$0.environment.dbId = { nil }
89+
} operation: {
90+
let p = try await savePackage(on: app.db, "1")
91+
try await Repository(package: p, owner: "owner").save(on: app.db)
92+
try await Version(package: p, latest: .defaultBranch).save(on: app.db)
8593

86-
// MUT
87-
try await app.test(.GET, "/fake-owner", afterResponse: { response async in
88-
XCTAssertEqual(response.status, .notFound)
89-
})
94+
// MUT
95+
try await app.test(.GET, "/fake-owner", afterResponse: { response async in
96+
XCTAssertEqual(response.status, .notFound)
97+
})
98+
}
9099
}
91100

92101
}

Tests/AppTests/BuildMonitorControllerTests.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class BuildMonitorControllerTests: AppTestCase {
2525
func test_show_owner() async throws {
2626
try await withDependencies {
2727
$0.date.now = .now
28+
$0.environment.dbId = { nil }
2829
} operation: {
2930
let package = try await savePackage(on: app.db, "https://github.com/daveverwer/LeftPad")
3031
let version = try Version(package: package)

Tests/AppTests/ErrorMiddlewareTests.swift

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
import XCTest
16+
1517
@testable import App
1618

19+
import Dependencies
1720
import Vapor
18-
import XCTest
1921

2022

2123
class ErrorMiddlewareTests: AppTestCase {
@@ -39,24 +41,32 @@ class ErrorMiddlewareTests: AppTestCase {
3941

4042
func test_html_error() throws {
4143
// Test to ensure errors are converted to html error pages via the ErrorMiddleware
42-
try app.test(.GET, "404", afterResponse: { response in
43-
XCTAssertEqual(response.content.contentType, .html)
44-
XCTAssert(response.body.asString().contains("404 - Not Found"))
45-
})
44+
try withDependencies {
45+
$0.environment.dbId = { nil }
46+
} operation: {
47+
try app.test(.GET, "404", afterResponse: { response in
48+
XCTAssertEqual(response.content.contentType, .html)
49+
XCTAssert(response.body.asString().contains("404 - Not Found"))
50+
})
51+
}
4652
}
4753

4854
func test_status_code() throws {
4955
// Ensure we're still reporting the actual status code even when serving html pages
5056
// (Status is important for Google ranking, see
5157
// https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/issues/323)
52-
try app.test(.GET, "404", afterResponse: { response in
53-
XCTAssertEqual(response.status, .notFound)
54-
XCTAssertEqual(response.content.contentType, .html)
55-
})
56-
try app.test(.GET, "500", afterResponse: { response in
57-
XCTAssertEqual(response.status, .internalServerError)
58-
XCTAssertEqual(response.content.contentType, .html)
59-
})
58+
try withDependencies {
59+
$0.environment.dbId = { nil }
60+
} operation: {
61+
try app.test(.GET, "404", afterResponse: { response in
62+
XCTAssertEqual(response.status, .notFound)
63+
XCTAssertEqual(response.content.contentType, .html)
64+
})
65+
try app.test(.GET, "500", afterResponse: { response in
66+
XCTAssertEqual(response.status, .internalServerError)
67+
XCTAssertEqual(response.content.contentType, .html)
68+
})
69+
}
6070
}
6171

6272
}

Tests/AppTests/KeywordControllerTests.swift

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
import XCTest
16+
1517
@testable import App
1618

19+
import Dependencies
1720
import Vapor
18-
import XCTest
21+
1922

2023
class KeywordControllerTests: AppTestCase {
2124

@@ -102,25 +105,32 @@ class KeywordControllerTests: AppTestCase {
102105
}
103106

104107
func test_show_keyword() async throws {
105-
// setup
106-
do {
107-
let p = try await savePackage(on: app.db, "1")
108-
try await Repository(package: p,
109-
keywords: ["foo"],
110-
name: "1",
111-
owner: "owner").save(on: app.db)
112-
try await Version(package: p, latest: .defaultBranch).save(on: app.db)
113-
}
114-
// MUT
115-
try await app.test(.GET, "/keywords/foo") { req async in
116-
// validate
117-
XCTAssertEqual(req.status, .ok)
108+
try await withDependencies {
109+
$0.environment.dbId = { nil }
110+
} operation: {
111+
do {
112+
let p = try await savePackage(on: app.db, "1")
113+
try await Repository(package: p,
114+
keywords: ["foo"],
115+
name: "1",
116+
owner: "owner").save(on: app.db)
117+
try await Version(package: p, latest: .defaultBranch).save(on: app.db)
118+
}
119+
// MUT
120+
try await app.test(.GET, "/keywords/foo") { req async in
121+
// validate
122+
XCTAssertEqual(req.status, .ok)
123+
}
118124
}
119125
}
120126

121127
func test_not_found() throws {
122-
try app.test(.GET, "/keywords/baz") {
123-
XCTAssertEqual($0.status, .notFound)
128+
try withDependencies {
129+
$0.environment.dbId = { nil }
130+
} operation: {
131+
try app.test(.GET, "/keywords/baz") {
132+
XCTAssertEqual($0.status, .notFound)
133+
}
124134
}
125135
}
126136

Tests/AppTests/Mocks/AppEnvironment+mock.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@ import Vapor
2222
extension AppEnvironment {
2323
static func mock(eventLoop: EventLoop) -> Self {
2424
.init(
25-
currentReferenceCache: { nil },
26-
dbId: { "db-id" },
2725
fetchDocumentation: { _, _ in .init(status: .ok) },
2826
fetchHTTPStatusCode: { _ in .ok },
2927
fetchLicense: { _, _, _ in .init(htmlUrl: "https://github.com/foo/bar/blob/main/LICENSE") },

0 commit comments

Comments
 (0)