Study · SwiftPM · 2.3.2
Learn CoAkka HTTP Runtime with Swift
Start with one request in one process. Then send a file, stream updates, open a WebSocket and watch the service finish its work.
Beginner
Install the connector
Use Swift 6.0 or later and create a project folder. The manifest pins coakka-http-runtime-swift 2.3.2 from SwiftPM.
swift --version
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "CoAkkaHttpListenerSample",
platforms: [.macOS(.v14)],
dependencies: [
.package(url: "https://github.com/phuong-tran/coakka-http-runtime-swift.git", exact: "2.3.2"),
],
targets: [
.executableTarget(name: "Server", dependencies: [
.product(name: "CoAkkaHttp", package: "coakka-http-runtime-swift"),
]),
]
)
On macOS 14 or later with Apple silicon, run the project with swift run Server.
Linux, WSL2 and Windows
Place the SwiftPM native libraries beside the compiled executable. Find its directory with swift build --show-bin-path. The architectures below refer to the Swift process.
- Linux or WSL2
- Install
lld, then useswift build -Xswiftc -use-ld=lld. Copylibcoakka_http_host.so.1andlibcoakka_http_managed_host.sofrom.build/checkouts/coakka-http-runtime-swift/Native/linux-x64/orNative/linux-arm64/. - Windows
- Run
swift buildin the Swift toolchain shell. Copycoakka_http_host.dllandcoakka_http_managed_host.dllfrom the checkout’sNative/win-x64/orNative/win-arm64/. Keep the builtCoAkkaHttp.dllbesideServer.exeand the Swift runtime onPATH.
On Linux, set LD_LIBRARY_PATH to the executable directory and run Server from the project directory. On Windows run Server.exe by its path from the project directory. Keep that working directory so the examples can find files/ and certs/.
In 2.3.2, 2.3 identifies Core and 2 is the connector revision. The package includes the matching native libraries.
Beginner
Serve the first request
Save this file as Sources/Server/main.swift.
import CoAkkaHttp
import Foundation
enum LessonError: Error {
case expectedRequest
case drainFailed
}
let listener: HttpListener = .standalone(protocol: .http11, address: "127.0.0.1", port: 0)
let route = HttpRoute(routeID: 1, bindingID: 1, method: "GET", pattern: "/hello/{name}")
let service = try HttpService(listener: listener, routes: [route])
defer { try? service.close() }
try service.start()
FileHandle.standardOutput.write(Data(("http://127.0.0.1:\(try service.port)/hello/Ada" + "\n").utf8))
let requestDeadline = ContinuousClock.now + .seconds(60)
var next = try service.take(timeoutMilliseconds: 250)
while next == nil && ContinuousClock.now < requestDeadline {
next = try service.take(timeoutMilliseconds: 250)
}
guard let request = next, request.kind == .request, request.bindingID == 1 else {
throw LessonError.expectedRequest
}
let name = request.pathParameters.first(where: { $0.name == "name" })?.value ?? ""
try requireOK(service.respond(
to: request.exchange, status: 200, body: Array("hello \(name)".utf8),
headers: [HttpField("content-type", "text/plain; charset=utf-8")]))
try service.beginDrain()
let drain = try service.waitDrained(timeoutMilliseconds: 5000)
try service.stop()
guard drain.state == .complete, drain.status == .ok else { throw LessonError.drainFailed }
try service.close()
print("drain complete")
func requireOK(_ status: CoreStatus) throws {
guard status == .ok else { throw status }
}
swift run Server
When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.
curl -isS "$BASE_URL/hello/Ada"
Expect 200 and hello Ada. The server serves one matching request, drains and exits. A port of 0 lets the OS pick a free port.
Beginner
Read the request
Restart the first example and call /hello/Ada?tag=one&tag=two&flag. It still returns hello Ada. Inspect the request in the debugger to see the 3 ordered query entries.
pathParameters- The capture
namefrom/hello/{name}. Decode and validate it when needed. queryParameters- Entries keep order, duplicate keys and the difference between a missing and an empty value.
headers- Read each value your handler needs. The Core already matched the method and path.
body- The buffered request body. Use a streaming route when the body needs incremental processing.
Beginner
Call an upstream service
In a separate terminal, start an HTTP/1.1 upstream with Python 3.11+.
mkdir -p upstream
printf '%s\n' 'hello upstream' > upstream/hello.txt
python3 -m http.server 9080 --bind 127.0.0.1 --protocol HTTP/1.1 --directory upstream
Save this file as Sources/Server/main.swift, replacing the previous episode’s source.
import CoAkkaHttp
enum LessonError: Error {
case missingResult
case upstreamFailed(OutboundReason, UInt16)
}
let endpoint = OutboundEndpoint(
nodeID: "local", connectHost: "127.0.0.1", connectPort: 9080,
httpAuthority: "127.0.0.1:9080", security: .plaintext)
let target = OutboundTarget(name: "example", generation: 1, endpoints: [endpoint])
let service = try HttpService(
listener: .standalone(protocol: .http11, address: "127.0.0.1"),
routes: [], outbound: OutboundOptions(targets: [target]))
defer { try? service.close() }
try service.start()
let call = try service.submitOutbound(OutboundRequest(
logicalTarget: "example", method: "GET", target: "/hello.txt", timeoutMilliseconds: 3000))
guard let result = try service.takeOutbound(timeoutMilliseconds: 5000),
result.call == call else {
throw LessonError.missingResult
}
guard result.reason == .response, result.responseStatus == 200 else {
throw LessonError.upstreamFailed(result.reason, result.responseStatus)
}
print("HTTP \(result.responseStatus)")
print(String(decoding: result.body, as: UTF8.self))
try service.stop()
try service.close()
swift run Server
Expect HTTP 200 then hello upstream. The 3-second request deadline and the 5-second result wait serve separate purposes. Stop the fixture with Ctrl+C when done.
Advanced
Send a file
Create one test file. The file authority confines the handler’s selection to this directory and bounds active files and size.
mkdir -p files
printf '%s\n' 'CoAkka file delivery' > files/manual.txt
Save this file as Sources/Server/main.swift, replacing the previous episode’s source.
import CoAkkaHttp
import Foundation
enum LessonError: Error {
case expectedRequest
case drainFailed
}
let listener: HttpListener = .standalone(protocol: .http11, address: "127.0.0.1", port: 0)
let root = URL(fileURLWithPath: "files", isDirectory: true).standardizedFileURL.path
let files = FileAuthority(id: 1, root: root, maxActiveFiles: 4, maxFileBytes: 1024 * 1024)
let route = HttpRoute(routeID: 1, bindingID: 1, method: "GET", pattern: "/download")
let service = try HttpService(listener: listener, routes: [route], fileAuthorities: [files])
defer { try? service.close() }
try service.start()
FileHandle.standardOutput.write(Data(("http://127.0.0.1:\(try service.port)/download" + "\n").utf8))
let requestDeadline = ContinuousClock.now + .seconds(60)
var next = try service.take(timeoutMilliseconds: 250)
while next == nil && ContinuousClock.now < requestDeadline {
next = try service.take(timeoutMilliseconds: 250)
}
guard let request = next, request.kind == .request, request.bindingID == 1 else {
throw LessonError.expectedRequest
}
try requireOK(service.respondFile(
to: request.exchange, status: 200, authorityID: files.id, encodedPath: "/manual.txt"))
try service.beginDrain()
let drain = try service.waitDrained(timeoutMilliseconds: 5000)
try service.stop()
guard drain.state == .complete, drain.status == .ok else { throw LessonError.drainFailed }
try service.close()
print("drain complete")
func requireOK(_ status: CoreStatus) throws {
guard status == .ok else { throw status }
}
swift run Server
When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.
curl -isS "$BASE_URL/download"
Expect the contents of files/manual.txt. This example sends a file from the server to the client. See the file delivery guide. For the reverse direction, open the upload labs.
Advanced
Send two server events
Save this file as Sources/Server/main.swift, replacing the previous episode’s source.
import CoAkkaHttp
import Foundation
enum LessonError: Error {
case expectedRequest
case drainFailed
case expectedWritable
}
let listener: HttpListener = .standalone(protocol: .http11, address: "127.0.0.1", port: 0)
let route = HttpRoute(routeID: 1, bindingID: 1, method: "GET", pattern: "/events")
let service = try HttpService(listener: listener, routes: [route])
defer { try? service.close() }
try service.start()
FileHandle.standardOutput.write(Data(("http://127.0.0.1:\(try service.port)/events" + "\n").utf8))
let requestDeadline = ContinuousClock.now + .seconds(60)
var next = try service.take(timeoutMilliseconds: 250)
while next == nil && ContinuousClock.now < requestDeadline {
next = try service.take(timeoutMilliseconds: 250)
}
guard let request = next, request.kind == .request, request.bindingID == 1 else {
throw LessonError.expectedRequest
}
try requireOK(service.startServerSentEvents(to: request.exchange))
// Wait for Core to make the response writable before submitting events.
let writeDeadline = ContinuousClock.now + .seconds(5)
var nextWritable = try service.take(timeoutMilliseconds: 250)
while nextWritable == nil && ContinuousClock.now < writeDeadline {
nextWritable = try service.take(timeoutMilliseconds: 250)
}
guard let writable = nextWritable,
writable.kind == .responseWritable, writable.exchange == request.exchange else {
throw LessonError.expectedWritable
}
try requireOK(service.writeServerSentEvent(to: request.exchange, event: ServerSentEvent(
data: "ready", eventType: "state", id: "1", retryMilliseconds: 1000)))
try requireOK(service.writeServerSentEvent(to: request.exchange, event: ServerSentEvent(data: "done")))
try requireOK(service.finishResponseStream(to: request.exchange))
try service.beginDrain()
let drain = try service.waitDrained(timeoutMilliseconds: 5000)
try service.stop()
guard drain.state == .complete, drain.status == .ok else { throw LessonError.drainFailed }
try service.close()
print("drain complete")
func requireOK(_ status: CoreStatus) throws {
guard status == .ok else { throw status }
}
swift run Server
When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.
curl -NsS "$BASE_URL/events"
The client receives data: ready and data: done before the stream ends. The handler waits for a writable event from the same request before submitting output.
Advanced
Echo a WebSocket message
Save this file as Sources/Server/main.swift, replacing the previous episode’s source.
import CoAkkaHttp
import Foundation
enum LessonError: Error {
case expectedRequest
case drainFailed
case handshakeFailed
case clientDidNotClose
}
let listener: HttpListener = .standalone(protocol: .http11, address: "127.0.0.1", port: 0)
let route = HttpRoute(routeID: 1, bindingID: 1, method: "GET", pattern: "/socket", webSocket: true)
let service = try HttpService(listener: listener, routes: [route])
defer { try? service.close() }
try service.start()
FileHandle.standardOutput.write(Data(("http://127.0.0.1:\(try service.port)/socket" + "\n").utf8))
let requestDeadline = ContinuousClock.now + .seconds(60)
var next = try service.take(timeoutMilliseconds: 250)
while next == nil && ContinuousClock.now < requestDeadline {
next = try service.take(timeoutMilliseconds: 250)
}
guard let request = next, request.kind == .request, request.bindingID == 1 else {
throw LessonError.expectedRequest
}
try requireOK(service.acceptWebSocket(request.exchange, subprotocol: "coakka.demo"))
let deadline = ContinuousClock.now + .seconds(45)
var closed = false
while !closed && ContinuousClock.now < deadline {
guard let frame = try service.takeWebSocket(timeoutMilliseconds: 500) else { continue }
switch frame.kind {
case .open:
try requireOK(service.sendWebSocket(to: frame.session, kind: .text, data: Array("hello".utf8)))
case .text:
let echo = "echo: " + String(decoding: frame.data, as: UTF8.self)
try requireOK(service.sendWebSocket(to: frame.session, kind: .text, data: Array(echo.utf8)))
case .close:
closed = true
case .acceptFailed:
throw LessonError.handshakeFailed
default:
break
}
}
guard closed else { throw LessonError.clientDidNotClose }
try service.beginDrain()
let drain = try service.waitDrained(timeoutMilliseconds: 5000)
try service.stop()
guard drain.state == .complete, drain.status == .ok else { throw LessonError.drainFailed }
try service.close()
print("drain complete")
func requireOK(_ status: CoreStatus) throws {
guard status == .ok else { throw status }
}
swift run Server
Use a browser console on a local HTTP page. Replace 49321 with the printed port.
const socket = new WebSocket("ws://127.0.0.1:49321/socket", "coakka.demo");
socket.onmessage = ({ data }) => {
console.log(data);
if (data === "hello") {
socket.send("ping");
} else if (data === "echo: ping") {
socket.close();
}
};
Expect the greeting and echo: ping. The client closes the session, then the process drains. The example uses one WebSocket session on loopback.
Advanced
Choose the listener profile
Use a standalone listener for file responses, streams and WebSockets in these lessons. Choose MultiProtocol for buffered HTTP/1.1, HTTP/2 and HTTP/3 on one TLS port.
Run the full Swift protocol project · Certificates and reload
Advanced
Observe completion and drain
Save this file as Sources/Server/main.swift, replacing the previous episode’s source.
import CoAkkaHttp
import Foundation
enum LessonError: Error {
case expectedRequest
case drainFailed
case monitorMissingCompletion
}
let listener: HttpListener = .standalone(protocol: .http11, address: "127.0.0.1", port: 0)
let route = HttpRoute(routeID: 1, bindingID: 1, method: "GET", pattern: "/hello/Ada")
let service = try HttpService(listener: listener, routes: [route], monitor: MonitorOptions(categories: .exchange))
defer { try? service.close() }
try service.start()
FileHandle.standardOutput.write(Data(("http://127.0.0.1:\(try service.port)/hello/Ada" + "\n").utf8))
let requestDeadline = ContinuousClock.now + .seconds(60)
var next = try service.take(timeoutMilliseconds: 250)
while next == nil && ContinuousClock.now < requestDeadline {
next = try service.take(timeoutMilliseconds: 250)
}
guard let request = next, request.kind == .request, request.bindingID == 1 else {
throw LessonError.expectedRequest
}
try requireOK(service.respond(to: request.exchange, status: 200, body: Array("hello Ada".utf8)))
try service.beginDrain()
let drain = try service.waitDrained(timeoutMilliseconds: 5000)
let snapshot = try service.readMonitor()
guard snapshot.collecting, snapshot.admittedRequests > 0, snapshot.completed > 0 else {
throw LessonError.monitorMissingCompletion
}
print("admitted=\(snapshot.admittedRequests), completed=\(snapshot.completed)")
try service.stop()
guard drain.state == .complete, drain.status == .ok else { throw LessonError.drainFailed }
try service.close()
print("drain complete")
func requireOK(_ status: CoreStatus) throws {
guard status == .ok else { throw status }
}
swift run Server
When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.
curl -isS "$BASE_URL/hello/Ada"
After 200 hello Ada, look for the admitted and completed counts and drain complete in the service terminal. Drain stops admitting new work and lets accepted work finish within the wait. A timeout requires checking the returned drain state before disposal.