Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

asyncBoot will no longer try booting server again if it is already booted #3195

Merged
merged 4 commits into from
May 21, 2024
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
13 changes: 8 additions & 5 deletions Sources/Vapor/Application.swift
Original file line number Diff line number Diff line change
Expand Up @@ -247,12 +247,15 @@ public final class Application: Sendable {

/// Called when the applications starts up, will trigger the lifecycle handlers. The asynchronous version of ``boot()``
public func asyncBoot() async throws {
self.isBooted.withLockedValue { booted in
guard !booted else {
return
}
booted = true
/// Skip the boot process if already booted
guard !self.isBooted.withLockedValue({
var result = true
swap(&$0, &result)
return result
}) else {
return
}

for handler in self.lifecycle.handlers {
try await handler.willBootAsync(self)
}
Expand Down
41 changes: 41 additions & 0 deletions Tests/VaporTests/ApplicationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,47 @@ final class ApplicationTests: XCTestCase {
XCTAssertEqual(foo.didBootAsyncFlag.withLockedValue({ $0 }), true)
XCTAssertEqual(foo.shutdownAsyncFlag.withLockedValue({ $0 }), true)
}

func testBootDoesNotTriggerLifecycleHandlerMultipleTimes() throws {
let app = Application(.testing)
defer { app.shutdown() }

final class Handler: LifecycleHandler, Sendable {
let bootCount = NIOLockedValueBox(0)
func willBoot(_ application: Application) throws {
bootCount.withLockedValue { $0 += 1 }
}
}

let handler = Handler()
app.lifecycle.use(handler)

try app.boot()
try app.boot()

XCTAssertEqual(handler.bootCount.withLockedValue({ $0 }), 1)
}

func testAsyncBootDoesNotTriggerLifecycleHandlerMultipleTimes() async throws {
let app = try await Application.make(.testing)

final class Handler: LifecycleHandler, Sendable {
let bootCount = NIOLockedValueBox(0)
func willBoot(_ application: Application) throws {
bootCount.withLockedValue { $0 += 1 }
}
}

let handler = Handler()
app.lifecycle.use(handler)

try await app.asyncBoot()
try await app.asyncBoot()

XCTAssertEqual(handler.bootCount.withLockedValue({ $0 }), 1)

try await app.asyncShutdown()
}

func testThrowDoesNotCrash() throws {
enum Static {
Expand Down
Loading