Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

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.

PropType
urlURL

The environment's URL, the LUNA_URL in .env.local.

TypeURL
key?String?

A publishable key. It reaches public luna types only.

TypeString?
token?String?

A secret token, sent as Authorization: Bearer. For your own servers and tools, never in an app.

TypeString?
headers?[String: String]

Extra request headers.

Type[String: String]
Default[:]
params?(@Sendable () async throws -> [String: String])?

Query parameters for each new connection, which onBeforeConnect reads. Asked again on every reconnect.

Type(@Sendable () async throws -> [String: String])?
keepAlive?Duration

How long a query nobody watches stays live and cached.

TypeDuration
Default.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.

TypeDuration
Default.seconds(1)
callTimeout?Duration

How long a call may take, including the wait to connect.

TypeDuration
Default.seconds(30)
multiplex?Bool

One WebSocket for all of the client's lunas. With false, one each.

TypeBool
Defaulttrue
store?(any ClientStore)?

Where query results and queued writes are kept between runs. Use one per account.

Type(any ClientStore)?
optimistic?[String: QueuedOptimistic]

Optimistic updates for queued writes, by name.

Type[String: QueuedOptimistic]
Default[:]
transport?@MainActor @Sendable (URL, [String: String]) -> any LunaTransport

Makes each WebSocket. Tests replace it.

Type@MainActor @Sendable (URL, [String: String]) -> any LunaTransport
fetch?@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse)

Makes each stream read. Tests replace it.

Type@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse)

LunaClient

PropType
init(_ options:)?LunaClient

Makes a client. With a store, it reads back saved writes and starts sending them.

TypeLunaClient
luna(_ type:, _ key...)?LunaHandle

One luna, by its type and key values, such as luna("List", "groceries").

TypeLunaHandle
index(_ name:, partition:)?IndexHandle

One partition of an index, read live.

TypeIndexHandle
writes?[QueuedWrite]

The queued writes that wait or failed, oldest first.

Type[QueuedWrite]
subscribeWrites(_ fn:)?Subscription

Hears every change to the queue.

TypeSubscription
resumeWrites()?Void

Sends the queue again after it stopped for a sign-in that ran out.

TypeVoid
retryWrite(_ id:)?Void

Puts a failed write back in the queue.

TypeVoid
discardWrite(_ id:)?Void

Drops a failed write.

TypeVoid
wipe()?async

Empties the store and the queue, for when someone signs out.

Typeasync
close()?Void

Closes every connection. The client cannot be used after.

TypeVoid
options?ClientOptions

The options the client was made with.

TypeClientOptions

LunaHandle

PropType
query(_ handler:, _ args:, as:)?LiveQuery<T>

A live query of a query handler, decoded as T.

TypeLiveQuery<T>
mutate(_ handler:, _ args:, timeout:, optimistic:)?async throws -> JSON

Calls a handler. optimistic changes what queries show until the write is in.

Typeasync throws -> JSON
mutate(_ handler:, _ args:, returning:, timeout:, optimistic:)?async throws -> R

The same, with the result decoded.

Typeasync throws -> R
read(_ handler:, _ args:, timeout:)?async throws -> JSON

One answer from a handler, not followed.

Typeasync throws -> JSON
read(_ handler:, _ args:, as:, timeout:)?async throws -> R

The same, with the result decoded.

Typeasync throws -> R
response(_ handler:, _ args:, timeout:)?async throws -> HTTPResult

Calls a handler that answers with a Response: its status, headers and body.

Typeasync throws -> HTTPResult
iterate(_ handler:, _ args:)?AsyncThrowingStream<JSON, Error>

What a streaming handler yields, as it yields it. Leaving the loop stops the handler.

TypeAsyncThrowingStream<JSON, Error>
connectionStatus?ConnectionStatus

The connection's state now.

TypeConnectionStatus
onConnectionChange(_ fn:)?Subscription

Hears each change of state and keeps the connection open.

TypeSubscription
enqueue(_ handler:, _ args:, optimistic:)?throws -> QueuedResult

Queues a write that survives restarts. optimistic names an update in ClientOptions.optimistic.

Typethrows -> QueuedResult
on(_ push:, as:, _ fn:)?Subscription

Hears a push, decoded as T. A push that does not decode is skipped.

TypeSubscription
stream(_ name:, as:, offset:, limit:)?StreamReader<T>

Reads a stream as it grows. offset is "-1" and limit 1000 unless given.

TypeStreamReader<T>
observe(_ handler:, _ args:, as:)?ObservedQuery<T>

A live query as an observable value, for SwiftUI.

TypeObservedQuery<T>
observeConnection()?ObservedConnection

The connection as an observable value.

TypeObservedConnection
observeStream(_ name:, as:, offset:, limit:)?ObservedStream<T>

A stream as an observable value.

TypeObservedStream<T>

LiveQuery and QueryState

PropType
state?QueryState<T>

The latest state.

TypeQueryState<T>
subscribe(_ fn:)?Subscription

Hears every change and keeps the query live while the subscription is held.

TypeSubscription
updates?AsyncStream<QueryState<T>>

Each state as it changes, starting with the current one.

TypeAsyncStream<QueryState<T>>
QueryState.status?.loading | .ready | .error

.ready once there is data. .error when the first run failed.

Type.loading | .ready | .error
QueryState.data?T?

The confirmed result, with pending writes laid over it.

TypeT?
QueryState.error?LunaError?

The latest run's failure. data stays as it was.

TypeLunaError?
QueryState.stale?Bool

The connection dropped, or the result is a saved one, so data may be behind.

TypeBool

LocalStore

What an optimistic closure receives.

PropType
get(_ query:)?T?

A query's value as of the writes before this one. nil when it is not loaded.

TypeT?
set(_ query:, _ value:)?Void

Replaces what a query shows while this write is pending.

TypeVoid
update(_ query:, _ fn:)?Void

set from the current value. Does nothing when the query is not loaded.

TypeVoid

Subscription 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

PropType
state?StreamState<T>

What has been read so far.

TypeStreamState<T>
subscribe(_ fn:)?Subscription

Hears new entries and keeps reading.

TypeSubscription
StreamState.entries?[T]

What has been read, oldest first, at most limit of them.

Type[T]
StreamState.offset?String

Where reading goes on from.

TypeString
StreamState.upToDate?Bool

The last read reached the end of the stream.

TypeBool
StreamState.error?LunaError?

The last read's failure.

TypeLunaError?

IndexHandle

Options are JSON with the same names as in TypeScript. See IndexHandle.

PropType
find(_ options:, as:)?LiveQuery<[Row]>

Rows that match: where, orderBy and limit.

TypeLiveQuery<[Row]>
count(_ options:)?LiveQuery<Int>

How many rows match: where.

TypeLiveQuery<Int>
groupBy(_ options:, as:)?LiveQuery<[Row]>

Rows grouped: by, where, sum, min, max and limit.

TypeLiveQuery<[Row]>
search(_ text:, where:, limit:, match:, prefix:, as:)?LiveQuery<[SearchHit<Row>]>

Full-text search, best first. match is "all" unless given.

TypeLiveQuery<[SearchHit<Row>]>
nearest(_ column:, to:, k:, where:, as:)?LiveQuery<[NearestHit<Row>]>

The rows whose vector column is nearest, nearest first.

TypeLiveQuery<[NearestHit<Row>]>
SearchHit?{ row: Row, score: Double }

A row search found. A higher score is a better match.

Type{ row: Row, score: Double }
NearestHit?{ row: Row, distance: Double }

A row nearest found. A smaller distance is nearer.

Type{ 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.

PropType
ObservedQuery(_ query:)?state, data, status, error, stale

A live query.

Typestate, data, status, error, stale
ObservedConnection(_ luna:)?status

The connection to a luna.

Typestatus
ObservedStream(_ reader:)?state, entries

A stream of a luna.

Typestate, entries

JSON

The value arguments and results are made of. It is Codable, Hashable and Sendable, and Swift literals make one, such as ["text": "milk"].

PropType
cases?.null, .bool, .int, .double, .string, .array, .object

One case per kind of JSON value. Whole numbers are Int64.

Type.null, .bool, .int, .double, .string, .array, .object
init(encoding:)?throws

Any Encodable value as JSON.

Typethrows
decode(as:)?throws -> T

This value as a Decodable type.

Typethrows -> T
subscript(_ key:)?JSON?

A field of an object. nil for anything else.

TypeJSON?

LunaError, HTTPResult and HTTPError

PropType
LunaError.code?String

Luna's code, such as Closed or Timeout, or the luna's own.

TypeString
LunaError.message?String

What went wrong.

TypeString
LunaError.data?JSON?

What came with the error, such as a declared error's data.

TypeJSON?
LunaError.status?Int?

For a refused connection, the HTTP status. 403 when onBeforeConnect refused.

TypeInt?
LunaError(code:message:data:status:)?init

Makes one.

Typeinit
HTTPResult.status?Int

The Response's status.

TypeInt
HTTPResult.headers?[String: String]

Its headers, names in lower case.

Type[String: String]
HTTPResult.body?Data

Its body, as sent.

TypeData
HTTPResult.text?String

The body as text.

TypeString
HTTPResult.json()?throws -> JSON

The body as JSON.

Typethrows -> JSON
HTTPError.result?HTTPResult

A Response with a status of 400 or above, thrown by mutate and read.

TypeHTTPResult
HTTPError.status?Int

Its status.

TypeInt

ClientStore 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.

PropType
DiskStore(account:)?throws

A folder for one account under the app's Application Support directory.

Typethrows
DiskStore(directory:)?throws

A folder you choose. It is made if it does not exist.

Typethrows
directory?URL

Where the files are.

TypeURL

DiskStore keeps one file per key, and keeps the 2,000 query results saved most recently.

QueuedWrite, QueuedResult and QueuedOptimistic

PropType
QueuedWrite?id, path, handler, args, status, error

A write that waits or failed. status is .pending or .failed.

Typeid, path, handler, args, status, error
QueuedResult.id?String

The write's id, also its idempotency key.

TypeString
QueuedResult.value()?async throws -> JSON

What the handler returned, once it has run.

Typeasync throws -> JSON
QueuedOptimistic?@MainActor @Sendable (LocalStore, LunaHandle, JSON) -> Void

An optimistic update for a queued write: the store, the luna and the write's arguments.

Type@MainActor @Sendable (LocalStore, LunaHandle, JSON) -> Void

LunaTransport

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 with Closed. The writes stay in the store and go when a new client starts.
  • The package has no typed wrappers of its own. luna generate writes them for your luna types.
  • Swift has no connect. Messages to onMessage need 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)
}

Was this page helpful?