No description
  • Swift 94.2%
  • Shell 3.2%
  • JavaScript 2.1%
  • Nushell 0.5%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-11-10 21:52:25 -05:00
docs Handoff: C2 bench stopped, state recorded 2026-11-03 20:05:49 -05:00
Examples/TodoApp Code-review pass: byte-level JS string escaping, mandatory nonce signer, one-shot reply builder, odd-quote attribute trap 2026-11-10 21:52:25 -05:00
loadtest Colocated load numbers, profile.sh bench mode, slow-reader sizing notes, handoff 2026-11-03 20:02:53 -05:00
scripts Example app Phase B (B1-B5): sessions, CSRF, same-origin assets, filters, validation, end-to-end tests 2026-11-03 19:44:33 -05:00
Sources Code-review pass: byte-level JS string escaping, mandatory nonce signer, one-shot reply builder, odd-quote attribute trap 2026-11-10 21:52:25 -05:00
Tests Code-review pass: byte-level JS string escaping, mandatory nonce signer, one-shot reply builder, odd-quote attribute trap 2026-11-10 21:52:25 -05:00
.gitignore Serialize SSE frames by hand: one buffer per broadcast, byte-wise split 2026-10-14 11:19:32 -04:00
.swift-format format 2026-10-15 09:24:18 -04:00
AGENTS.md Make a hung test run name its stuck tests; add AGENTS.md and a durable local-agent launcher 2026-11-03 19:00:19 -05:00
Package.resolved Add DatastarElementary: typed Elementary builders for core data-* attributes 2026-10-27 20:24:10 -04:00
Package.swift Stream zstd from the fan-out; negotiate zstd > br; refuse identity streams (L4b) 2026-11-03 19:19:03 -05:00
README.md Script nonces from the first load; swift-crypto HMAC; README for signals reading and execute-script 2026-11-10 21:00:27 -05:00

swift-datastar

A Swift package with the server side of a Datastar app, plus a todos app in pure Swift that uses it. Hummingbird 2 serves it, Elementary renders the HTML, SQLiteNIO stores the data, and Datastar drives the frontend from a CDN. The kit writes the SSE events itself. There is no build step and no client JavaScript beyond the Datastar bundle.

The root package is SwiftDatastar, with six library products.

Product What it holds
SwiftBrotli Streaming brotli encoder over libbrotlienc and its tuning (BrotliSettings). No framework dependencies.
SwiftZstd Streaming zstd encoder over libzstd and its tuning (ZstdSettings). No framework dependencies.
DatastarCore The wire SDK (Datastar.patchElements, Datastar.executeScript and friends), StreamEncoding, and ViewFanout, which delivers frames to open streams and compresses them once per group of clients. No Hummingbird.
SQLiteServerKit One writer connection behind a group-commit WriteBatcher, a reader pool, and the pragma set. SQLiteServer is a ServiceLifecycle service.
DatastarElementary Typed data-* attribute builders for Elementary views.
DatastarHummingbird DatastarView (page or stream per request, coalesced re-renders, heartbeats), request negotiation (zstd > br, identity streams refused by default), one-shot signal and script replies (Response.datastarSignals, Response.datastarScript), request.datastarSignals(as:) for reading the signals a client sent, and CompressionMiddleware.

The todos app lives in Examples/TodoApp as its own package with a path dependency on ../...

Use it in your project

dependencies: [
  .package(url: "git@git.animeteamspeak.moe:ginjiruu/swift-datastar.git", from: "1.0.0"),
  .package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "2.0.0"),
],
targets: [
  .executableTarget(
    name: "App",
    dependencies: [
      .product(name: "DatastarHummingbird", package: "swift-datastar"),
      .product(name: "SQLiteServerKit", package: "swift-datastar"),
    ]
  )
]

Wiring an app looks like this.

let db = try await SQLiteServer.open(path: "app.db", logger: logger)
let view = DatastarView(state: AppState.self) { state in
  AppPage(state).render()
}

let router = Router()
router.middlewares.add(CompressionMiddleware())
router.get("/") { request, _ in
  try await view.handle(request) { try await AppState.read(db.readers) }
}
router.post("/things") { request, context in
  try await db.writer.submit { connection in /* INSERT ... */ }
  await view.invalidate { try await AppState.read(db.readers) }
  return Response(status: .noContent)
}

let app = Application(router: router, services: [db, view], logger: logger)
try await app.runService()

Both db and view go into services. The database runs its write batcher there, and the view sends heartbeats to open streams. Leave the view out and streams still work, but idle ones get no heartbeats and may be cut by a proxy. runService() adds SIGINT and SIGTERM handling. On shutdown the HTTP server stops first and every open stream ends, so browsers reconnect to the next process. Then the view stops and refuses late joiners, and last the database commits whatever writes are still queued.

Run the example

cd Examples/TodoApp
swift run App
open http://localhost:8080

The SQLite database lands in todos.db next to the process. Delete it to reset, or keep it: an older database is migrated on startup. Configuration comes from the environment (AppConfig lists every variable): HOST, PORT, DB_PATH, COALESCE_MS, ALLOW_IDENTITY_STREAMS (stream uncompressed, for curl) and SECURE_COOKIES (behind HTTPS, use a __Host-sid cookie).

The example is a library, TodoKit, plus a three-line App executable, so swift test in Examples/TodoApp runs the same application end to end over HTTP.

The shape of it

Pseudo-CQRS, straight from The Tao of Datastar. The view is one endpoint, and commands are plain writes.

Route Purpose
GET / Static shell for browsers; for Datastar, the view stream (?filter=active or done picks a filtered view)
POST /todos Insert a todo; replies with signals for the acting client only
POST /todos/:id/toggle Flip done, 204
POST /todos/:id/title Rename; a duplicate title replies with an error signal and changes nothing
DELETE /todos/:id Delete a todo, 204
GET /examples Index of the examples
GET /simple A hand-rolled stream that pushes a tick every second, without DatastarView
GET /button One-shot patches in plain responses: a whole element by id, a targeted selector + mode: inner patch, and an execute-script reply carrying the session's CSP nonce
GET /assets/… datastar.js (vendored v1.0.4, cached forever), its source map, the stylesheet

A browser navigation gets a static shell, encoded once and revalidated with an ETag. Its data-init opens the view stream on the same URL, and the stream's first frame fills <main id="morph">. The server tells the two apart by the datastar-request header Datastar adds to every request it makes, and both responses carry Vary: datastar-request. Commands return no HTML. After a write commits, the route calls view.invalidate. The view waits one coalesce window (10 ms by default), reads the state once in one read transaction, renders once per distinct view (one per filter), and hands each frame to its ViewFanout. Every open stream updates, including the one in the tab that made the change.

A stream that joins a view with no frame yet gets one without waiting for a write. Its page read goes through the same coalescer as invalidate, so it lands within one coalesce window and can never deliver older state after newer state.

Updates are fat morphs. Each change sends the whole main as one datastar-patch-elements event, and Datastar's morph diffs it into the live DOM. There is no fragment targeting, no element ids to keep in sync, no partial-state bookkeeping. Signals never ride a view frame, since every subscriber shares it. What belongs to the acting client alone (its cleared input, a validation error, an "added" notice) comes back as signals in the reply to its own request, and _-prefixed signals are never sent up. A command reads the client's own signals with request.datastarSignals(as:): the datastar query parameter for GET and DELETE, the JSON body for everything else. When a per-client reply must do a one-shot browser effect, Response.datastarScript pushes a <script> that removes itself after running, and Datastar.redirect / Datastar.replaceURL are prebuilt scripts of that shape. Scripts ride these one-shot replies only: a view frame is shared by every subscriber, and one client's nonce cannot ride compressed bytes the others receive. One delegated pointerdown listener on the list handles every row.

Every response carries a strict CSP (same-origin scripts, styles and connections, plus 'unsafe-eval' because Datastar compiles its expressions with Function), nosniff, no-referrer and X-Frame-Options: DENY. The first GET sets a random 160-bit session cookie, and every response tied to a session also lists a per-session 'nonce-…' script source, derived as HMAC-SHA256 of the sid under a process secret, which is what a server-pushed script carries so its page will run it. A command needs that cookie and Sec-Fetch-Site: same-origin, or it gets 403. Bodies over 4 KB get 413.

Streams

A stream request is answered in zstd when the client accepts it (every current browser does), else brotli. A client that accepts neither gets 406 Not Acceptable, because an uncompressed stream turns the compression ratio into an amplification lever. DatastarView(allowIdentityStreams: true) lifts that for curl debugging. ViewFanout compresses each update once per generation of same-encoding clients and hands the same bytes to every client in it. Neither zstd nor brotli streams can be joined mid-stream, so a late joiner replays the open generation of its encoding from byte 0. Replay is capped at 64 frames and 1 MiB of uncompressed frames by default. Past either cap the generation is sealed, and the next joiner starts a fresh one seeded with the latest frame. A client that falls 64 frames behind is evicted. Its stream ends and Datastar reconnects it at the latest state. The kit never drops single frames, because a skipped frame would desync a shared decoder. Heartbeats are SSE comment frames (:), every 15 s by default, below the 30 to 60 s idle timeouts common in proxies.

The SDK

Every official Datastar SDK reduces to a few event writers (see PatchElements and PatchSignals in datastar-go). Sources/DatastarCore/Datastar.swift is the Swift equivalent. Each function appends one complete SSE frame to a ByteBuffer.

static func patchElements(
  rendered: String, into buffer: inout ByteBuffer,
  selector: String? = nil, mode: ElementPatchMode = .outer, namespace: ElementNamespace = .html,
  useViewTransition: Bool = false, viewTransitionSelector: String? = nil,
  id: String? = nil, retry: Duration = defaultRetry)
static func removeElements(
  selector: String, into buffer: inout ByteBuffer,
  useViewTransition: Bool = false, id: String? = nil, retry: Duration = defaultRetry)
static func patchSignals(
  _ json: String, into buffer: inout ByteBuffer,
  onlyIfMissing: Bool = false, id: String? = nil, retry: Duration = defaultRetry)
static func executeScript(
  _ script: String, into buffer: inout ByteBuffer,
  autoRemove: Bool = true, attributes: [String] = [], nonce: String? = nil,
  id: String? = nil, retry: Duration = defaultRetry)
static func redirect(_ url: String, into buffer: inout ByteBuffer, ...)   // the same, with location.href
static func replaceURL(_ url: String, into buffer: inout ByteBuffer, ...) // the same, with history.replaceState
static func heartbeat(into buffer: inout ByteBuffer)  // ":\n\n"

There is no script event in the protocol. executeScript ships its JavaScript the way the Go SDK does: one datastar-patch-elements frame carrying a single <script> tag appended to body, whose data-effect="el.remove()" attribute deletes the tag again after it has run.

Multi-line HTML travels as repeated data: elements lines, which Datastar joins again before morphing, so the whole document, CSS included, goes over as is. Options equal to their protocol default stay off the wire, as in the Go SDK.

Layout

Package.swift                 # SwiftDatastar, six library products
Sources/
├── CBrotli/                  # systemLibrary shim for libbrotlienc
├── CBrotliDec/               # systemLibrary shim for libbrotlidec (tests only)
├── CZstd/                     # systemLibrary shim for libzstd
├── SwiftBrotli/              # streaming brotli encoder, no framework deps
├── SwiftZstd/                # streaming zstd encoder, no framework deps
├── DatastarCore/             # SSE wire SDK, ViewFanout and its state machines
├── SQLiteServerKit/          # writer + WriteBatcher + ReaderPool + pragmas
├── DatastarElementary/       # typed data-* attributes for Elementary
└── DatastarHummingbird/      # DatastarView, coalescer, negotiation, compression middleware
Tests/
├── DatastarCoreTests/        # wire format, fan-out lifecycles, brotli round trips
├── DatastarElementaryTests/
├── SQLiteServerKitTests/     # batching, lifecycle, checkpoints
└── DatastarHummingbirdTests/ # view, coalescer, middleware, live-server end-to-end tests
Examples/TodoApp/             # standalone package, path-depends on ../..
├── Sources/App/main.swift         # reads the environment, runs TodoKit
├── Sources/TodoKit/
│   ├── Application.swift          # middleware, routes, services, clean close
│   ├── Config.swift               # AppConfig from the environment
│   ├── Security.swift             # session cookie, CSRF, body cap, CSP and friends
│   ├── Assets.swift               # same-origin datastar.js, map, stylesheet
│   ├── TodoRoutes.swift           # the DatastarView (one per filter) and the commands
│   ├── Store.swift                # schema, migration, statements over SQLiteServer
│   ├── Views.swift                # Elementary shell and morph target
│   ├── IndexPage.swift            # /examples
│   ├── ServerDrivenUpdates.swift  # /simple
│   ├── ClientDrivenUpdates.swift  # /button
│   └── Public/                    # datastar.js v1.0.4 + map, app.css
└── Tests/TodoKitTests/            # the app end to end over HTTP, store, config
loadtest/                     # k6 script, profile.sh, flame graphs
docs/                         # design notes, performance plan, research, plans

Best practices

Borrowed from andersmurphy.com, who runs this architecture (fat-morph SSE + SQLite) in production.

Compress the stream (why you should use brotli SSE). A long-lived SSE stream shares one compression context across every event, so each full-page render compresses almost entirely into references to the last one. Quality 5, text mode and a 256 KB window (lgwin 18) are his measured sweet spot and the kit's BrotliSettings.sse. The encoder flushes after every event, so latency stays the same. The 2025 post ruled out zstd because iOS Safari lacked it. Safari 26.3 has since added it and hyperlith now streams zstd at fast level -1 with a 512 KB window, which is the kit's ZstdSettings.sse and its first choice. CompressionMiddleware makes the same zstd > br choice for every other compressible response and leaves clients that accept neither uncompressed. Measured here, a 1.6 KB render goes out as about 100 compressed bytes per event.

Tune SQLite (100k TPS over a billion rows). The article's speed comes from the connection architecture as much as the pragmas. SQLiteServer.open opens one writer connection plus a reader pool (one per core, up to 8, query_only) so reads don't starve writes. Each read leases a reader connection exclusively. readers.withReadTransaction { db in … } holds one lease across BEGIN DEFERRED … COMMIT, so a multi-query render sees one snapshot and takes one WAL read lock. Every write goes to an async batcher that commits batches in one transaction with a SAVEPOINT per write, so writers share each other's commits. WAL makes both safe. The default SQLitePragmas.taoOfSQLite sets journal_mode=WAL, synchronous=NORMAL, busy_timeout=5000, the article's cache and temp-store pragmas, and wal_autocheckpoint=0, since the batcher checkpoints between batches itself. Keep the database on local disk, not a network filesystem.

Load test

k6 drives the app in loadtest/loadtest.js. A writer is one browser tab: it loads the page, thinks, and sometimes adds, toggles or deletes a todo. Watchers hold the SSE view stream open until it times out and reconnect; churners join late and drop. See loadtest/README.md.

(cd Examples/TodoApp && swift build -c release && .build/release/App) &
WRITERS=100 WATCHERS=50 DURATION=15s k6 run loadtest/loadtest.js

Current numbers (2026-11-03, colocated)

Measured with the human-model script (loadtest/loadtest.js: think time between commands, so load is users held under latency, not maximum drain). k6 ran on the same 16-core box as the server, which also hosts a local LLM server, so these numbers are a floor, not a fair measurement. Release build, fresh database, zstd streams, 15 s ramp + 60 s steady state.

Scenario Requests/s Command p95 Page p95 Server CPU (avg cores) Peak RSS
500 writers 28 0.64 ms 0.35 ms 0.01 53 MB
1000 writers + 500 watchers + 50 churners 71 0.68 ms 0.37 ms 0.19 178 MB

At this traffic shape the server is nearly idle. The watchers' streams time out and reconnect at 30 s by design, so the all-requests p95 (30 s) reads as stream lifetime, not latency. The watchers received 1.2 GB in the run (about 2.4 MB per stream), which has not been broken down into replay vs live frames yet. For the kit's CPU ceiling, use the headless harness (Benchmarks/HeadlessBench, task C2) rather than k6.

Historical numbers

All numbers below were measured before the fix round of November 2026 (join-time frames, replay caps, eviction, services), on a 16-core desktop with the release binary and the load generator on the same box, so treat them as a floor. The database started empty.

Scenario requests/s command loops/s p95 latency
100 writers, first 5 seconds 1688 563 –
1000 writers, first 5 seconds 1142 401 2.45 s
100 writers, 15 s 974 325 216 ms
100 writers + 50 SSE streams 916 308 229 ms

Read them as the architecture, not the CPU. Every loop is an insert, a delete, two full-page renders and two broadcasts, so throughput is writes per second of O(list size) work. The first seconds off an empty table are the fastest. As the list grows each render costs more, the scaling cliff the fat morph accepts on purpose. Fifty live eyeballs cost writes about 6% throughput and 13 ms p95, brotli fan-out included.

After the empty-room guard landed, writers-only measured 1,633 req/s (544 loops/s) on this box. After the SQLite reader pool and write batching landed, writers-only measured 3,673 req/s (1,224 loops/s), 3.8x the table's original row. Watchers-scenario throughput followed co-tenants too closely to print a number. The DB was never its wall, the encoder was, and the flame graphs are the honest artifact.

Two k6 caveats. k6 buffers response bodies, so an SSE watcher must set responseType: 'none' or the load generator will OOM the box before the server breaks a sweat (it ate 24 GB once here). k6 v2 takes that option as a string, not a number.

Profiling

./loadtest/profile.sh writers|watchers records the release server with perf while k6 drives load and renders a flame graph into loadtest/profiles/. It needs the perf and flamegraph-git packages. Frame-pointer unwinding works because Swift Linux binaries keep frame pointers. With perf_event_paranoid=1 the hardware cycles PMU works unprivileged. Otherwise the script falls back to the cpu-clock software event. For the off-CPU half, swift-profile-recorder is an in-process library, not a standalone binary. Add the ProfileRecorderServer dependency and one line at the top of main, then curl the unix socket and pipe through swipr-sample-conv.

The graphs (writers.svg, watchers.svg) rewrote the performance story the benchmarks alone could not. Like the load-test numbers, both tables come from before the fix round. The first is the original build, which still encoded events with the since-removed SSEKit dependency.

CPU share writers only +50 SSE streams
Elementary HTML rendering 58% 20%
SSEKit SSEValue line split 27% 12%
brotli compression 0% 61%
SQLite 13% 0.8%
NIO/HTTP framing 0.2% 4%

The hot leaves were all Swift.String Character-indexing machinery. Every write rendered the whole page by string appending, and every rendered page was then scanned character by character twice, once in the SDK and again in the event encoder, costing O(page size) per event. Roughly 85% of writers-only CPU went into fat morphs nobody was subscribed to, and with 50 streams brotli became the bill for the 100:1 compression ratio.

Two fixes later, an isEmpty guard that skips rendering for an empty room and SSE frames hand-encoded once per broadcast (byte-split on newlines, one shared ByteBuffer for every stream), the same graphs read as follows.

CPU share writers only +50 SSE streams
Elementary HTML rendering 77% 74%
Datastar byte encode 0% (skipped) 3%
brotli compression 0% 1%
SQLite 7% 6%
NIO/HTTP framing 3% 2%

The original profiles misread SQLite's cost twice. First it looked nearly free, masked by broadcasts for an empty room. Stripped to 42% on one serialized connection, it looked like a ceiling. The article's architecture, a reader pool plus async write batching with SAVEPOINTs, cut it to 7% and tripled writers-only throughput. What remained of its cost was SQLiteNIO's per-row Swift dictionary materialization, not the engine. The writers path is now an Elementary-render story at 77%. The watchers path was an encoder story, which made render coalescing and shared generation encoders the next moves (docs/performance-plan.md).

Notes

  • Datastar's v1.0 wire format (datastar-patch-elements/datastar-patch-signals, exclusive data-bind="signal" syntax) was verified against the v1.0.4 tag of the datastar repo and the datastar-go SDK. The vendored datastar.js is that release.
  • data-ignore-morph on the Datastar script tag keeps the fat morph from booting the frontend a second time.
  • Subscriber cleanup rides on AsyncStream.Continuation.onTermination. Hummingbird cancels body iteration when a client disconnects, which fires it and removes the subscriber from the fan-out.