项目作者: skylab-inc

项目描述 :
A Swift Multiplatform Single-threaded Non-blocking Web and Networking Framework
高级语言: Swift
项目地址: git://github.com/skylab-inc/Lightning.git
创建时间: 2016-05-03T07:49:00Z
项目社区:https://github.com/skylab-inc/Lightning

开源协议:MIT License

下载



Edge

Serverside non-blocking IO in Swift

Ask questions in our Slack channel!

Lightning

(formerly Edge)

Swift
Build Status
codecov
Slack Status

Node

Lightning is an HTTP Server and TCP Client/Server framework written in Swift and inspired by Node.js. It runs on both OS X and Linux. Like Node.js, Lightning uses an event-driven, non-blocking I/O model. In the same way that Node.js uses libuv to implement this model, Lightning uses libdispatch.

This makes Lightning fast, efficient, and most crutially single-threaded by default. You simply do not need to worry about locks/mutexes/semaphores/etc if you have server-side state. Of course, Lightning applications can make use of libdispatch to easily offload heavy processing to a background thread if necessary.

Reactive Programming

Lightning’s event API embraces Functional Reactive Programming by generalizing the familiar concept of promises. This API is called StreamKit.

StreamKit’s architecture is inspired by both ReactiveCocoa and RxSwift.

Why did we reimplement?
  • Lightning should be easy to use out of the box.
  • Lightning is optimized for maximum performance, which requires careful tuning of the internals.
  • The modified API is meant to be more similar to the familiar concepts of Futures and Promises.
  • We don’t want to be opinionated about any one framework. We want it to be easy to integate Lightning with either ReactiveCocoa or RxSwift.

FRP, greatly simplies management of asynchronous events. The general concept is that we can build a spout which pushes out asynchronous events as they happen. Then we hookup a pipeline of transformations that operate on events and pass the transformed values along. We can even do things like merge streams in interesting ways! Take a look at some of these operations or watch this talk about how FRP is used at Netflix.

Installation

Lightning is available as a Swift 3/4 package. Simply add Lightning as a dependency to your Swift Package.

Swift 3

  1. import PackageDescription
  2. let package = Package(
  3. name: "MyProject",
  4. dependencies: [
  5. .Package(url: "https://github.com/skylab-inc/Lightning.git", majorVersion: 0, minor: 3)
  6. ]
  7. )

Swift 4

  1. // swift-tools-version:4.0
  2. // The swift-tools-version declares the minimum version of Swift required to build this package.
  3. import PackageDescription
  4. let package = Package(
  5. name: "MyProject",
  6. dependencies: [
  7. .package(url: "https://github.com/skylab-inc/Lightning.git", from: "0.3.0"),
  8. ]
  9. )

Usage

Routing

  1. import Lightning
  2. import Foundation
  3. // Create an API router.
  4. let api = Router()
  5. // Add a GET "/users" endpoint.
  6. api.get("/users") { request in
  7. return Response(status: .ok)
  8. }
  9. // NOTE: Equivalent to `api.post("/auth/login")`
  10. let auth = api.subrouter("/auth")
  11. auth.post("/login") { request in
  12. return Response(status: .ok)
  13. }
  14. // Middleware to log all requests
  15. // NOTE: Middleware is a simple as a map function or closure!
  16. let app = Router()
  17. app.map { request in
  18. print(request)
  19. return request
  20. }
  21. // Mount the API router under "/v1.0".
  22. app.add("/v1.0", api)
  23. // NOTE: Warnings on all unhandled requests. No more hanging clients!
  24. app.any { _ in
  25. return Response(status: .notFound)
  26. }
  27. // Start the application.
  28. app.start(host: "0.0.0.0", port: 3000)

Raw HTTP

  1. import Lightning
  2. import Foundation
  3. func handleRequest(request: Request) -> Response {
  4. print(String(bytes: request.body, encoding: .utf8)!)
  5. return try! Response(json: ["message": "Message received!"])
  6. }
  7. let server = HTTP.Server()
  8. server.listen(host: "0.0.0.0", port: 3000).startWithNext { client in
  9. let requestStream = client.read()
  10. requestStream.map(handleRequest).onNext{ response in
  11. client.write(response).start()
  12. }
  13. requestStream.onFailed { clientError in
  14. print("Oh no, there was an error! \(clientError)")
  15. }
  16. requestStream.onCompleted {
  17. print("Goodbye \(client)!")
  18. }
  19. requestStream.start()
  20. }
  21. RunLoop.runAll()

TCP

  1. import Lightning
  2. import Foundation
  3. let server = try! TCP.Server()
  4. try! server.bind(host: "0.0.0.0", port: 50000)
  5. server.listen().startWithNext { connection in
  6. let byteStream = connection.read()
  7. let strings = byteStream.map { String(bytes: $0, encoding: .utf8)! }
  8. strings.onNext { message in
  9. print("Client \(connection) says \"\(message)\"!")
  10. }
  11. strings.onFailed { error in
  12. print("Oh no, there was an error! \(error)")
  13. }
  14. strings.onCompleted {
  15. print("Goodbye \(connection)!")
  16. }
  17. strings.start()
  18. }
  19. RunLoop.runAll()

Lightning is not Node.js

Lightning is not meant to fulfill all of the roles of Node.js. Node.js is a JavaScript runtime, while Lightning is a TCP/Web server framework. The Swift compiler and package manager, combined with third-party Swift packages, make it unnecessary to build that functionality into Lightning.