The official client for GenesisDB. Swift 5.9+, async/await, zero dependencies, runs on macOS 12+, iOS 15+, tvOS 15+, watchOS 8+ and Linux.
// Package.swift
dependencies: [
.package(url: "https://github.com/genesisdb-io/genesisdb-io-client-swift.git", from: "2.0.0"),
],
targets: [
.target(name: "App", dependencies: [.product(name: "GenesisDB", package: "genesisdb-io-client-swift")]),
]Quick start
import GenesisDB
let db = try Client(url: "http://localhost:8080", token: ProcessInfo.processInfo.environment["GENESISDB_AUTH_TOKEN"])
try await db.commit([
NewEvent(source: "io.example.shop", subject: "/customer/42", type: "io.example.shop.customer-registered", data: ["name": "Bruce Wayne"]),
])
let events = try await db.fetch("/customer/42")url and token fall back to GENESISDB_URL and GENESISDB_AUTH_TOKEN, so try Client() works in an environment that sets both. The client is Sendable and shares one URLSession.
Events
Payloads are JSONValue, a plain enum over JSON with literal syntax and subscripts.
// Commit a batch atomically. The server assigns ID, time and hashes and returns the stored events.
let stored = try await db.commit([
NewEvent(source: "io.example.shop", subject: "/order/1", type: "io.example.shop.order-placed", data: ["total": 99.5]),
NewEvent(source: "io.example.shop", subject: "/order/1/item/1", type: "io.example.shop.item-added", data: ["sku": "A1", "qty": 2]),
])
stored[0].id // "3f2c..."
stored[0].hash // "a9b1..."
stored[0].time // Date
// A subject with one segment gets a generated ID appended.
try await db.commit([NewEvent(source: "io.example.shop", subject: "/customer", type: "io.example.shop.customer-registered", data: ["name": "Selina"])])
// Fetch a subject with all descendants, in commit order.
let all = try await db.fetch("/order/1")
// Resume after a known event, or stop at one.
let since = try await db.fetch("/order", options: FetchOptions(lowerBound: lastSeenId, includeLowerBoundEvent: false))
let until = try await db.fetch("/order", options: FetchOptions(upperBound: someId, includeUpperBoundEvent: true))
// Only the newest event of a type below the subject.
let latest = try await db.fetch("/order/1", options: FetchOptions(latestByEventType: "io.example.shop.order-placed"))
// Typed payloads
struct Order: Codable { let total: Double }
let order = try stored[0].data(as: Order.self)
let event = try NewEvent.encoding(Order(total: 10), source: "io.example.shop", subject: "/order/2", type: "io.example.shop.order-placed")Preconditions
Preconditions are checked atomically with the commit. A failed precondition throws GenesisDBError.preconditionFailed and writes nothing.
do {
try await db.commit(
[NewEvent(source: "io.example.shop", subject: "/customer/42", type: "io.example.shop.customer-registered", data: ["email": "bruce@example.com"])],
preconditions: [
.isSubjectNew(subject: "/customer/42"),
.isQueryResultTrue(query: "STREAM e FROM events WHERE e.data.email == 'bruce@example.com' MAP COUNT() == 0"),
]
)
} catch GenesisDBError.preconditionFailed(_, let type, let reason, _) {
print(type, reason) // "isSubjectNew" "subject /customer/42 already has events"
}Cases: isSubjectNew, isSubjectExisting, isQueryResultTrue.
Subscriptions
subscribe returns an AsyncThrowingStream over Server-Sent Events. It yields the existing history first, then new events as they are committed, and runs until the task is cancelled.
let consumer = Task {
for try await event in db.subscribe("/order", options: SubscribeOptions(interval: 0.5)) {
print(event.type, event.data)
}
}
// ...
consumer.cancel()interval is the poll interval in seconds (default 1). The bound options of fetch work here as well through SubscribeOptions(fetch:), so a consumer that persists the last processed event ID resumes with lowerBound. A stream the server ends with an error throws GenesisDBError.subscriptionEnded.
Queries
GDBQL runs on the server. Results come back as rows, a bare aggregate as a single-element array.
let rows = try await db.query("STREAM e FROM events WHERE e.subject UNDER '/customer' MAP { name: e.data.name, total: e.data.total }")
struct Row: Decodable { let name: String; let total: Double }
let typed = try await db.query("STREAM e FROM events WHERE e.subject UNDER '/customer' MAP { name: e.data.name, total: e.data.total }", as: Row.self)
let count = try await db.query("STREAM e FROM events WHERE e.type == 'io.example.shop.order-placed' MAP COUNT()", as: Int.self)
let byCategory = try await db.query(
"STREAM e FROM events WHERE e.type == 'io.example.shop.item-added' GROUP BY e.data.category MAP { category: e.data.category, items: COUNT(), revenue: SUM(e.data.total) }"
)GDPR: reference payloads and erasure
Store a payload as reference data and it can be erased later. The event, its hash and the chain stay intact, the payload becomes {}.
try await db.commit([
NewEvent(source: "io.example.shop", subject: "/customer/42", type: "io.example.shop.customer-registered", data: ["name": "Bruce", "email": "bruce@example.com"]).asReference(),
])
try await db.erase("/customer/42") // administrator tokenInline payloads are immutable. erase on a subject without reference payloads throws an error with isUnprocessable (422).
Schemas
try await db.registerSchema("io.example.shop.order-placed", schema: [
"type": "object",
"properties": ["total": ["type": "number"], "currency": ["type": "string"]],
"required": ["total"],
])
let schemas = try await db.schemas()Commits of that type are validated. A violation throws GenesisDBError.api with status 400.
Catalog, status, administration
try await db.subjects() // ["/customer", "/order"]
try await db.types() // ["io.example.shop.customer-registered", ...]
try await db.status() // engine version, event counts, storage format, readiness
try await db.ping() // "Pong", no token required
try await db.audit() // "Audit passed. All 1234 events integrity checks succeeded."Audit, erase and schema registration need the administrator token. Everything else works with a reader token (GENESISDB_READ_TOKEN), commit additionally with a writer token.
Errors
Every non-2xx answer throws GenesisDBError.api(operation:status:body:kind:), except 412 which throws .preconditionFailed(operation:preconditionType:reason:body:). APIErrorKind classifies .authentication (401, 403), .notFound (404), .conflict (409), .unprocessable (422), .notReady (503) and .other. Convenience: error.status, error.isPreconditionFailed, error.isAuthentication, error.isNotFound, error.isConflict, error.isUnprocessable, error.isNotReady. Transport failures throw .transport.
Configuration
try Client(
url: "http://localhost:8080", // or GENESISDB_URL
token: "...", // or GENESISDB_AUTH_TOKEN
timeout: 30, // seconds, for non-streaming calls
session: URLSession(...) // optional, bring your own session (proxies, TLS)
)