Skip to content

Commit 03c1510

Browse files
authored
feat: allow http status endpoint for monitoring (#44)
Add `/health` URL which just returns OK with `200` code for health check of the application. Partially avoiding #43
1 parent aefd3e5 commit 03c1510

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ Below, some compatible visualisation tools:
9090

9191
- pprof's [`/debug/pprof/profile` endpoint](https://pkg.go.dev/net/http/pprof)
9292
- Swift Profile Recorder's own `/sample` endpoint
93+
- `/health` endpoint for health checks (returns `200 OK`)
9394

9495
## Example profiles
9596

Sources/ProfileRecorderServer/Server.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,21 @@ public struct ProfileRecorderServer: Sendable {
585585
) != nil:
586586
// Native Swift Profile Recorder Sampling server
587587
sampleRequest = try JSONDecoder().decode(SampleRequest.self, from: request.body ?? ByteBuffer())
588+
case (.GET, .some(let decodedURI))
589+
where decodedURI.components.matches(prefix: [], oneOfPaths: [["health"]]) != nil:
590+
// Health check endpoint
591+
try await outbound.write(
592+
.head(
593+
HTTPResponseHead(
594+
version: .http1_1,
595+
status: .ok,
596+
headers: ["connection": "close"]
597+
)
598+
)
599+
)
600+
try await outbound.write(.body(ByteBuffer(string: "OK")))
601+
try await outbound.write(.end(nil))
602+
return
588603
case (let verb, .some(let decodedURI)):
589604
let extraRouteHandlers = self.state.withLockedValue { state in
590605
state.extraRouteHandlers

Tests/ProfileRecorderServerTests/ProfileRecorderServerTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,24 @@ final class ProfileRecorderServerTests: XCTestCase {
5858
}
5959
}
6060

61+
func testHealthEndpoint() async throws {
62+
let server = ProfileRecorderServer(
63+
configuration: try ProfileRecorderServerConfiguration.makeTCPListener(host: "127.0.0.1", port: 0)
64+
)
65+
try await server.withProfileRecordingServer(logger: Logger(label: "")) { server in
66+
guard case .successful(let serverAddress) = server.startResult else {
67+
XCTFail("failed to start server")
68+
return
69+
}
70+
71+
let response = try await HTTPClient.shared.get(
72+
url: "http://127.0.0.1:\(serverAddress.port!)/health"
73+
).get()
74+
XCTAssertEqual(.ok, response.status)
75+
XCTAssertEqual(ByteBuffer(string: "OK"), response.body)
76+
}
77+
}
78+
6179
func testUserExtraHandlerBasic() async throws {
6280
let server = ProfileRecorderServer(
6381
configuration: try ProfileRecorderServerConfiguration.makeTCPListener(host: "127.0.0.1", port: 0)

0 commit comments

Comments
 (0)