acb's technical journal

Malimbe: an asynchronous server-side web framework in Swift

Recently, I have been experimenting with the open-source beta of Swift for Linux, and in particular looking into its potential as a language for server-side web applications. As such, I present the first draft of my experimental server-side web framework, Malimbe.

Malimbe (named after several species of African weaver bird) is written in Swift and will build on Linux; no attempt has yet been made to make it work on OSX, though it would certainly be possible. The main influences on Malimbe's design have been various Python/WSGI-based frameworks (mainly Pylons/Pyramid) and the Play framework in Scala (though Malimbe is a lot more minimal at this stage). The key design decisions of Malimbe, as it currently stands, are:

The main source file of a Malimbe web application, as it stands, constructs the chain of request handler, and creates a HTTPServer object (passing the top of this chain to it); requests propagate down the chain until they are handled; at the bottom is typically the Router request handler, which matches methods and paths, extracting arguments from paths, and calling the appropriate handler for each path. This might well look something like:

func itemPageHandler(request: HTTPRequest, args:[String:String]) -> Future<HTTPResponse> {
    let id = args["id"] ?? ""
    // make the item page here...
}

let router = Router(routes:[
	Router.Get("/items/",    handler:itemsListHandler),
	Router.Get("/items/:id", handler:itemPageHandler),
])

let staticFiles = StaticFileRequestHandler(pathPrefix: "/static/", staticDir:appRelativePath("StaticFiles/"), next:router)

let server = HTTPServer(handler: staticFiles)

do {
    try server.start(9999)
    print("started on 9999")

    while(true) {
        NSRunLoop.mainRunLoop().runUntilDate(NSDate.distantFuture())
    }
} catch {
    print("error: \(error)")
}

Malimbe currently has a few request handlers: the path-matching Router shown above; StaticFileRequestHandler, which can conveniently serve static files (such as stylesheets and JavaScript) from a local directory under a certain path, along with a HTTP Basic Authentication middleware; others will be added in future.

HTMLRenderable

Malimbe also has a simple set of objects for generating HTML in Swift code. This, Swiftily enough, has a protocol at its centre, the HTMLRenderable protocol, which allows objects to return HTML representations of them:

public protocol HTMLRenderable {
    /** Return a HTML representation of this object as a String */
    var asHTML: String { get }
}

The Swift String type has been extended to be HTMLRenderable; a string rendered asHTML will be quoted, with angle brackets replaced with &lt; and &gt; so that its contents are displayed as they are. If you wish to pass HTML markup back, there is a HTMLLiteral object you can wrap it in, which renders without any quoting. However, in most cases, you will want to create tags using the HTMLTag type, a HTMLRenderable representing a single tag and its contents (which may include zero or more HTMLRenderables within the tag), like so:

HTMLTag.DIV([
    HTMLTag.SPAN(HTMLTag.B(self.name), "says:", class:"itemtop"),
    HTMLTag.DIV(self.text, class:"itembody")
], class:"guestbookitem")

(The tag's contents are the first rather than last parameters; this is because of quirks in Swift's handling of variadic arguments.)

Of course, since HTMLRenderable is a protocol, there is every reason to extend your data types to implement it, which then allows you to insert them directly in the markup:

extension Item: HTMLRenderable {
    var asHTML: String {
        return HTMLTag.P(
            "Item ", HTMLTag.B(self.id), "(\(self.name))"
        , class: "item").asHTML
    }
}

The state of the framework

Malimbe is an experimental framework, still in an early stage of development. Many pieces that one would expect in a full stack are missing (notably any support for access to databases or web-based APIs). Some of these may be developed separately as other projects and imported as dependencies into Malimbe-based projects, though ideally, Malimbe would integrate them into its design. (For example, once a database framework exists, it would be the intention for it to be wrapped in an asynchronous interface that returns Futures of results.) Other components (such as session middleware, templating libraries, and a configuration system) are also missing at this stage.

Also, because Swift support on Linux is still immature, Malimbe applications will probably not be performant at this stage. For one, at the time of writing, there was no stable Linux port of libdispatch (Apple's concurrency framework, also known as Grand Central Dispatch); Malimbe uses a workaround from a Swift package named NSLinux which fakes this by spawning a thread for each dispatched block; this is obviously not something one would want on a heavily loaded production server. However, once libdispatch is ready, Malimbe will not require significant changes to use it.

Malimbe is available on GitHub, and is distributed under the Apache Licence (i.e., it may be used freely, as long as acknowledgement is provided).

There are 1 comments on "Malimbe: an asynchronous server-side web framework in Swift":

Posted by: Christian

Thu Feb 25 13:16:01 2016

Amazing stuff, I'm starting with Server Side Swift as well, and this is just what I needed ! thanks :)

Want to say something? Do so here.

Post pseudonymously

Display name:
URL:(optional)
To prove that you are not a bot,
please enter the text in the image on the right
in the field below it.

Your Comment:

Please keep comments on topic and to the point. Inappropriate comments may be deleted.

Note that markup is stripped from comments; URLs will be automatically converted into links.