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 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
💧 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

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

Envoy 170 Nov 15, 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 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
Swift HTTP server using the pre-fork worker model

Curassow Curassow is a Swift Nest HTTP Server. It uses the pre-fork worker model and it's similar to Python's Gunicorn and Ruby's Unicorn. It exposes

Kyle Fuller Archive 397 Oct 30, 2022
Tiny http server engine written in Swift programming language.

What is Swifter? Tiny http server engine written in Swift programming language. Branches * stable - lands on CocoaPods and others. Supports the latest

null 3.6k Jan 3, 2023
Meet Corvus, the first strongly declarative server-side framework.

Corvus Corvus is the first truly declarative server-side framework for Swift. It provides a declarative, composable syntax which makes it easy to get

null 42 Jun 29, 2022
Evented I/O streams for Swift

Noze.io "Das Haus das Verrückte macht." Noze.io is an attempt to carry over the Node.js ideas into pure Swift. It uses libdispatch for event-driven, n

The Noze Consortium 305 Oct 14, 2022
Lightweight library for web server applications in Swift on macOS and Linux powered by coroutines.

Why Zewo? • Support • Community • Contributing Zewo Zewo is a lightweight library for web applications in Swift. What sets Zewo apart? Zewo is not a w

Zewo 1.9k Dec 22, 2022
Lightweight library for web server applications in Swift on macOS and Linux powered by coroutines.

Why Zewo? • Support • Community • Contributing Zewo Zewo is a lightweight library for web applications in Swift. What sets Zewo apart? Zewo is not a w

Zewo 1.9k Dec 22, 2022
Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.

Venice provides structured concurrency and CSP for Swift. Features Coroutines Coroutine cancelation Coroutine groups Channels Receive-only chan

Zewo 1.5k Dec 22, 2022
SwiftCoroutine - Swift coroutines for iOS, macOS and Linux.

Many languages, such as Kotlin, Go, JavaScript, Python, Rust, C#, C++ and others, already have coroutines support that makes the async/await pattern i

Alex Belozierov 808 Dec 1, 2022
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Envoy 540 Dec 15, 2022
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Envoy 540 Dec 15, 2022
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Envoy 540 Dec 15, 2022
A spatial analysis library written in Swift for native iOS, macOS, tvOS, watchOS, and Linux applications, ported from Turf.js.

Turf for Swift ?? ?? ?? ?? ⌚️ A spatial analysis library written in Swift for native iOS, macOS, tvOS, watchOS, and Linux applications, ported from Tu

Mapbox 187 Dec 19, 2022
Interactive, thoroughly customizable maps in native Android, iOS, macOS, Node.js, and Qt applications, powered by vector tiles and OpenGL

Mapbox GL Native A C++ library that powers customizable vector maps in native applications on multiple platforms by taking stylesheets that conform to

Mapbox 4.2k Jan 9, 2023
TraceLog is a highly configurable, flexible, portable, and simple to use debug logging system for Swift and Objective-C applications running on Linux, macOS, iOS, watchOS, and tvOS.

Please star this github repository to stay up to date. TraceLog Introduction TraceLog is a highly configurable, flexible, portable, and simple to use

Tony Stone 52 Oct 28, 2022
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://

Operator Foundation 0 Dec 26, 2021