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

Overview

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.

Comments
  • Move log timestamp to Foundation Date

    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.

    opened by JGiola 17
  • HTTPSClient error

    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                                     0@10: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)
    
    opened by donut 14
  • POSIX: add Regex, update Regex to swift 3, API changes

    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)?
    opened by bosr 11
  • [Axis] Clean up Map's API, making it more predictable and simple

    [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

    opened by Danappelxx 9
  • Add ability to customize HTTP response error handling

    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.

    opened by donut 9
  • Swift build error: rename error

    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

    opened by wfilleman 9
  • [Reflection] Segmentation Fault, Swift Reflection

    [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

    opened by hikelee 8
  • [HTTPFile] cause chunk encoding error

    [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.

    opened by donut 8
  • Update all Zewo modules to the new 07-25 snapshot

    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:

    help wanted 
    opened by Danappelxx 7
  • [HTTPClient] Client fails when Content-Length is not set

    [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

    opened by paulofaria 6
  • [PostgreSQL] Obtaining Null values from varchar/text columns in DB results in Optional(

    [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.
    opened by Cyfirr 5
  • Is this Project Still Alive AND KICKING?

    Is this Project Still Alive AND KICKING?

    I have been experimenting with swift as a replacement for nodejs micro services. It seems that the server side Swift world has cooled off a lot. As best I can tell only Vapor is in active development. But I’m not sure. Is Zewo still being ACTIVELY developed or will it?

    opened by petergi 0
Releases(0.16.1)
Owner
Zewo
Open source libraries for modern server software.
Zewo
A small, lightweight, embeddable HTTP server for Mac OS X or iOS applications

CocoaHTTPServer CocoaHTTPServer is a small, lightweight, embeddable HTTP server for Mac OS X or iOS applications. Sometimes developers need an embedde

Robbie Hanson 5.5k Jan 7, 2023
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

Saulius Grigaitis 2k Dec 5, 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

Alsey Coleman Miller 258 Oct 6, 2022
PillowTalk - An iOS & SwiftUI server monitor tool for linux based machines using remote proc file system with script execution.

An iOS & SwiftUI server monitor tool for linux based machines using remote proc file system with script execution.

Lakr Aream 416 Dec 16, 2022
GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS & tvOS apps.

GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS & tvOS apps. It was written from scr

Pierre-Olivier Latour 6.3k Dec 27, 2022
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

Kitura 7.6k Dec 27, 2022
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/

Crossroad Labs 850 Dec 2, 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

Kyle Fuller Archive 376 Jan 3, 2023
💧 A server-side Swift HTTP web framework.

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

Vapor 22.4k Jan 3, 2023
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

leeyoseob 46 Jan 29, 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

John Holdsworth 68 Jul 25, 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

Jorge Izquierdo 925 Nov 17, 2022
🪶 Feather is a modern Swift-based content management system powered by Vapor 4.

Feather CMS ?? ?? Feather is a modern Swift-based content management system powered by Vapor 4. ?? Click to join the chat on Discord. Requirements To

Phu Huynh 0 Oct 20, 2021
HTTP Implementation for Swift on Linux and Mac OS X

Swift HTTP Server Simple HTTP implementation for Swift using POSIX socket API. Running on Mac OS X and Linux. For Mac users: You can install new Swift

Huy 451 Jul 28, 2022
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

PerfectlySoft Inc. 13.9k Dec 29, 2022
A minimal, fast and unopinionated web framework for Swift

![Fire Image] (http://i.imgur.com/1qR6Nl4.png) Blackfire An extremely fast Swift web framework ?? Getting Started If you're familiar with express.js t

Elliott Minns 908 Dec 2, 2022
A Swift Multiplatform Single-threaded Non-blocking Web and Networking Framework

Serverside non-blocking IO in Swift Ask questions in our Slack channel! Lightning (formerly Edge) Node Lightning is an HTTP Server and TCP Client/Serv

SkyLab 316 Oct 6, 2022
Sinatra-like DSL for developing web apps in Swift

Swiftra Swiftra is a library that provides DSLs like Sinatra. System Requirements DEVELOPMENT-SNAPSHOT-2016-02-08-a Example See swiftra-example. impor

Shun Takebayashi 262 Jun 29, 2022
Simple server APIs in Swift

Simple server APIs in Swift

null 4 Apr 25, 2022