Swift client
Every public type, initialiser and method of the Luna Swift package, for iOS, macOS and the other Apple platforms.
The Luna Swift package calls lunas from an app on iOS 17, macOS 14, tvOS 17, watchOS 10, visionOS 1 and later. It follows the same model as createClient: live queries, optimistic writes, reconnecting, pushes, streams and queued writes.
import Foundation
import Luna
struct Item: Codable, Sendable { let id: Int; let text: String }
@MainActor
func addMilk() async throws {
let client = LunaClient(ClientOptions(url: URL(string: "<LUNA_URL>")!, key: "<LUNA_KEY>"))
let list = client.luna("List", "groceries")
let items = list.query("all", as: [Item].self)
let subscription = items.subscribe { print(items.state.data ?? []) }
try await list.mutate("add", ["text": "milk"])
subscription.cancel()
}
Reference
Every type that holds state is @MainActor. Call it from the main actor.
ClientOptions
ClientOptions(url:key:) makes the options. Set the other fields on a var before you pass it to LunaClient.
urlURL
The environment's URL, the LUNA_URL in .env.local.
URLkey?String?
A publishable key. It reaches public luna types only.
String?token?String?
A secret token, sent as Authorization: Bearer. For your own servers and tools, never in an app.
String?headers?[String: String]
Extra request headers.
[String: String][:]params?(@Sendable () async throws -> [String: String])?
Query parameters for each new connection, which onBeforeConnect reads. Asked again on every reconnect.
(@Sendable () async throws -> [String: String])?keepAlive?Duration
How long a query nobody watches stays live and cached.
Duration.seconds(10)settle?Duration
How long a confirmed write stays laid over the queries of other lunas. Queries of the write's own luna get four times as long.
Duration.seconds(1)callTimeout?Duration
How long a call may take, including the wait to connect.
Duration.seconds(30)multiplex?Bool
One WebSocket for all of the client's lunas. With false, one each.
Booltruestore?(any ClientStore)?
Where query results and queued writes are kept between runs. Use one per account.
(any ClientStore)?optimistic?[String: QueuedOptimistic]
Optimistic updates for queued writes, by name.
[String: QueuedOptimistic][:]transport?@MainActor @Sendable (URL, [String: String]) -> any LunaTransport
Makes each WebSocket. Tests replace it.
@MainActor @Sendable (URL, [String: String]) -> any LunaTransportfetch?@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse)
Makes each stream read. Tests replace it.
@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse)LunaClient
init(_ options:)?LunaClient
Makes a client. With a store, it reads back saved writes and starts sending them.
LunaClientluna(_ type:, _ key...)?LunaHandle
One luna, by its type and key values, such as luna("List", "groceries").
LunaHandleindex(_ name:, partition:)?IndexHandle
One partition of an index, read live.
IndexHandlewrites?[QueuedWrite]
The queued writes that wait or failed, oldest first.
[QueuedWrite]subscribeWrites(_ fn:)?Subscription
Hears every change to the queue.
SubscriptionresumeWrites()?Void
Sends the queue again after it stopped for a sign-in that ran out.
VoidretryWrite(_ id:)?Void
Puts a failed write back in the queue.
VoiddiscardWrite(_ id:)?Void
Drops a failed write.
Voidwipe()?async
Empties the store and the queue, for when someone signs out.
asyncclose()?Void
Closes every connection. The client cannot be used after.
Voidoptions?ClientOptions
The options the client was made with.
ClientOptionsLunaHandle
query(_ handler:, _ args:, as:)?LiveQuery<T>
A live query of a query handler, decoded as T.
LiveQuery<T>mutate(_ handler:, _ args:, timeout:, optimistic:)?async throws -> JSON
Calls a handler. optimistic changes what queries show until the write is in.
async throws -> JSONmutate(_ handler:, _ args:, returning:, timeout:, optimistic:)?async throws -> R
The same, with the result decoded.
async throws -> Rread(_ handler:, _ args:, timeout:)?async throws -> JSON
One answer from a handler, not followed.
async throws -> JSONread(_ handler:, _ args:, as:, timeout:)?async throws -> R
The same, with the result decoded.
async throws -> Rresponse(_ handler:, _ args:, timeout:)?async throws -> HTTPResult
Calls a handler that answers with a Response: its status, headers and body.
async throws -> HTTPResultiterate(_ handler:, _ args:)?AsyncThrowingStream<JSON, Error>
What a streaming handler yields, as it yields it. Leaving the loop stops the handler.
AsyncThrowingStream<JSON, Error>connectionStatus?ConnectionStatus
The connection's state now.
ConnectionStatusonConnectionChange(_ fn:)?Subscription
Hears each change of state and keeps the connection open.
Subscriptionenqueue(_ handler:, _ args:, optimistic:)?throws -> QueuedResult
Queues a write that survives restarts. optimistic names an update in ClientOptions.optimistic.
throws -> QueuedResulton(_ push:, as:, _ fn:)?Subscription
Hears a push, decoded as T. A push that does not decode is skipped.
Subscriptionstream(_ name:, as:, offset:, limit:)?StreamReader<T>
Reads a stream as it grows. offset is "-1" and limit 1000 unless given.
StreamReader<T>observe(_ handler:, _ args:, as:)?ObservedQuery<T>
A live query as an observable value, for SwiftUI.
ObservedQuery<T>observeConnection()?ObservedConnection
The connection as an observable value.
ObservedConnectionobserveStream(_ name:, as:, offset:, limit:)?ObservedStream<T>
A stream as an observable value.
ObservedStream<T>LiveQuery and QueryState
state?QueryState<T>
The latest state.
QueryState<T>subscribe(_ fn:)?Subscription
Hears every change and keeps the query live while the subscription is held.
Subscriptionupdates?AsyncStream<QueryState<T>>
Each state as it changes, starting with the current one.
AsyncStream<QueryState<T>>QueryState.status?.loading | .ready | .error
.ready once there is data. .error when the first run failed.
.loading | .ready | .errorQueryState.data?T?
The confirmed result, with pending writes laid over it.
T?QueryState.error?LunaError?
The latest run's failure. data stays as it was.
LunaError?QueryState.stale?Bool
The connection dropped, or the result is a saved one, so data may be behind.
BoolLocalStore
What an optimistic closure receives.
get(_ query:)?T?
A query's value as of the writes before this one. nil when it is not loaded.
T?set(_ query:, _ value:)?Void
Replaces what a query shows while this write is pending.
Voidupdate(_ query:, _ fn:)?Void
set from the current value. Does nothing when the query is not loaded.
VoidSubscription and ConnectionStatus
Subscription.cancel() ends what it was returned for. Releasing the subscription ends it too, so keep it while you need it.
ConnectionStatus is .connecting, .open, .reconnecting or .closed.
StreamReader and StreamState
state?StreamState<T>
What has been read so far.
StreamState<T>subscribe(_ fn:)?Subscription
Hears new entries and keeps reading.
SubscriptionStreamState.entries?[T]
What has been read, oldest first, at most limit of them.
[T]StreamState.offset?String
Where reading goes on from.
StringStreamState.upToDate?Bool
The last read reached the end of the stream.
BoolStreamState.error?LunaError?
The last read's failure.
LunaError?IndexHandle
Options are JSON with the same names as in TypeScript. See IndexHandle.
find(_ options:, as:)?LiveQuery<[Row]>
Rows that match: where, orderBy and limit.
LiveQuery<[Row]>count(_ options:)?LiveQuery<Int>
How many rows match: where.
LiveQuery<Int>groupBy(_ options:, as:)?LiveQuery<[Row]>
Rows grouped: by, where, sum, min, max and limit.
LiveQuery<[Row]>search(_ text:, where:, limit:, match:, prefix:, as:)?LiveQuery<[SearchHit<Row>]>
Full-text search, best first. match is "all" unless given.
LiveQuery<[SearchHit<Row>]>nearest(_ column:, to:, k:, where:, as:)?LiveQuery<[NearestHit<Row>]>
The rows whose vector column is nearest, nearest first.
LiveQuery<[NearestHit<Row>]>SearchHit?{ row: Row, score: Double }
A row search found. A higher score is a better match.
{ row: Row, score: Double }NearestHit?{ row: Row, distance: Double }
A row nearest found. A smaller distance is nearer.
{ row: Row, distance: Double }Observable values
Each is @Observable. Hold one in @State and the view follows it. It stays live for as long as it is held.
ObservedQuery(_ query:)?state, data, status, error, stale
A live query.
state, data, status, error, staleObservedConnection(_ luna:)?status
The connection to a luna.
statusObservedStream(_ reader:)?state, entries
A stream of a luna.
state, entriesJSON
The value arguments and results are made of. It is Codable, Hashable and Sendable, and Swift literals make one, such as ["text": "milk"].
cases?.null, .bool, .int, .double, .string, .array, .object
One case per kind of JSON value. Whole numbers are Int64.
.null, .bool, .int, .double, .string, .array, .objectinit(encoding:)?throws
Any Encodable value as JSON.
throwsdecode(as:)?throws -> T
This value as a Decodable type.
throws -> Tsubscript(_ key:)?JSON?
A field of an object. nil for anything else.
JSON?LunaError, HTTPResult and HTTPError
LunaError.code?String
Luna's code, such as Closed or Timeout, or the luna's own.
StringLunaError.message?String
What went wrong.
StringLunaError.data?JSON?
What came with the error, such as a declared error's data.
JSON?LunaError.status?Int?
For a refused connection, the HTTP status. 403 when onBeforeConnect refused.
Int?LunaError(code:message:data:status:)?init
Makes one.
initHTTPResult.status?Int
The Response's status.
IntHTTPResult.headers?[String: String]
Its headers, names in lower case.
[String: String]HTTPResult.body?Data
Its body, as sent.
DataHTTPResult.text?String
The body as text.
StringHTTPResult.json()?throws -> JSON
The body as JSON.
throws -> JSONHTTPError.result?HTTPResult
A Response with a status of 400 or above, thrown by mutate and read.
HTTPResultHTTPError.status?Int
Its status.
IntClientStore and DiskStore
ClientStore is a protocol with get(_:), set(_:_:), delete(_:), keys(prefix:) and compact(). Each method but compact() may throw. compact() runs once at startup and does nothing unless you give it a body.
DiskStore(account:)?throws
A folder for one account under the app's Application Support directory.
throwsDiskStore(directory:)?throws
A folder you choose. It is made if it does not exist.
throwsdirectory?URL
Where the files are.
URLDiskStore keeps one file per key, and keeps the 2,000 query results saved most recently.
QueuedWrite, QueuedResult and QueuedOptimistic
QueuedWrite?id, path, handler, args, status, error
A write that waits or failed. status is .pending or .failed.
id, path, handler, args, status, errorQueuedResult.id?String
The write's id, also its idempotency key.
StringQueuedResult.value()?async throws -> JSON
What the handler returned, once it has run.
async throws -> JSONQueuedOptimistic?@MainActor @Sendable (LocalStore, LunaHandle, JSON) -> Void
An optimistic update for a queued write: the store, the luna and the write's arguments.
@MainActor @Sendable (LocalStore, LunaHandle, JSON) -> VoidLunaTransport
The protocol a WebSocket meets for ClientOptions.transport: onMessage, onClose, send(_:) and close(code:). The default uses URLSession.
Good to know
- Writes made on one connection run one at a time, in the order sent. A write whose connection dropped throws
Closed, and may or may not have happened. close()fails the promises of queued writes withClosed. The writes stay in the store and go when a new client starts.- The package has no typed wrappers of its own.
luna generatewrites them for your luna types. - Swift has no
connect. Messages toonMessageneed the TypeScript connect.
Examples
Show a write at once
try await list.mutate("add", ["text": "milk"]) { local in
local.update(items) { $0 + [Item(id: -1, text: "milk")] }
}
Follow a query in SwiftUI
import Luna
import SwiftUI
struct GroceriesView: View {
@State private var items: ObservedQuery<[Item]>
init(list: LunaHandle) {
_items = State(initialValue: list.observe("all", as: [Item].self))
}
var body: some View {
List(items.data ?? [], id: \.id) { Text($0.text) }
}
}
Follow a query without SwiftUI
for await state in list.query("all", as: [Item].self).updates {
print(state.data ?? [], state.stale)
}
Queue writes that survive a restart
var options = ClientOptions(url: URL(string: "<LUNA_URL>")!, key: "<LUNA_KEY>")
options.store = try DiskStore(account: "account-42")
options.optimistic = [
"addItem": { local, luna, args in
let text = (try? args["text"]?.decode(as: String.self)) ?? ""
local.update(luna.query("all", as: [Item].self)) { $0 + [Item(id: -1, text: text)] }
},
]
let client = LunaClient(options)
try client.luna("List", "groceries").enqueue("add", ["text": "eggs"], optimistic: "addItem")
Hear a push and read a stream
struct Said: Codable, Sendable { let text: String }
let room = client.luna("Room", "lobby")
let pushes = room.on("said", as: Said.self) { print($0.text) }
let reader = room.stream("said", as: Said.self, offset: "now", limit: 100)
let reading = reader.subscribe { print(reader.state.entries.map(\.text)) }
Search an index
struct Card: Codable, Sendable { let title: String; let done: Bool; let board: String }
let cards = client.index("BoardCards", partition: "b1")
let open = cards.find(["where": ["done": false], "orderBy": "title"], as: Card.self)
let hits = cards.search("mil", prefix: true, as: Card.self)
Tell errors apart
do {
try await list.mutate("add", ["text": "milk"])
} catch let e as LunaError {
print(e.code, e.message)
} catch let e as HTTPError {
print(e.status)
}