Lightweight library for web server applications in Swift on macOS and Linux powered by coroutines.

Last update: Jun 23, 2022

Zewo

Swift License Slack Codebeat

Why Zewo?SupportCommunityContributing

Zewo

Zewo is a lightweight library for web applications in Swift.

What sets Zewo apart?

Zewo is not a web framework. Zewo is a lightweight library for web applications in Swift. Most server-side Swift projects use Grand Central Dispatch (GCD) as the concurrency library of choice. The drawback of using GCD is that its APIs are asynchronous. With async code comes callback hell and we all know it, it's no fun.

Node.js is the best example of how callbacks can be frustrating. Express.js creator TJ Holowaychuk wrote a blog post about Callback vs Coroutines in 2013 and one year later left the Node.js community in favor of Go. There were many reasons for that but one of the main reasons was the concurrency model. Sure we have futures and promises and functional reactive programming. They all mitigate the problem, but the async nature of the code will always be there.

At Zewo we use coroutines. Coroutines allow concurrency while maintaining synchronous APIs. We all learn how to program with synchronous code. We're used to reason about our code synchronously. Being able to use synchronous APIs makes the code much more readable and understandable. Coroutines are also faster than threads, because they live in user-space, unlike threads which are managed by the kernel.

Our implementation of coroutines (which is based on libdill) is single-threaded. This means that you don't have to worry about locks or race conditions. So your code is safer by default. To use all the CPU power available all you have to do is to replicate the work according to the number of logical CPUs available. As an example, this could mean running as many processes of your server as cores in your machine. Rob Pike, one of the creators of Go had a talk called Concurrency is not Parallelism that explains this concept very well. Go also has the philosophy:

Don't communicate by sharing memory. Share memory by communicating.

Like Go, instead of sharing memory and handling state we promote the use of CSP-style concurrency using channels. This pattern brings the abstractions used on the development of distributed systems closer to the way we're used to think about communication. It also aligns well with Swift's mindset of immutability and value types. All of these things contributes to a distinct experince on the server-side Swift.

With Zewo you get:

  • Go-style concurrency
  • Synchronous APIs
  • Incredible performance
  • Safer applications
  • Scalable systems
  • Cleaner code
  • Proper error handling
  • No callback hell
  • No race conditions

Support

If you have any trouble create a Github issue and we'll do everything we can to help you. When stating your issue be sure to add enough details and reproduction steps so we can help you faster. If you prefer you can join our Slack and go to the #help channel too.

Community

We have an amazing community of open and welcoming developers. Join us on Slack to get to know us!

License

All Zewo modules are released under the MIT license. See LICENSE for details.

GitHub

https://github.com/Zewo/Zewo
Comments
  • 1. Move log timestamp to Foundation Date

    Summary

    This pull request is aimed to the issue #129 for using Foundation.Date for log timestamps

    Design decisions

    I've add a private time formatter shared instance for keeping the initialisation cost low, and set the format template to print hours, minutes, seconds and milliseconds. I don't know if you prefer additional information on the date or the time is enough.

    Reviewed by JGiola at 2016-10-05 21:41
  • 2. HTTPSClient error "Connection reset by peer" when making request

    Gist Download project

    With snapshot 2016-4-12-a on OS X, I get "Connection reset by peer" when running this code:

    import HTTPSClient
    
    let client = try HTTPSClient.Client(uri: "https://www.googleapis.com:443")
    let response = try client.get(
        "/youtube/v3/videos?part=snippet,statistics&id=1,2&key=REDACTED")
    

    The full error:

    [I] ~/work/HTTPSClient_issue                                                    
    ↪ ./.build/debug/HTTPClient_issue                                     [email protected]:36:38
    fatal error: Error raised at top level: Connection reset by peer: file /Users/buildnode/jenkins/workspace/oss-swift-package-osx/swift/stdlib/public/core/ErrorType.swift, line 59
    Current stack trace:
    0   libswiftCore.dylib                  0x00000001007376a1 swift_reportError + 145
    1   libswiftCore.dylib                  0x0000000100754a17 _swift_stdlib_reportFatalErrorInFile + 103
    2   libswiftCore.dylib                  0x000000010070a193 partial apply forwarder for Swift.(_assertionFailed (Swift.StaticString, Swift.String, Swift.StaticString, Swift.UInt, flags : Swift.UInt32) -> ()).(closure #1).(closure #1).(closure #1) + 99
    3   libswiftCore.dylib                  0x000000010070a1ef partial apply forwarder for reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> (@out ()).291 + 63
    4   libswiftCore.dylib                  0x00000001005c09bd generic specialization <preserving fragile attribute, ()> of Swift.StaticString.withUTF8Buffer <A> (invoke : (Swift.UnsafeBufferPointer<Swift.UInt8>) -> A) -> A + 349
    5   libswiftCore.dylib                  0x00000001006cf77c function signature specialization <preserving fragile attribute, Arg[1] = Owned To Guaranteed and Exploded> of Swift.(_assertionFailed (Swift.StaticString, Swift.String, Swift.StaticString, Swift.UInt, flags : Swift.UInt32) -> ()).(closure #1) + 204
    6   libswiftCore.dylib                  0x00000001006e280f partial apply forwarder for Swift.(_assertionFailed (Swift.StaticString, Swift.String, Swift.StaticString, Swift.UInt, flags : Swift.UInt32) -> ()).(closure #1) + 143
    7   libswiftCore.dylib                  0x00000001006adb9a function signature specialization <preserving fragile attribute, Arg[1] = Exploded> of Swift._assertionFailed (Swift.StaticString, Swift.String, Swift.StaticString, Swift.UInt, flags : Swift.UInt32) -> () + 218
    8   libswiftCore.dylib                  0x00000001005d6cff swift_errorInMain + 719
    9   HTTPClient_issue                    0x00000001000bd243 main + 2403
    10  libdyld.dylib                       0x00007fff962145ad start + 1
    11  ???                                 0x0000000000000001 0x0 + 1
    fish: './.build/debug/HTTPClient_issue' terminated by signal SIGILL (Illegal instruction)
    
    Reviewed by donut at 2016-04-21 17:44
  • 3. POSIX: add Regex, update Regex to swift 3, API changes

    Hi, this is not finished yet, but it's clear enough for you to begin reviewing

    • [x] update to Swift 3
    • [x] utf8 support
    • [x] convenience operators ~, ~*, ~?
    • [x] Tests for match and groups
    • [x] Tests for replace
    • [ ] API change (needs review @paulofaria)
    • [ ] get rid of one Foundation dependency (used for one method)?
    Reviewed by bosr at 2016-09-29 06:59
  • 4. [Axis] Clean up Map's API, making it more predictable and simple

    These are my suggested changes, but let's keep discussing this.

    What's in here:

    • [x] Remove ExpressibleByNilLiteral. Making Map.null == nil is confusing, and is more similar to the null pointer mechanism that Swift discourages rather than the optional pattern. Correctness > convenience in this case IMO.
    • [x] Remove get in favor of subscript
    • [x] Remove set in favor of subscript
    • [x] Remove remove in favor of subscript
    • [x] Make subscript optional
    • [x] Add asInferred method which uses type inference. It is the only generic method.
    • [ ] Reintegrate with Mapper (there were API conflicts)
    • [ ] Remove MapRepresentable in favor of just MapFallibleRepresentable. Having two similar API's is confusing, especially since being MapInitiliazable and MapRepresentable doesn't give you MapConvertible.
    • [ ] Remove unused errors from enum
    • [ ] Any ideas?

    There is now exactly one way to index map (subscript), and several ways to unbox the type (int, isInt, asInt(), asInferred):

    let map: Map = [
        "string": "hello world",
        "array": [1, 2, 3, 4, 5],
        "dictionary": [
            "string": "nested hello world",
            "array": [6, 7, 8, 9, 10]
        ]
    ]
    
    let a: Map? = map["dictionary", "array", 2]
    let b: Int? = map["dictionary", "array", 2]?.int
    let c: Int = try map["dictionary", "array", 2].map.asInt()
    let d: Int = try map["dictionary", "array", 2].map.asInferred()
    

    cc @paulofaria @robertjpayne @dreymonde

    Reviewed by Danappelxx at 2016-11-12 21:36
  • 5. Add ability to customize HTTP response error handling

    For example, HTTPFile.FileResponder simply return a 404 response on any file errors, regardless of whether its permission or the file is just a directory.

    I opened a pull request regarding this with a very in-elegant solution.

    It looks like Zewo/RecoveryMiddleware gets us halfway there.

    Reviewed by donut at 2016-04-05 20:44
  • 6. Swift build error: rename error

    Hopefully I'm just doing something wrong, but when I pull this repo and build in Linux using "swift build" the cloning of packages seems to work, but after the SSL Package is cloned, I see this error:

    swift-build: rename error: File exists (17): /src/Packages/CLibvenice -> /src/Packages/CLibvenice-0.1.0

    I also followed the steps to install the three C libs as well.

    Any ideas what I'm missing?

    Wes

    Reviewed by wfilleman at 2015-12-10 14:03
  • 7. [Reflection] Segmentation Fault, Swift Reflection

    Segmentation Fault of Swift Reflection

    I recently use swift reflection to convert json string to a struct, but got "Segmentation Fault" in runtime. As the test code is too much to write here, I committed my test code in github, can you help have a look, thanks.

    Steps to reproduce

    $uname -a Linux dev 4.4.0-34-generic #53-Ubuntu SMP Wed Jul 27 16:06:39 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

    $ swift --version Swift version 3.0 (swift-3.0.1-PREVIEW-1) Target: x86_64-unknown-linux-gnu

    $ git clone https://github.com/hikelee/SegmentationFault.git

    $ cd SegmentationFault

    $ swift build Cloning https://github.com/Zewo/Reflection.git HEAD is now at 2bc1a76 make mappable tests public on reflection Resolved version: 0.14.0 Compile Swift Module 'Reflection' (23 sources) Compile Swift Module 'Main' (1 sources) Linking ./.build/debug/Main

    $ .build/debug/Main Person(firstName: "James") Person(firstName: "James") Person(firstName: "James") Person(firstName: "James") ------ Person(firstName: "James") Person(firstName: "pb?\0\0\0\0\0a") Person(firstName: "\u{10}\u{10}\0a") Segmentation fault

    Reviewed by hikelee at 2016-10-21 05:34
  • 8. [HTTPFile] cause chunk encoding error

    When I deliver a certain file using HTTPFile.FileResponder along with either HTTPSServer or HTTPServer, it always fails delivering the whole file. Chrome reports "net:ERR_INVALID_CHUNKED_ENCODING" in its Developer Tools Network tab.

    In this gist you can see react.js file as delivered by nginx or HTTPServer. The page is super long, so it may be easier to open up the files in new tabs:

    I think I have experienced this occasionally on OS X, but it happens consistently on my 512 MB DigitalOcean VM running Ubuntu 14.04.3.

    Reviewed by donut at 2016-04-12 20:41
  • 9. Update all Zewo modules to the new 07-25 snapshot

    The plan:

    • All dependencies pointed at 0.10 (with the exception of Open-Swift/S4, which should be pointed at 0.11)
    • The version in the README updated to majorVersion: 0, minor: 10
    • The badge in the README updated to 0.10 (i.e. this badge)
    • Once the branch satisfies the requirements, a pull request is to be created (merging into master, obviously)
    • Build and run the tests locally, and fix any warnings or errors
    • Create a new tag 0.10.0

    List of relevant repositories:

    Reviewed by Danappelxx at 2016-06-14 05:56
  • 10. [HTTPClient] Client fails when Content-Length is not set

    When HTTP response doesn't set Content-Length, http and https client raises and closedStream(0 bytes) error. It should calculate total length read till the end of http server connection, when this header is not set.

    How to reproduce?

    For this response:

    HTTP/1.1 200 OK
    Date: Fri, 16 Sep 2016 16:23:17 GMT
    Connection: close
    
    test
    

    Run on the simplest http server (https://gist.github.com/vi4m/a3809caea5e4a59d27e1032f8b9657f1)

    And with this swift client code:

    
    import HTTPClient
    
    do {
        let c = try Client(url: "http://localhost:9000")
        let request = Request(method: .get, url: "/")
        var response = try c.request(request!)
    }
    catch {
        print(error)
        print("Failed.")
        exit(2)
    }
    print("Success.")
    
    

    it will fail with closedStream(0 bytes error).

    When the response is completed with "Content-Lenght: 5" http request works fine.

    Created by @vi4m

    Reviewed by paulofaria at 2016-09-18 09:29
  • 11. [PostgreSQL] Obtaining Null values from varchar/text columns in DB results in Optional("") being returned

    Optional("") returned where nil is expected

    Based on TodoBackend project (https://github.com/Zewo/TodoBackend) I did very similar PSQL store for my project. When my model contains String? fields replicating the null-allowed text or varchar columns in DB, if I insert nil values when writing it to DB I expect the nil values to be returned by the get methods as well. DB correctly has NULL values in it, but values returned by get(id) or getAll() methods are Optional("") instead of nil.

    Steps to reproduce

    1. Create a model having the String? fields and corresponding table in DB having text or varchar fields which can be NULLs.
    2. In your tests / main / whatever executable source file instantiate your model and assign nil values to fields of type String?.
    3. Insert the record using the model and store.insert(model) method.
    4. Save the value returned by insert into a variable.
    5. Compare model object created by you and model returned by insert within the PersistedEntity.

    Expected: nil values are nil values in both and comparison succeeds. Actual: nil values were replaced by Optional("")

    My code:

    func testAssetInsertion() throws {
        let original = Asset(id: "bc_id", name: "Test", frontCover: nil, data: nil, type: nil) 
        let inserted = try store.insertAsset(asset: original)
        XCTAssertEqual(inserted.model, original)
        let retrieved = try store.getAsset(id: "bc_id")
        XCTAssertEqual(retrieved!.model, original)
        let retrievedThroughGetAll = try store.getAllAssets()
        XCTAssertEqual(retrievedThroughGetAll.count, 1)
        XCTAssertEqual(retrievedThroughGetAll[0].model, original)
    }
    

    Test results:

    /home/anatoli/workspace/StorageService/Tests/StorageLayerTests/PostgreSQLEBooksStore/PostgreSQLEBooksStoreTests.swift:45: error: PostgreSQLEBooksStoreTests.testAssetInsertion : XCTAssertEqual failed: ("Asset(id: "bc_id", name: "Test", frontCover: Optional(""), data: Optional(""), type: Optional(""))") is not equal to ("Asset(id: "bc_id", name: "Test", frontCover: nil, data: nil, type: nil)") - 
    /home/anatoli/workspace/StorageService/Tests/StorageLayerTests/PostgreSQLEBooksStore/PostgreSQLEBooksStoreTests.swift:47: error: PostgreSQLEBooksStoreTests.testAssetInsertion : XCTAssertEqual failed: ("Asset(id: "bc_id", name: "Test", frontCover: Optional(""), data: Optional(""), type: Optional(""))") is not equal to ("Asset(id: "bc_id", name: "Test", frontCover: nil, data: nil, type: nil)") - 
    /home/anatoli/workspace/StorageService/Tests/StorageLayerTests/PostgreSQLEBooksStore/PostgreSQLEBooksStoreTests.swift:50: error: PostgreSQLEBooksStoreTests.testAssetInsertion : XCTAssertEqual failed: ("Asset(id: "bc_id", name: "Test", frontCover: Optional(""), data: Optional(""), type: Optional(""))") is not equal to ("Asset(id: "bc_id", name: "Test", frontCover: nil, data: nil, type: nil)")
    
    • I have implementation of insert and model very close to what is in TodoStore and related sources. So I expect it to be reproducible there. If not - please let me know and I will add more info.
    Reviewed by Cyfirr at 2016-11-02 17:58
A tool to build projects on MacOS and a remote linux server with one command

DualBuild DualBuild is a command line tool for building projects on MacOS and a remote Linux server. ##Setup Install the repository git clone https://

Dec 26, 2021
A Ruby on Rails inspired Web Framework for Swift that runs on Linux and OS X

IMPORTANT! We don't see any way how to make web development as great as Ruby on Rails or Django with a very static nature of current Swift. We hope th

Jun 12, 2022
Swift backend / server framework (Pure Swift, Supports Linux)

NetworkObjects NetworkObjects is a #PureSwift backend. This framework compiles for OS X, iOS and Linux and serves as the foundation for building power

May 30, 2022
A Swift web framework and HTTP server.
A Swift web framework and HTTP server.

A Swift Web Framework and HTTP Server Summary Kitura is a web framework and web server that is created for web services written in Swift. For more inf

Jun 19, 2022
Swift Express is a simple, yet unopinionated web application server written in Swift
Swift Express is a simple, yet unopinionated web application server written in Swift

Documentation <h5 align="right"><a href="http://demo.swiftexpress.io/">Live ?? server running Demo <img src="https://cdn0.iconfinder.com/data/icons/

May 23, 2022
Frank is a DSL for quickly writing web applications in Swift

Frank Frank is a DSL for quickly writing web applications in Swift with type-safe path routing. Sources/main.swift import Frank // Handle GET request

Apr 14, 2022
💧 A server-side Swift web framework.
💧 A server-side Swift web framework.

Vapor is a web framework for Swift. It provides a beautifully expressive and easy to use foundation for your next website, API, or cloud project. Take

Jun 22, 2022
High Performance (nearly)100% Swift Web server supporting dynamic content.

Dynamo - Dynamic Swift Web Server Starting this project the intention was to code the simplest possible Web Server entirely in Swift. Unfortunately I

Jan 29, 2022
libuv base Swift web HTTP server framework

Notice Trevi now open a Trevi Community. Yoseob/Trevi project split up into respective Trevi, lime, middlewares and sys packages at our community. If

Jan 29, 2022
A lightweight library for writing HTTP web servers with Swift

Taylor Disclaimer: Not actively working on it anymore. You can check out some alternatives Swift 2.0 required. Working with Xcode 7.1. Disclaimer: It

Feb 27, 2022
Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.

BlueSocket Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux. Prerequisites Swift Swift Open Source swift-5.1

Jun 19, 2022
SwiftCANLib is a library used to process Controller Area Network (CAN) frames utilizing the Linux kernel open source library SOCKETCAN.

SwiftCANLib SwiftCANLib is a library used to process Controller Area Network (CAN) frames utilizing the Linux kernel open source library SOCKETCAN. Th

Oct 25, 2021
Super lightweight web framework in Swift based on SWSGI

Ambassador Super lightweight web framework in Swift based on SWSGI Features Super lightweight Easy to use, designed for UI automatic testing API mocki

Mar 18, 2022
Lightweight, flexible HTTP server framework written in Swift

Hummingbird Lightweight, flexible server framework written in Swift. Hummingbird consists of three main components, the core HTTP server, a minimal we

Jun 19, 2022
FlyingFox - a lightweight HTTP server built using Swift Concurrency

Usage Credits Introduction FlyingFox is a lightweight HTTP server built using Swift Concurrency. The server uses non blocking BSD sockets, handling ea

Jun 17, 2022
🌏 A zero-dependency networking solution for building modern and secure iOS, watchOS, macOS and tvOS applications.
🌏 A zero-dependency networking solution for building modern and secure iOS, watchOS, macOS and tvOS applications.

A zero-dependency networking solution for building modern and secure iOS, watchOS, macOS and tvOS applications. ?? TermiNetwork was tested in a produc

Jun 27, 2022
Minecraft server RCON client for iOS/macOS

iRCON Minecraft server RCON client for iOS/macOS. Features Full remote console window Player list with ability to easily op, kick, ban, etc. Quickly s

Apr 5, 2022
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

Jun 27, 2022
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)

Perfect: Server-Side Swift 简体中文 Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

Jun 27, 2022