High Performance (nearly)100% Swift Web server supporting dynamic content.

Related tags

Networking Dynamo
Overview

Dynamo - Dynamic Swift Web Server

Starting this project the intention was to code the simplest possible Web Server entirely in Swift. Unfortunately I got a bit carried away adding features such as proxying and dynamic reloading of server code. Dynamo now also works on Linux, see DynamoLinux.

So.. while Dynamo can be used in an iOS application as is demonstrated in this project, the focus has turned to the server side to set up a simple framework inside which it is possible to experiment with SSL, Proxies and what you could call "Swift Server Pages" which are loadable bundles of code placed in the document hierarchy.

The Dynamo server core is based on "Swiftlets", instances implementing the DynamoSwiftlet protocol. These are presented with incoming HTTP requests from the browser and can choose to process it in any manner it chooses. The developer passes in an array of swiftlet instances combining the features and applications desired on server startup.

    @objc public protocol DynamoSwiftlet {

        @objc func present( httpClient: DynamoHTTPConnection ) -> DynamoProcessed    
    }

    @objc public enum DynamoProcessed : Int {
        case
            NotProcessed, // does not recognise the request
            Processed, // has processed the request
            ProcessedAndReusable // "" and connection may be reused in HTTP/1.1
    }

For further information about the classes and protools that make up Dynamo please consult the jazzy docs here. The Swiftlets included in the framework are as follows:

DocumentSwiftlet

The default swiftlet to serve documents from ~/Sites/host:port or the applications resources directory for iOS.

ProxySwiftlet, SSLProxySwiftlet

Dynamo can act as a proxy server logging what can be a surprising about of traffic from your browser. To use the proxy, run OSX target and set your proxy to localhost:8080.

ApplicationSwiftlet, SessionSwiftlet

ApplicationSwiftlet is the abstract superclass of all "application" swiftlets parsing browser GET and POST parameters and any Cookies. SessionSwiftlet adds the ability to have an application Swiftlet created separately for each unique web user using Cookies.

BundleSwiftlet, ServerPagesSwiftlet

BundleSwiftlet, loads a swiftlet from a bundle with extension ".ssp" in an OSX application's resources. A simple python script can generate the Swift source for the bundle from a ".shtml" mixing HTML and Swift language. The ServerPagesSwiftlet takes this a step further where the bundle is loaded from the document root for the sever when used from the command line. If the bundle is updated for new functionality, provided it contains the "AutoLoader.m" stub the new code will be "swizzled" into operation.

ExampleAppSwiftlet, TickTackToe, NumberGuesser

The ExampleAppSwiftlet is used in the tests for checking character encoding in GET and POST form submission. TickTackToe is an example .ssp application in a bundle target. NumberGuesser is implemented as a .shtml template compiled into swift code by the Utilities/sspcompiler.py script. Changes made to these Swiftlets will take effect when you reload the page after a project build.

DynamoWebServer, DynamoSSLWebServer severs.

Consult OSX/AppDelegate.swift or iOS/AppDelegate.m of the OSX and iOS targets for how to create instances of these classes.

    // create shared swiftlet for server applications
    let exampleTableGenerator = ExampleAppSwiftlet( pathPrefix: "/example" )
    let tickTackToeGame = BundleSwiftlet( pathPrefix: "/ticktacktoe", bundleName: "TickTackToe" )!

    let logger = {
        (msg: String) in
        println( msg )
    }

    // create non-SSL server/proxy on 8080
    DynamoWebServer( portNumber: serverPort, swiftlets: [
        LoggingSwiftlet( logger: dynamoTrace ),
        exampleTableGenerator,
        tickTackToeGame,
        SSLProxySwiftlet( logger: logger ),
        ProxySwiftlet( logger: logger ),
        ServerPagesSwiftlet( documentRoot: documentRoot ),
        DocumentSwiftlet( documentRoot: documentRoot )
    ] )

Creating the instance is sufficient for the server to start and run in it's own threads. There is an additional "Daemon" target creating a command line version of the sever which should be run from inside the DynamoApp.app's resources so it can find the Dynamo framework.

The Dynamo framework has a .podspec file so it can be brought into your project with the following:

    use_frameworks!

    target "<project>" do

        pod 'Dynamo', :git => 'https://github.com/johnno1962/Dynamo.git'

    end

Running an SSL server requires set of certificates which can be generated using code slightly modified from robbiehanson's CocoaHTTPServer under a BSD license contained in the Utilities/DDKeyChain.[hm] source.

Performance

Testing with JMeter has shown Dynamo is capable of serving:

40,000 requests per minute for a static file in the documents directory (25 threads)

40,000 requests per minute for the NumberGuesser which reuses connections (see below)

18,000 requests per minute for TickTckToe which does not reuse connections (see below)

Reusing connections is important for large numbers of requests from the same client. This is achieved by using a single DynamoHTTPConnection.response( html ) method call rather than individual calls to method DynamoHTTPConnection.print( html ).

As ever, announcements of major commits to the repo will be made on twitter @Injection4Xcode.

MIT License

Copyright (C) 2015 John Holdsworth

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You might also like...
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

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

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

A Swift Multiplatform Single-threaded Non-blocking Web and Networking Framework
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

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

Minimal web framework and middleware for Swift

Kunugi Kunugi(椚) is minimal web framework and middleware systems for Swift. This is inpired by Node.js' Koa. Kunugi doesn't provide http server its se

A web API client in Swift built using Async/Await

Get A modern web API client in Swift built using Async/Await and Actors. let cli

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

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

Comments
  • SSL interception through ProxySwiftlet or other means

    SSL interception through ProxySwiftlet or other means

    I noticed that SSLProxySwiftlet (great name, Swiftlet, btw :) ) performs TLS tunneling to/from the remote server. I was wondering, if there was a way in Dynamo to intercept TLS connections (i.e. mitmproxy)? From reading about how mitmproxy works, I've already implemented generating a cert on the fly. I've also looked into how DynamoSSLWebServer works--but I can't seem to wrap my head around how to sign an incoming HTTPS request through the proxy. I imagine once I'm able to sign it with my own cert/key, I can use the present() method to intercept/inject what I want.

    opened by satishmaha 2
Owner
John Holdsworth
Add a bio
John Holdsworth
💧 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 2, 2023
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 Jan 6, 2023
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
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
A type-safe, high-level networking solution for Swift apps

What Type-safe network calls made easy Netswift offers an easy way to perform network calls in a structured and type-safe way. Why Networking in Swift

Dorian Grolaux 23 Apr 27, 2022
YTKNetwork is a high level request util based on AFNetworking.

YTKNetwork What YTKNetwork is a high level request util based on AFNetworking. It's developed by the iOS Team of YuanTiKu. It provides a High Level AP

猿辅导技术团队 6.5k Jan 6, 2023
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 Jan 6, 2023
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
Robust Swift networking for web APIs

Conduit Conduit is a session-based Swift HTTP networking and auth library. Within each session, requests are sent through a serial pipeline before bei

Mindbody 52 Oct 26, 2022
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