Skip to content

Commit

Permalink
asyncBoot will no longer try booting server again if it is already bo…
Browse files Browse the repository at this point in the history
…oted (#3195)
  • Loading branch information
RussBaz committed May 21, 2024
1 parent 50c6196 commit 2c185b7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
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

0 comments on commit 2c185b7

Please sign in to comment.