FlyingFox 0.15.0

FlyingFox 0.15.0

Simon Whitty维护。



FlyingFox 0.15.0

  • 作者
  • Simon Whitty

Build Codecov Platforms Swift 5.8 License Twitter

简介

FlyingFox 是一个使用 Swift 并发 构建的轻量级 HTTP 服务器。该服务器使用非阻塞的 BSD 套接字,在并发子 任务 中处理每个连接。当一个套接字由于没有数据而阻塞时,将通过共享的 AsyncSocketPool 暂停任务。

安装

FlyingFox 可以通过使用 Swift 包管理器进行安装。

注意: FlyingFox 需要 Swift 5.5 及以上版本,以及在 Xcode 13.2 及以上版本中运行。它支持 iOS 13 及以上版本、tvOS 13 及以上版本、macOS 10.15 及以上版本和 Linux。Windows 10 支持为实验性质。

要使用 Swift 包管理器进行安装,请将以下内容添加到您的 Package.swift 文件的 dependencies: 部分

.package(url: "https://github.com/swhitty/FlyingFox.git", .upToNextMajor(from: "0.12.2"))

用法

通过提供端口号来启动服务器

import FlyingFox

let server = HTTPServer(port: 80)
try await server.start()

服务器在当前任务中运行。要停止服务器,取消任务,立即终止所有连接。

let task = Task { try await server.start() }
task.cancel()

在所有现有请求完成后,优雅地关闭服务器,否则将在超时后强制关闭。

await server.stop(timeout: 3)

等待服务器开始监听并准备好连接。

try await server.waitUntilListening()

检索当前监听地址。

await server.listeningAddress

注意:当应用程序在后台挂起时,iOS 将挂起监听套接字。一旦应用程序返回前台,HTTPServer.start() 检测到此情况,抛出 SocketError.disconnected。然后必须再次启动服务器。

处理器

可以通过实现 HTTPHandler 将处理器添加到服务器。

protocol HTTPHandler {
  func handleRequest(_ request: HTTPRequest) async throws -> HTTPResponse
}

可以将路由添加到服务器,将请求委派给处理器。

await server.appendRoute("/hello", to: handler)

它们也可以添加到闭包中。

await server.appendRoute("/hello") { request in
  try await Task.sleep(nanoseconds: 1_000_000_000)
  return HTTPResponse(statusCode: .ok)
}

传入的请求将被路由到第一个匹配路由的处理器。

如果处理器在检查请求后无法处理,它们可以抛出 HTTPUnhandledError。然后使用下一个匹配的路由。

不匹配任何处理路由的请求会收到 HTTP 404 响应。

FileHTTPHandler

可以使用 FileHTTPHandler 将请求路由到静态文件。

await server.appendRoute("GET /mock", to: .file(named: "mock.json"))

FileHTTPHandler 如果文件不存在,将返回 HTTP 404

DirectoryHTTPHandler

可以使用 DirectoryHTTPHandler 将请求路由到目录中的静态文件。

await server.appendRoute("GET /mock/*", to: .directory(subPath: "Stubs", serverPath: "mock"))
// GET /mock/fish/index.html  ---->  Stubs/fish/index.html

DirectoryHTTPHandler 如果文件不存在,将返回 HTTP 404

ProxyHTTPHandler

请求可以通过基本URL进行代理。

await server.appendRoute("GET *", to: .proxy(via: "https://pie.dev"))
// GET /get?fish=chips  ---->  GET https://pie.dev/get?fish=chips

RedirectHTTPHandler

请求可以被重定向到URL。

await server.appendRoute("GET /fish/*", to: .redirect(to: "https://pie.dev/get"))
// GET /fish/chips  --->  HTTP 301
//                        Location: https://pie.dev/get

WebSocketHTTPHandler

可以通过提供一个 WSMessageHandler,在其中交换一对 AsyncStream<WSMessage>,将请求路由到WebSocket。

await server.appendRoute("GET /socket", to: .webSocket(EchoWSMessageHandler()))

protocol WSMessageHandler {
  func makeMessages(for client: AsyncStream<WSMessage>) async throws -> AsyncStream<WSMessage>
}

enum WSMessage {
  case text(String)
  case data(Data)
}

也可以提供原始WebSocket帧。

RoutedHTTPHandler

可以使用 RoutedHTTPHandler 将多个处理程序与请求分组,并匹配 HTTPRoute

var routes = RoutedHTTPHandler()
routes.appendRoute("GET /fish/chips", to: .file(named: "chips.json"))
routes.appendRoute("GET /fish/mushy_peas", to: .file(named: "mushy_peas.json"))
await server.appendRoute(for: "GET /fish/*", to: routes)

当无法用其已注册的处理程序处理请求时,将抛出 HTTPUnhandledError

Routes

HTTPRoute设计为可以通过模式匹配HTTPRequest进行比较,允许通过其一部分或全部属性来识别请求。

let route = HTTPRoute("/hello/world")

route ~= HTTPRequest(method: .GET, path: "/hello/world") // true
route ~= HTTPRequest(method: .POST, path: "/hello/world") // true
route ~= HTTPRequest(method: .GET, path: "/hello/") // false

路由支持ExpressibleByStringLiteral,允许字面量自动转换为HTTPRoute

let route: HTTPRoute = "/hello/world"

路由可以包括一个特定的方法来匹配

let route = HTTPRoute("GET /hello/world")

route ~= HTTPRequest(method: .GET, path: "/hello/world") // true
route ~= HTTPRequest(method: .POST, path: "/hello/world") // false

它们还可以在路径中使用通配符

let route = HTTPRoute("GET /hello/*/world")

route ~= HTTPRequest(method: .GET, path: "/hello/fish/world") // true
route ~= HTTPRequest(method: .GET, path: "/hello/dog/world") // true
route ~= HTTPRequest(method: .GET, path: "/hello/fish/sea") // false

尾部通配符匹配所有尾部路径组件

let route = HTTPRoute("/hello/*")

route ~= HTTPRequest(method: .GET, path: "/hello/fish/world") // true
route ~= HTTPRequest(method: .GET, path: "/hello/dog/world") // true
route ~= HTTPRequest(method: .POST, path: "/hello/fish/deep/blue/sea") // true

可以匹配特定的查询项

let route = HTTPRoute("/hello?time=morning")

route ~= HTTPRequest(method: .GET, path: "/hello?time=morning") // true
route ~= HTTPRequest(method: .GET, path: "/hello?count=one&time=morning") // true
route ~= HTTPRequest(method: .GET, path: "/hello") // false
route ~= HTTPRequest(method: .GET, path: "/hello?time=afternoon") // false

查询项值可以包含通配符

let route = HTTPRoute("/hello?time=*")

route ~= HTTPRequest(method: .GET, path: "/hello?time=morning") // true
route ~= HTTPRequest(method: .GET, path: "/hello?time=afternoon") // true
route ~= HTTPRequest(method: .GET, path: "/hello") // false

可以匹配HTTP头

let route = HTTPRoute("*", headers: [.contentType: "application/json"])

route ~= HTTPRequest(headers: [.contentType: "application/json"]) // true
route ~= HTTPRequest(headers: [.contentType: "application/xml"]) // false

头值可以是通配符

let route = HTTPRoute("*", headers: [.authorization: "*"])

route ~= HTTPRequest(headers: [.authorization: "abc"]) // true
route ~= HTTPRequest(headers: [.authorization: "xyz"]) // true
route ~= HTTPRequest(headers: [:]) // false

可以创建Body模式来匹配请求数据

public protocol HTTPBodyPattern: Sendable {
  func evaluate(_ body: Data) -> Bool
}

Darwin平台可以使用NSPredicate匹配JSON体

let route = HTTPRoute("POST *", body: .json(where: "food == 'fish'"))
{"side": "chips", "food": "fish"}

WebSockets

HTTPResponse可以通过在响应载荷中提供WSHandler来切换到WebSocket协议

protocol WSHandler {
  func makeFrames(for client: AsyncThrowingStream<WSFrame, Error>) async throws -> AsyncStream<WSFrame>
}

WSHandler促成了包含通过连接发送的原始WebSocket帧的AsyncStream<WSFrame>的交换。尽管很强大,但还是更方便通过WebSocketHTTPHandler交换消息流。

FlyingSocks

内部,FlyingFox使用标准BSD套接字的薄包装。FlyingSocks模块为这些套接字提供跨平台的异步接口;

import FlyingSocks

let socket = try await AsyncSocket.connected(to: .inet(ip4: "192.168.0.100", port: 80))
try await socket.write(Data([0x01, 0x02, 0x03]))
try socket.close()

Socket

Socket封装了一个文件描述符,并提供了一个Swift接口对常见操作,通过抛出SocketError代替返回错误代码。

public enum SocketError: LocalizedError {
  case blocked
  case disconnected
  case unsupportedAddress
  case failed(type: String, errno: Int32, message: String)
}

当套接字的数据不可用且返回EWOULDBLOCK errno时,抛出SocketError.blocked

AsyncSocket

AsyncSocket 简单地封装了一个 Socket,提供了一个异步接口。所有异步套接字都配置为使用标志 O_NONBLOCK,捕获 SocketError.blocked 异常,然后使用 AsyncSocketPool 暂停当前任务。当数据变得可用时,任务将恢复,并且 AsyncSocket 将重新尝试操作。

AsyncSocketPool

protocol AsyncSocketPool {
  func prepare() async throws
  func run() async throws

  // Suspends current task until a socket is ready to read and/or write
  func suspendSocket(_ socket: Socket, untilReadyFor events: Socket.Events) async throws
}

SocketPool

SocketPool<Queue>HTTPServer 中使用的默认池。它根据平台使用泛型 EventQueue 暂停和恢复套接字。在 Darwin 平台上抽象 kqueue(2),在 Linux 上抽象 epoll(7),池使用内核事件,无需持续轮询等待的文件描述符。

Windows 使用由 poll(2) / Task.yield() 支持的循环队列来检查在指定间隔内等待数据的所有套接字。

SocketAddress

通过符合 SocketAddress 的规范,将结构体簇 sockaddr 进行分组。

  • sockaddr_in
  • sockaddr_in6
  • sockaddr_un

这允许使用这些配置好的地址启动 HTTPServer

// only listens on localhost 8080
let server = HTTPServer(address: .loopback(port: 8080))

它还可以与 UNIX-domain 地址一起使用,允许通过套接字进行私密 IPC。

// only listens on Unix socket "Ants"
let server = HTTPServer(address: .unix(path: "Ants"))

然后可以通过 netcat 与套接字进行交互。

% nc -U Ants

命令行应用程序

一个示例命令行应用程序 FlyingFoxCLI 在这里可用:https://github.com/swhitty/FlyingFoxCLI

鸣谢

FlyingFox 主要由 Simon Whitty 完成。

(所有贡献者列表)