Compare commits

..

2 Commits

Author SHA1 Message Date
Christoph Hagen
e6132a38b3 Switch to new vapor main 2023-12-06 09:39:12 +01:00
Christoph Hagen
6aaa9cb458 Simplify async scheduler 2023-12-06 09:13:59 +01:00
8 changed files with 72 additions and 75 deletions

View File

@ -13,21 +13,15 @@ let package = Package(
.package(url: "https://github.com/christophhagen/ClairvoyantBinaryCodable", from: "0.3.0"), .package(url: "https://github.com/christophhagen/ClairvoyantBinaryCodable", from: "0.3.0"),
], ],
targets: [ targets: [
.target(name: "App", .executableTarget(
name: "App",
dependencies: [ dependencies: [
.product(name: "Vapor", package: "vapor"), .product(name: "Vapor", package: "vapor"),
.product(name: "Clairvoyant", package: "Clairvoyant"), .product(name: "Clairvoyant", package: "Clairvoyant"),
.product(name: "ClairvoyantVapor", package: "ClairvoyantVapor"), .product(name: "ClairvoyantVapor", package: "ClairvoyantVapor"),
.product(name: "ClairvoyantBinaryCodable", package: "ClairvoyantBinaryCodable"), .product(name: "ClairvoyantBinaryCodable", package: "ClairvoyantBinaryCodable"),
], ]
swiftSettings: [ )
// Enable better optimizations when building in Release configuration. Despite the use of
// the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release
// builds. See <https://github.com/swift-server/guides#building-for-production> for details.
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release))
]),
.executableTarget(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"]),
] ]
) )

View File

@ -3,32 +3,9 @@ import Clairvoyant
import Vapor import Vapor
import NIOCore import NIOCore
final class EventLoopScheduler { extension MultiThreadedEventLoopGroup: AsyncScheduler {
private let backgroundGroup: EventLoopGroup
init(numberOfThreads: Int = 2) {
backgroundGroup = MultiThreadedEventLoopGroup(numberOfThreads: numberOfThreads)
}
func next() -> EventLoop {
backgroundGroup.next()
}
func provider() -> NIOEventLoopGroupProvider {
return .shared(backgroundGroup)
}
func shutdown() {
backgroundGroup.shutdownGracefully { _ in
} public func schedule(asyncJob: @escaping @Sendable () async throws -> Void) {
} _ = any().makeFutureWithTask(asyncJob)
}
extension EventLoopScheduler: AsyncScheduler {
func schedule(asyncJob: @escaping @Sendable () async throws -> Void) {
_ = backgroundGroup.any().makeFutureWithTask(asyncJob)
} }
} }

View File

@ -7,17 +7,11 @@ import ClairvoyantBinaryCodable
private var provider: VaporMetricProvider! private var provider: VaporMetricProvider!
private var serverStatus: Metric<ServerStatus>! private var serverStatus: Metric<ServerStatus>!
private let asyncScheduler = EventLoopScheduler() private let asyncScheduler = MultiThreadedEventLoopGroup(numberOfThreads: 2)
private var server: CapServer! private var server: CapServer!
private func status(_ newStatus: ServerStatus) { func configure(_ app: Application) async throws {
asyncScheduler.schedule {
try await serverStatus.update(newStatus)
}
}
public func configure(_ app: Application) throws {
let resourceDirectory = URL(fileURLWithPath: app.directory.resourcesDirectory) let resourceDirectory = URL(fileURLWithPath: app.directory.resourcesDirectory)
let publicDirectory = app.directory.publicDirectory let publicDirectory = app.directory.publicDirectory
@ -32,7 +26,7 @@ public func configure(_ app: Application) throws {
serverStatus = Metric<ServerStatus>("caps.status", serverStatus = Metric<ServerStatus>("caps.status",
name: "Status", name: "Status",
description: "The general status of the service") description: "The general status of the service")
status(.initializing) try await serverStatus.update(.initializing)
app.http.server.configuration.port = config.port app.http.server.configuration.port = config.port
app.routes.defaultMaxBodySize = .init(stringLiteral: config.maxBodySize) app.routes.defaultMaxBodySize = .init(stringLiteral: config.maxBodySize)
@ -55,18 +49,29 @@ public func configure(_ app: Application) throws {
do { do {
try server.loadData() try server.loadData()
} catch { } catch {
status(.initializationFailure) try await serverStatus.update(.initializationFailure)
print("[\(df.string(from: Date()))] Server failed to start: \(error)") print("[\(df.string(from: Date()))] Server failed to start: \(error)")
return return
} }
if server.canResizeImages { if server.canResizeImages {
status(.nominal) try await serverStatus.update(.nominal)
} else { } else {
status(.reducedFunctionality) try await serverStatus.update(.reducedFunctionality)
} }
print("[\(df.string(from: Date()))] Server started (\(server.capCount) caps)") print("[\(df.string(from: Date()))] Server started (\(server.capCount) caps)")
} }
func shutdown() {
print("[\(df.string(from: Date()))] Server shutdown")
asyncScheduler.schedule {
do {
try await asyncScheduler.shutdownGracefully()
} catch {
print("Failed to shut down MultiThreadedEventLoopGroup: \(error)")
}
}
}
func log(_ message: String) { func log(_ message: String) {
guard let observer = MetricObserver.standard else { guard let observer = MetricObserver.standard else {
print(message) print(message)

View File

@ -0,0 +1,43 @@
import Vapor
import Dispatch
import Logging
/// This extension is temporary and can be removed once Vapor gets this support.
private extension Vapor.Application {
static let baseExecutionQueue = DispatchQueue(label: "vapor.codes.entrypoint")
func runFromAsyncMainEntrypoint() async throws {
try await withCheckedThrowingContinuation { continuation in
Vapor.Application.baseExecutionQueue.async { [self] in
do {
try self.run()
continuation.resume()
} catch {
continuation.resume(throwing: error)
}
}
}
}
}
@main
enum Entrypoint {
static func main() async throws {
var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env)
let app = Application(env)
defer {
shutdown()
app.shutdown()
}
do {
try await configure(app)
} catch {
app.logger.report(error: error)
throw error
}
try await app.runFromAsyncMainEntrypoint()
}
}

View File

@ -1,9 +0,0 @@
import App
import Vapor
var env = Environment.production
try LoggingSystem.bootstrap(from: &env)
let app = Application(env)
defer { app.shutdown() }
try configure(app)
try app.run()

View File

View File

@ -1,13 +0,0 @@
import App
import Dispatch
import XCTest
final class AppTests : XCTestCase {
func testNothing() throws {
XCTAssert(true)
}
static let allTests = [
("testNothing", testNothing),
]
}

View File