Study · SwiftPM · 2.3.2

Học CoAkka HTTP Runtime với Swift

Bắt đầu với một yêu cầu trong một tiến trình. Sau đó thực hành gửi tệp, phát sự kiện, mở WebSocket và theo dõi dịch vụ xử lý xong.

Beginner

Cài connector

Dùng Swift 6.0 trở lên và tạo thư mục dự án riêng. Tệp dự án ghim coakka-http-runtime-swift 2.3.2 qua SwiftPM.

Terminal
swift --version
Package.swift
// 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"),
        ]),
    ]
)

Trên macOS 14 trở lên với Apple silicon, chạy dự án bằng swift run Server.

Linux, WSL2 và Windows

Đặt thư viện native SwiftPM cạnh chương trình đã build. Dùng swift build --show-bin-path để tìm thư mục chứa chương trình. Chọn thư viện theo kiến trúc của tiến trình Swift.

Linux hoặc WSL2
Cài lld rồi chạy swift build -Xswiftc -use-ld=lld. Chép libcoakka_http_host.so.1 và libcoakka_http_managed_host.so từ .build/checkouts/coakka-http-runtime-swift/Native/linux-x64/ hoặc Native/linux-arm64/.
Windows
Chạy swift build trong terminal đã cấu hình Swift. Chép coakka_http_host.dll và coakka_http_managed_host.dll từ Native/win-x64/ hoặc Native/win-arm64/ trong checkout. Giữ CoAkkaHttp.dll cạnh Server.exe và đưa Swift runtime vào PATH.

Trên Linux, đặt LD_LIBRARY_PATH trỏ tới thư mục chứa chương trình rồi chạy Server từ thư mục dự án. Trên Windows, gọi Server.exe bằng đường dẫn tới tệp từ thư mục dự án. Các ví dụ tìm files/ và certs/ theo thư mục đang đứng.

Trong 2.3.2, 2.3 là thế hệ Core và 2 là số thứ tự của bản phát hành connector của connector trên Core đó. Gói kèm thư viện native tương ứng.

Beginner

Chạy yêu cầu đầu tiên

Lưu mã dưới đây thành Sources/Server/main.swift.

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 }
}
Terminal
swift run Server

Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.

Terminal
curl -isS "$BASE_URL/hello/Ada"

Kết quả đúng là 200 và hello Ada. Server xử lý một yêu cầu khớp route, drain rồi thoát. Giá trị cổng 0 để hệ điều hành chọn cổng trống.

Beginner

Đọc yêu cầu

Chạy lại ví dụ đầu tiên và gọi /hello/Ada?tag=one&tag=two&flag. Kết quả vẫn là hello Ada. Xem request trong debugger để thấy 3 mục query theo đúng thứ tự.

pathParameters
Giá trị name khớp với /hello/{name}. Giải mã và xác thực khi nghiệp vụ cần.
queryParameters
Giữ thứ tự, các khóa lặp và phân biệt giá trị vắng mặt với chuỗi rỗng.
headers
Đọc giá trị handler cần sau khi Core đã khớp phương thức và đường dẫn.
body
Nội dung yêu cầu đã được đọc vào bộ đệm. Chọn route streaming khi cần xử lý từng phần.

Tra cứu các thành phần của yêu cầu

Beginner

Gọi dịch vụ upstream

Dùng Python 3.11 trở lên để mở upstream HTTP/1.1 trong terminal riêng.

Terminal
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

Lưu mã dưới đây thành Sources/Server/main.swift và thay nội dung của tập trước.

Sources/Server/main.swift
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()
Terminal
swift run Server

Kết quả đúng là HTTP 200 rồi hello upstream. Hạn 3 giây của yêu cầu và thời gian chờ kết quả 5 giây có mục đích riêng. Bấm Ctrl+C để dừng upstream sau khi thử.

Tra cứu lỗi khi gọi upstream

Advanced

Gửi tệp cho client

Tạo một tệp thử. File authority giới hạn tệp mà handler được chọn trong thư mục này, đồng thời giới hạn số tệp đang gửi và kích thước.

Terminal
mkdir -p files
printf '%s\n' 'CoAkka file delivery' > files/manual.txt

Lưu mã dưới đây thành Sources/Server/main.swift và thay nội dung của tập trước.

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 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 }
}
Terminal
swift run Server

Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.

Terminal
curl -isS "$BASE_URL/download"

Kết quả là nội dung tệp files/manual.txt. Ví dụ gửi tệp từ server về client. Để gửi tệp theo chiều ngược lại, xem hướng dẫn tải tệp · bài thực hành upload.

Advanced

Gửi 2 sự kiện SSE

Lưu mã dưới đây thành Sources/Server/main.swift và thay nội dung của tập trước.

Sources/Server/main.swift
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 }
}
Terminal
swift run Server

Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.

Terminal
curl -NsS "$BASE_URL/events"

Client nhận data: ready rồi data: done trước khi luồng kết thúc. Handler chờ sự kiện cho phép ghi của đúng yêu cầu rồi mới gửi dữ liệu.

Tra cứu SSE và cách kết nối lại

Advanced

Phản hồi tin nhắn WebSocket

Lưu mã dưới đây thành Sources/Server/main.swift và thay nội dung của tập trước.

Sources/Server/main.swift
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 }
}
Terminal
swift run Server

Dùng console của trình duyệt trên một trang HTTP cục bộ. Thay 49321 bằng cổng mà server in ra.

JavaScript
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();
  }
};

Kết quả gồm lời chào và echo: ping. Client đóng phiên rồi tiến trình drain. Ví dụ chạy một phiên WebSocket trên loopback.

Vòng đời và lỗi của WebSocket

Advanced

Chọn cấu hình listener

Các bài gửi tệp, streaming và WebSocket ở đây dùng listener đơn. Chọn MultiProtocol khi muốn phục vụ HTTP/1.1, HTTP/2 và HTTP/3 cùng cổng TLS cho yêu cầu và phản hồi có bộ đệm.

Chạy project Swift với 3 giao thức · Chứng chỉ và thay chứng chỉ

Advanced

Theo dõi yêu cầu và drain

Lưu mã dưới đây thành Sources/Server/main.swift và thay nội dung của tập trước.

Sources/Server/main.swift
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 }
}
Terminal
swift run Server

Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.

Terminal
curl -isS "$BASE_URL/hello/Ada"

Sau 200 hello Ada, xem số yêu cầu đã nhận, đã hoàn tất và dòng drain complete trong terminal của server. Drain ngừng nhận việc mới để xử lý nốt việc đã nhận trong thời hạn chờ. Khi hết hạn, đọc trạng thái drain trước khi giải phóng service.

Các thuộc tính của Monitor · Điều khiển khi đang chạy · Thử giữ một yêu cầu khi drain