Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Sources/App/Commands/Alerting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,10 @@ enum Alerting {
}

func run(using context: CommandContext, signature: Signature) async throws {
prepareDependencies {
$0.logger = Logger(component: "alerting")
}
@Dependency(\.logger) var logger
logger.set(to: Logger(component: "alerting"))

logger.info("Running alerting...")

Expand Down
9 changes: 6 additions & 3 deletions Sources/App/Commands/Analyze.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,13 @@ enum Analyze {
var help: String { "Run package analysis (fetching git repository and inspecting content)" }

func run(using context: CommandContext, signature: SPICommand.Signature) async throws {
prepareDependencies {
$0.logger = Logger(component: "analyze")
}
@Dependency(\.logger) var logger

let client = context.application.client
let db = context.application.db
@Dependency(\.logger) var logger
logger.set(to: Logger(component: "analyze"))

Analyze.resetMetrics()

Expand Down Expand Up @@ -251,7 +254,7 @@ extension Analyze {
attributes: nil)
} catch {
let error = AppError.genericError(nil, "Failed to create checkouts directory: \(error.localizedDescription)")
logger.logger.report(error: error)
logger.report(error: error)
}
}

Expand Down
7 changes: 5 additions & 2 deletions Sources/App/Commands/Ingestion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,13 @@ enum Ingestion {
var help: String { "Run package ingestion (fetching repository metadata)" }

func run(using context: CommandContext, signature: SPICommand.Signature) async {
prepareDependencies {
$0.logger = Logger(component: "ingest")
}
@Dependency(\.logger) var logger

let client = context.application.client
let db = context.application.db
@Dependency(\.logger) var logger
logger.set(to: Logger(component: "ingest"))

Self.resetMetrics()

Expand Down
10 changes: 6 additions & 4 deletions Sources/App/Commands/ReAnalyzeVersions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,16 @@ enum ReAnalyzeVersions {
var help: String { "Run version re-analysis" }

func run(using context: CommandContext, signature: Signature) async throws {
let limit = signature.limit ?? defaultLimit
prepareDependencies {
$0.logger = Logger(component: "re-analyze-versions")
}
@Dependency(\.logger) var logger
@Dependency(\.date.now) var now

let limit = signature.limit ?? defaultLimit
let client = context.application.client
let db = context.application.db
@Dependency(\.logger) var logger
logger.set(to: Logger(component: "re-analyze-versions"))

@Dependency(\.date.now) var now
if let id = signature.packageId {
logger.info("Re-analyzing versions (id: \(id)) ...")
do {
Expand Down
10 changes: 5 additions & 5 deletions Sources/App/Commands/Reconcile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,23 @@ struct ReconcileCommand: AsyncCommand {
var help: String { "Reconcile package list with server" }

func run(using context: CommandContext, signature: Signature) async throws {
prepareDependencies{
$0.logger = Logger(component: "reconcile")
}
@Dependency(\.logger) var logger
logger.set(to: Logger(component: "reconcile"))

logger.info("Reconciling...")

do {
try await reconcile(client: context.application.client,
database: context.application.db)
try await reconcile(client: context.application.client, database: context.application.db)
} catch {
logger.error("\(error)")
}

logger.info("done.")

do {
try await AppMetrics.push(client: context.application.client,
jobName: "reconcile")
try await AppMetrics.push(client: context.application.client, jobName: "reconcile")
} catch {
logger.warning("\(error)")
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/App/Commands/TriggerBuilds.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ struct TriggerBuildsCommand: AsyncCommand {
}

func run(using context: CommandContext, signature: Signature) async throws {
prepareDependencies {
$0.logger = Logger(component: "trigger-builds")
}
@Dependency(\.logger) var logger
logger.set(to: Logger(component: "trigger-builds"))

Self.resetMetrics()

Expand Down
69 changes: 18 additions & 51 deletions Sources/App/Core/Dependencies/LoggerClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,72 +13,39 @@
// limitations under the License.

import Dependencies
import DependenciesMacros
import IssueReporting
import Logging
import Synchronization


@DependencyClient
struct LoggerClient {
var log: @Sendable (_ level: Logging.Logger.Level, Logging.Logger.Message) -> Void
var set: @Sendable (_ to: Logging.Logger) -> Void
}


extension LoggerClient {
func critical(_ message: Logging.Logger.Message) { log(.critical, message) }
func debug(_ message: Logging.Logger.Message) { log(.debug, message) }
func error(_ message: Logging.Logger.Message) { log(.error, message) }
func info(_ message: Logging.Logger.Message) { log(.info, message) }
func warning(_ message: Logging.Logger.Message) { log(.warning, message) }
func trace(_ message: Logging.Logger.Message) { log(.trace, message) }
func report(error: Error, file: String = #fileID, function: String = #function, line: UInt = #line) {
logger.report(error: error, file: file, function: function, line: line)
private enum LoggerClient: DependencyKey {
static var liveValue: Logger {
reportIssue("The default logger is being used. Override this dependency in the entry point of your app.")
return Logging.Logger(label: "default")
}
var logger: Logging.Logger { Self._logger.withLock { $0 } }
}


#if DEBUG
extension LoggerClient {
func set(to handler: LogHandler?) {
if let handler {
let logger = Logger(label: "test", factory: { _ in handler })
set(to: logger)
}
}

static var noop: Self {
.init(log: { _, _ in }, set: { _ in })
extension LoggerClient: TestDependencyKey {
static var testValue: Logger {
unimplemented("testValue"); return .init(label: "test")
}
}
#endif


extension LoggerClient: DependencyKey {
static var liveValue: Self {
.init(
log: { level, message in
_logger.withLock { $0.log(level: level, message) }
},
set: { logger in
_logger.withLock { $0 = logger }
}
)
extension DependencyValues {
public var logger: Logger {
get { self[LoggerClient.self] }
set { self[LoggerClient.self] = newValue }
}

private static let _logger = Mutex(Logging.Logger(component: "default"))
}


extension LoggerClient: TestDependencyKey {
static var testValue: Self { liveValue }
}

#if DEBUG
extension Logger {
static var noop: Self { .init(label: "noop") { _ in SwiftLogNoOpLogHandler() } }

extension DependencyValues {
var logger: LoggerClient {
get { self[LoggerClient.self] }
set { self[LoggerClient.self] = newValue }
static func testLogger(_ handler: LogHandler) -> Self {
.init(label: "test", factory: { _ in handler })
}
}
#endif
2 changes: 1 addition & 1 deletion Sources/App/Core/Dependencies/ShellClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ extension ShellClient: DependencyKey {
run: { command, path in
@Dependency(\.logger) var logger
do {
let res = try await ShellOut.shellOut(to: command, at: path, logger: logger.logger)
let res = try await ShellOut.shellOut(to: command, at: path, logger: logger)
if !res.stderr.isEmpty {
logger.warning("stderr: \(res.stderr)")
}
Expand Down
2 changes: 0 additions & 2 deletions Sources/App/configure.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ public func configure(_ app: Application, databasePort: Int? = nil) async throws
let _ = Bundle(path: "/Applications/InjectionIII.app/Contents/Resources/macOSInjection.bundle")?.load()
#endif

@Dependency(\.logger) var logger
app.logger.component = "server"
logger.set(to: app.logger)

// It will be tempting to uncomment/re-add these lines in the future. We should not enable
// server-side compression as long as we pass requests through Cloudflare, which compresses
Expand Down
8 changes: 4 additions & 4 deletions Tests/AppTests/AnalyzeErrorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ extension AllTests.AnalyzeErrorTests {
try await withDependencies {
$0.environment.loadSPIManifest = { _ in nil }
$0.fileManager.fileExists = { @Sendable _ in true }
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
$0.shell.run = { @Sendable cmd, path in
switch cmd {
case _ where cmd.description.contains("git clone https://github.com/foo/1"):
Expand Down Expand Up @@ -100,7 +100,7 @@ extension AllTests.AnalyzeErrorTests {
try await withDependencies {
$0.environment.loadSPIManifest = { _ in nil }
$0.fileManager.fileExists = { @Sendable _ in true }
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
} operation: {
// setup
let pkg = try await Package.find(badPackageID, on: app.db).unwrap()
Expand Down Expand Up @@ -130,7 +130,7 @@ extension AllTests.AnalyzeErrorTests {
try await withDependencies {
$0.environment.loadSPIManifest = { _ in nil }
$0.fileManager.fileExists = { @Sendable _ in true }
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
$0.shell.run = { @Sendable cmd, path in
switch cmd {
case .gitCheckout(branch: "main", quiet: true) where path.hasSuffix("foo-1"):
Expand Down Expand Up @@ -166,7 +166,7 @@ extension AllTests.AnalyzeErrorTests {
}
return true
}
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
} operation: {
// MUT
try await Analyze.analyze(client: app.client,
Expand Down
9 changes: 8 additions & 1 deletion Tests/AppTests/AnalyzerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,7 @@ extension AllTests.AnalyzerTests {
// points to the correct version of Xcode!
try await withDependencies {
$0.fileManager.fileExists = FileManagerClient.liveValue.fileExists(atPath:)
$0.logger = .noop
$0.shell = .liveValue
} operation: {
// setup
Expand All @@ -1080,6 +1081,7 @@ extension AllTests.AnalyzerTests {
// See also https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/issues/1441
try await withDependencies {
$0.fileManager.fileExists = FileManagerClient.liveValue.fileExists(atPath:)
$0.logger = .noop
$0.shell = .liveValue
} operation: {
// setup
Expand All @@ -1100,6 +1102,7 @@ extension AllTests.AnalyzerTests {
// points to the correct version of Xcode!
try await withDependencies {
$0.fileManager.fileExists = FileManagerClient.liveValue.fileExists(atPath:)
$0.logger = .noop
$0.shell = .liveValue
} operation: {
// setup
Expand All @@ -1126,6 +1129,9 @@ extension AllTests.AnalyzerTests {
// NB: If this test fails on macOS make sure xcode-select -p
// points to the correct version of Xcode!
// setup
try await withDependencies {
$0.logger = .noop
} operation: {
try await withTempDir { @Sendable tempDir in
let fixture = fixturesDirectory()
.appendingPathComponent("5.9-Package-swift").path
Expand All @@ -1149,6 +1155,7 @@ extension AllTests.AnalyzerTests {
#endif
}
}
}

@Test func issue_577() async throws {
// Duplicate "latest release" versions
Expand Down Expand Up @@ -1456,7 +1463,7 @@ extension AllTests.AnalyzerTests {
1\tPerson 2
"""
}
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
$0.shell.run = { @Sendable _, _ in return "" }
} operation: {
let pkgId = UUID()
Expand Down
4 changes: 2 additions & 2 deletions Tests/AppTests/ErrorReportingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ extension AllTests.ErrorReportingTests {
try await withDependencies {
$0.date.now = .now
$0.github.fetchMetadata = { @Sendable _, _ throws(Github.Error) in throw Github.Error.invalidURL("1") }
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
} operation: {
// MUT
try await Ingestion.ingest(client: app.client, database: app.db, mode: .limit(10))
Expand All @@ -63,7 +63,7 @@ extension AllTests.ErrorReportingTests {
let capturingLogger = CapturingLogger()
try await withDependencies {
$0.fileManager.fileExists = { @Sendable _ in true }
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
$0.shell.run = { @Sendable cmd, _ in
if cmd.description == "git tag" { return "1.0.0" }
// returning a blank string will cause an exception when trying to
Expand Down
5 changes: 4 additions & 1 deletion Tests/AppTests/GithubTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ extension AllTests.GithubTests {
await withDependencies {
$0.github.token = { "secr3t" }
$0.httpClient.post = { @Sendable _, _, _ in .badRequest }
$0.logger = .noop
} operation: {
do {
_ = try await Github.fetchMetadata(owner: "alamofire",
Expand Down Expand Up @@ -219,6 +220,7 @@ extension AllTests.GithubTests {
await withDependencies {
$0.github.token = { "secr3t" }
$0.httpClient.post = { @Sendable _, _, _ in .tooManyRequests }
$0.logger = .noop
} operation: {
// MUT
do {
Expand Down Expand Up @@ -273,7 +275,7 @@ extension AllTests.GithubTests {
$0.httpClient.post = { @Sendable _, _, _ in
.init(status: .forbidden, headers: ["X-RateLimit-Remaining": "0"])
}
$0.logger.set(to: capturingLogger)
$0.logger = .testLogger(capturingLogger)
} operation: {
// MUT
do {
Expand Down Expand Up @@ -367,6 +369,7 @@ extension AllTests.GithubTests {
await withDependencies {
$0.github.token = { "secr3t" }
$0.httpClient.get = { @Sendable _, headers in .notFound }
$0.logger = .noop
} operation: {
// MUT
let res = await Github.fetchReadme(owner: "foo", repository: "bar")
Expand Down
2 changes: 2 additions & 0 deletions Tests/AppTests/GitlabBuilderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ extension AllTests.GitlabBuilderTests {
)
return try .created(jsonEncode: Gitlab.Builder.Response(webUrl: "http://web_url"))
}
$0.logger = .noop
} operation: {
// MUT
_ = try await Gitlab.Builder.triggerBuild(buildId: buildId,
Expand Down Expand Up @@ -112,6 +113,7 @@ extension AllTests.GitlabBuilderTests {
#expect(swiftVersion == "6.0")
return try .created(jsonEncode: Gitlab.Builder.Response(webUrl: "http://web_url"))
}
$0.logger = .noop
} operation: {
// MUT
_ = try await Gitlab.Builder.triggerBuild(buildId: .id0,
Expand Down
Loading
Loading