Dynamic websites

On this page

Two ways to serve dynamic content:

In-process SwiftReverse proxy
WhatYour handlers run inside the server: Router routes, WebSocketUpgrade endpoints, any HTTPHandlerThe server forwards path prefixes to apps on localhost (Go, Node, Python, Rails, another Swift server…) over HTTP/1.1 or a Unix socket
BuildYour own Swift package composing PhotonHTTP's productsThe shipped executable plus a proxy key; no Swift code
Cost per requestA function callTwo loopback round trips (about 18 µs added, see performance)
Good forAPIs and real-time endpoints written in SwiftExisting apps in any language; isolating an app in its own process

Both mix freely with static files: static at /, dynamic under /api.

In-process with Router

let router = try Router {
    GET("/api/users/:id") { request, context in
        guard let id = context.params.decimal("id") else { return HTTPResponse(status: .badRequest) }
        return json(#"{"id": \#(id)}"#)
    }
    POST("/api/users") { request, _ in
        let body = try await request.body.collect(upTo: 64 * 1024)   // bounded; 413-style limit is yours
        …
    }
    Group("/api/admin") {
        GET("/stats") { _, _ in … }
        Route("/files/*path", methods: [.get, .put]) { _, context in
            let path = context.params["path"] ?? ""
            …
        }
    }
}
let server = Server(listeners: [listener], protocols: [HTTP1()]) {
    router              // misses fall through to the files
    files
}

A complete, runnable version (with json(_:) and signal handling) is Examples/custom-server, walked through in Choosing components.

Router rules:

Handler rules (the request-path contract):

WebSockets

let chat = WebSocketUpgrade(path: "/ws",
                            origin: { $0.origin == "https://example.com" },  // stop cross-site use
                            subprotocol: { $0.offeredSubprotocols.first }) { socket, request in
    for await message in socket.messages {
        switch message {
        case .text(let text): try await socket.send(text: "echo: \(text)")
        case .binary: try await socket.send(message)
        }
    }
}
let server = Server(listeners: listeners, protocols: [HTTP2(configuration: h2), HTTP1()]) {
    chat
    router
    files
}

Reverse proxy to localhost apps

The executable forwards mounted path prefixes to upstream HTTP/1.1 apps and serves everything else from files. Example with the Go app in Examples/go-api (stdlib only; GET /api/health, CRUD on /api/items, GET /api/echo shows the forwarded headers):

{
  "root": "Public",
  "proxy": [
    { "path": "/api", "upstream": "http://127.0.0.1:9000",
      "timeouts": { "connect": 2, "response": 30 } }
  ]
}
(cd Examples/go-api && go run . -addr 127.0.0.1:9000) &
.build/release/photon --config Root/http-config.proxy.json   # needs scripts/make-test-identity.sh (TLS)
curl http://127.0.0.1:8080/api/health        # {"status":"ok"}
curl http://127.0.0.1:8080/api/echo          # shows X-Forwarded-For/Proto/Host/Prefix
curl http://127.0.0.1:8080/                  # Root/Public/index.html

How requests flow:

Proxy mount reference

proxy is an array of mounts (a single object is accepted). The same path twice for overlapping hosts is an error.

KeyTypeDefaultMeaning
pathstring"/"Prefix starting with /
host / hostsstring / arrayall hostsOnly for these Host names (one of the two)
upstream / upstreamsstring / array (required)–http://HOST:PORT[/base] or unix:/path. Several upstreams are used round-robin, skipping unhealthy ones (one of the two)
stripPrefixboolfalseRemove the mount path before forwarding (/api/x → /x)
preserveHostboolfalseSend the client's Host instead of the upstream's
forwardedHeadersstring"x-forwarded"x-forwarded (X-Forwarded-For/Proto/Host/Prefix), forwarded (RFC 7239), both, none
trustedProxiesarray[]IPs or CIDR ranges ("10.0.0.0/8", "::1") whose forwarded fields are kept and appended to; from anyone else they are replaced
rewriteLocationbooltrueRewrite upstream Location and Content-Location into the client's URL space
rewriteCookiePathboolfalseWith stripPrefix or a base path, rewrite Set-Cookie Path (Path=/ → Path=/api)
websocketboolfalseTunnel WebSocket / Upgrade requests
timeouts.connectseconds, 0/null off10Connecting to the upstream
timeouts.responseseconds, 0/null off60Request sent → response head
timeouts.idleseconds, 0/null off60Between body reads; also closes an idle tunnel (tunnels default to 300 s without it)
timeouts.totalseconds, 0/null offnoneWhole exchange
retriesinteger 0–101Extra attempts on the next upstream after a connect failure, idempotent methods only
health.failuresinteger 0–10003Consecutive failures that mark an upstream down (0: passive tracking off)
health.cooldownseconds10How long it stays down
health.pathstringnoneActive check: GET path every interval; status < 500 is healthy
health.intervalseconds > 010Active check period
pool.maxConnectionsinteger0 (no limit)Connections per upstream; more requests queue
pool.queueinteger256Requests that may wait for a connection; a full queue gets 503
pool.queueTimeoutseconds > 010Longest wait in the queue (503 after)
pool.maxIdleinteger16Kept-alive idle connections per upstream. Raise it to your expected concurrency: with more concurrent requests than maxIdle, extra connections are opened and closed per request
pool.idleTimeoutseconds60Idle connections closed after this (0 keeps them)

For all four timeouts keys, 0 or null turns that limit off and a missing key keeps the default (total is off by default). Values are capped at one year. For long-polling or streaming upstreams (server-sent events, long downloads), set "idle": 0 and "response": 0 (or large values); idle: 0 also leaves upgraded tunnels without an idle limit.

Apache mod_proxy → PhotonHTTP

Apacheproxy mount
ProxyPass /api http://127.0.0.1:9000/api{"path": "/api", "upstream": "http://127.0.0.1:9000"}
ProxyPass /api/ http://127.0.0.1:9000/{"path": "/api", "upstream": "http://127.0.0.1:9000", "stripPrefix": true}
ProxyPass /app http://127.0.0.1:9000/v2{"path": "/app", "upstream": "http://127.0.0.1:9000/v2", "stripPrefix": true}
ProxyPassReverse"rewriteLocation": true (default)
ProxyPassReverseCookiePath"rewriteCookiePath": true
ProxyPreserveHost On"preserveHost": true
RequestHeader set X-Forwarded-Proto …automatic with "forwardedHeaders": "x-forwarded" (default)
RemoteIPTrustedProxy"trustedProxies": ["10.0.0.0/8"]
<Proxy balancer://…> + BalancerMember"upstreams": [ … ] (round-robin, unhealthy members skipped)
ProxyTimeout, connectiontimeout=, timeout="timeouts": {"connect": …, "response": …, "idle": …}
retry= on a worker"health": {"cooldown": …}
max= on a worker"pool": {"maxConnections": …}
ProxyPass /ws ws://… (mod_proxy_wstunnel)"websocket": true
ProxyPass … unix:/path.sock|http://localhost/"upstream": "unix:/path.sock"
ProxyPass inside a <VirtualHost>hosts[].proxy, or "host"/"hosts" on a top-level mount
<Location /admin> + AuthType Basic"auth": [{"paths": ["/admin"], "basic": …}]
ProxyPass to https://not supported: run the app on HTTP on localhost or a Unix socket

System 1 decision server (Laya)

laya-go's laya-server runs Laya, a System 1 decision model, on the Mac's GPU with Metal and serves POST /predict ({"state": …, "questions": {…}} → {"answers": {…}}, or a "batch" of states), GET /health and GET /stats. It has no authentication, so keep it on loopback (--host 127.0.0.1 --port 8000) and put it behind a proxy mount, with the prefix stripped so /laya/predict reaches /predict:

{
  "root": "public",
  "proxy": [
    { "path": "/laya", "upstream": "http://127.0.0.1:8000", "stripPrefix": true,
      "timeouts": { "connect": 2, "response": 60 },
      "pool": { "maxIdle": 8 } }
  ],
  "auth": [ { "paths": ["/laya"], "tokens": [{ "name": "game", "sha256": "…" }] } ]
}

laya-server loads the model before it starts listening, so a request during its startup gets a fast 502, not a hang. A deployment that serves a game from one Mac and asks a laya-server on another over Tailscale is in Examples/parallax-gordon/README.md.

In-process with LayaKit (when it can answer)

Not runnable yet. LayaKit, the Swift + Metal port of laya-go, is bootstrapped: it compiles the Metal shaders and loads the fixtures, but its LayaModel is a placeholder that cannot answer questions. The sketch below uses the API planned in laya-swift's docs/swift-port.md (LayaModel.load, predict, LayaState, NamedQuestion), which may change. LayaKit is not a dependency of PhotonHTTP; it would be a dependency of your own server package.

Design:

import Foundation
import HTTPCore
import LayaKit          // your package's dependency, not PhotonHTTP's
import Router
import Synchronization

/// Admission control: at most `limit` predictions in flight; the rest get 503.
final class Gate: Sendable {
    private let inFlight = Mutex(0)
    let limit: Int
    init(limit: Int) { self.limit = limit }
    func enter() -> Bool { inFlight.withLock { n in guard n < limit else { return false }; n += 1; return true } }
    func leave() { inFlight.withLock { $0 -= 1 } }
}

let model = try await LayaModel.load(LayaOptions())      // once, before the server starts
let gate = Gate(limit: 32)

let laya = try Router {
    POST("/laya/predict") { request, _ in
        guard gate.enter() else { return HTTPResponse(status: .serviceUnavailable) }
        defer { gate.leave() }
        let body = try await request.body.collect(upTo: 1 << 20)
        let (state, questions) = try decodePredictRequest(body)   // your JSON → LayaState, [NamedQuestion]
        let result = try await model.predict(state, questions)    // hops to the actor; one GPU pass
        return json(encodeAnswers(result))                        // laya-go's wire format
    }
    GET("/laya/health") { _, _ in json(#"{"ok": true}"#) }
}
// Server(…) { laya; files } as in Examples/custom-server.

Until LayaKit answers, use the reverse-proxy setup above: the HTTP contract is the same, so a client does not change when the model moves in-process.

Production checklist