Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/zero-swift-poke-rows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'zero-swift': patch
---

Pokes now read each synced row straight into the row the replica and the queries' sources keep, without a JSON object in between, and so does reopening a stored replica. Pokes and first syncs apply 7–19% faster, and a client opens on a stored replica about 10% faster.
5 changes: 3 additions & 2 deletions swift/Sources/Zero/Client/Engine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ final class Engine {
},
onFatalError: { [weak self] error in self?.disconnect(error) })
pokeHandler = PokeHandler(
clientID: clientID, schema: schema, scheduler: scheduler,
clientID: clientID, schema: schema, layouts: ivmMain.layouts, scheduler: scheduler,
apply: { [weak self] poke in
guard let self else { return }
try self.withWriteLock { try self.applyPoke(poke) }
Expand Down Expand Up @@ -1062,7 +1062,8 @@ final class Engine {
}
let downstream: Downstream
do {
downstream = try Downstream(text: text)
downstream =
try pokeHandler.rowReader.pokePart(text).map(Downstream.pokePart) ?? Downstream(text: text)
} catch {
failOnMessage(
.client(
Expand Down
39 changes: 28 additions & 11 deletions swift/Sources/Zero/Client/PokeHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ final class PokeHandler {
private let clientID: String
private let schema: ZeroSchema
private let serverToClient: NameMapper
/// Reads pokes' rows into the layouts of the rows the replica keeps.
let rowReader: PokeRowReader
private let scheduler: any Scheduler
/// Applies a merged poke; throws when it does not apply.
private let apply: (MergedPoke) throws -> Void
Expand All @@ -43,14 +45,15 @@ final class PokeHandler {
private var playbackRunning = false

init(
clientID: String, schema: ZeroSchema, scheduler: any Scheduler,
clientID: String, schema: ZeroSchema, layouts: [String: RowLayout], scheduler: any Scheduler,
apply: @escaping (MergedPoke) throws -> Void,
onApplied: @escaping (MergedPoke) throws -> Void,
onPokeError: @escaping (_ message: String, _ received: Bool) -> Void
) {
self.clientID = clientID
self.schema = schema
self.serverToClient = NameMapper.serverToClient(schema)
self.rowReader = PokeRowReader(serverToClient, layouts: layouts)
self.scheduler = scheduler
self.apply = apply
self.onApplied = onApplied
Expand Down Expand Up @@ -111,12 +114,16 @@ final class PokeHandler {
}
var parts = receiving.parts
if !receiving.chunks.isEmpty {
do {
parts = try PokeChunk.decode(receiving.chunks)
} catch {
// `String(e)` of what `TextDecoder` and valita throw.
handlePokeError("TypeError: " + valitaMessage(error))
return nil
if let read = rowReader.parts(receiving.chunks) {
parts = read
} else {
do {
parts = try PokeChunk.decode(receiving.chunks)
} catch {
// `String(e)` of what `TextDecoder` and valita throw.
handlePokeError("TypeError: " + valitaMessage(error))
return nil
}
}
for part in parts {
if let message = Self.invalidLastMutationID(part) {
Expand Down Expand Up @@ -240,7 +247,7 @@ final class PokeHandler {
.put(
key: Keys.mutationResponseKey(
clientID: response.id.clientID, id: response.id.id),
value: response.result.json))
value: .json(response.result.json)))
case .del(let id):
merged.patch.append(
.del(key: Keys.mutationResponseKey(clientID: id.clientID, id: id.id)))
Expand Down Expand Up @@ -278,7 +285,7 @@ final class PokeHandler {
switch op {
case .clear: .clear
case .del(let hash): .del(key: key(hash))
case .put(let hash, _): .put(key: key(hash), value: .null)
case .put(let hash, _): .put(key: key(hash), value: .json(.null))
}
}

Expand All @@ -290,7 +297,12 @@ final class PokeHandler {
case .put(let serverTable, let value):
guard let table = serverToClient.tableNameIfKnown(serverTable) else { return nil }
let row = try serverToClient.row(serverTable, value)
return .put(key: try key(table, row), value: .object(row))
return .put(key: try key(table, row), value: .json(.object(row)))
case .putRow(let serverTable, let row):
guard let table = serverToClient.tableNameIfKnown(serverTable) else { return nil }
// Its columns are the client's: the reader reads only tables whose
// columns have the same names on the server.
return .put(key: try key(table, row), value: .row(row))
case .del(let serverTable, let id):
guard let table = serverToClient.tableNameIfKnown(serverTable) else { return nil }
return .del(key: try key(table, try serverToClient.row(serverTable, id)))
Expand All @@ -311,7 +323,8 @@ final class PokeHandler {
private static func aggregateRowPatchOp(_ op: RowPatchOp) throws -> KVPatchOp? {
switch op {
case .put(let table, let value) where isAggregateTableName(table):
return .put(key: try Keys.aggregateRowKey(table: table, row: value), value: .object(value))
return .put(
key: try Keys.aggregateRowKey(table: table, row: value), value: .json(.object(value)))
case .del(let table, let id) where isAggregateTableName(table):
return .del(key: try Keys.aggregateRowKey(table: table, row: id))
case .update(let table, let id, let merge, let constrain) where isAggregateTableName(table):
Expand All @@ -326,6 +339,10 @@ final class PokeHandler {
private func key(_ table: String, _ row: RowRecord) throws -> String {
try Keys.primaryKeyString(table: table, primaryKey: schema.tables[table]!.primaryKey, row: row)
}

private func key(_ table: String, _ row: Row) throws -> String {
try Keys.primaryKeyString(table: table, primaryKey: schema.tables[table]!.primaryKey, row: row)
}
}

/// A poke that cannot be applied. `message` is the JS error's message.
Expand Down
119 changes: 119 additions & 0 deletions swift/Sources/Zero/Client/PokeRowReader.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/// Reads the parts of a poke with each synced row straight into its table's
/// layout, the row the replica and the sources keep, instead of into a
/// JSON object the replica then turns into one.
///
/// It reads a `put` as zero-cache writes it, `{"op":"put","tableName":…,
/// "value":{…}}`, when the value's columns are all the table's; any other
/// op it reads as the decoder does. When the text is anything but a poke
/// part that decodes, it gives up (nil), and the decoder reads the text
/// from the start, with its errors.
struct PokeRowReader {
/// The layout of each table's rows, by the table's name on the server,
/// for the tables whose columns have the same names on the server.
private let layouts: [String: RowLayout]

init(_ serverToClient: NameMapper, layouts: [String: RowLayout]) {
var byServerName: [String: RowLayout] = [:]
for (serverName, table) in serverToClient.tables
where table.allColumnsSame && !isAggregateTableName(serverName) {
byServerName[serverName] = layouts[table.tableName]
}
self.layouts = byServerName
}

/// The body of the `pokePart` message `text` (`Downstream(text:)`).
func pokePart(_ text: String) -> PokePartBody? {
guard text.utf8.starts(with: #"["pokePart","#.utf8) else { return nil }
var text = text
return text.withUTF8 { buffer in
var r = JSONParser.Reader(buffer)
do {
guard try r.open("["), try r.string() != nil, r.read(","),
let part = try part(&r), r.close("]"), r.atEnd()
else { return nil }
return part
} catch {
return nil
}
}
}

/// The parts of a poke's binary chunks (`PokeChunk.decode`).
func parts(_ chunks: [ArraySlice<UInt8>]) -> [PokePartBody]? {
var bytes: [UInt8] = []
for chunk in chunks { bytes.append(contentsOf: chunk) }
let payload = bytes.starts(with: utf8BOM) ? bytes[3...] : bytes[...]
guard var text = String(validating: payload, as: UTF8.self) else { return nil }
return text.withUTF8 { buffer in
var r = JSONParser.Reader(buffer)
do {
guard try r.open("[") else { return nil }
var parts: [PokePartBody] = []
if !r.close("]") {
repeat {
guard let part = try part(&r) else { return nil }
parts.append(part)
} while r.read(",")
guard r.close("]") else { return nil }
}
return r.atEnd() ? parts : nil
} catch {
return nil
}
}
}

/// A part's body: its `rowsPatch` read here, the rest by the decoder.
private func part(_ r: inout JSONParser.Reader) throws(JSONParser.Error) -> PokePartBody? {
guard try r.open("{") else { return nil }
var rest = JSONObject()
var rows: RowsPatch?
if !r.close("}") {
repeat {
// A key given twice keeps its last value, as it does in an object.
let key = try r.key()
if StringCompare.equal(key, "rowsPatch") {
guard let ops = try rowsPatch(&r) else { return nil }
rows = ops
} else {
rest[key] = try r.value()
}
} while r.read(",")
guard r.close("}") else { return nil }
}
var json = JSONValue.object(rest)
defer { JSONValue.discard(&json) }
guard var part = try? PokePartBody(json: json) else { return nil }
part.rowsPatch = rows
return part
}

private func rowsPatch(_ r: inout JSONParser.Reader) throws(JSONParser.Error) -> RowsPatch? {
guard try r.open("[") else { return nil }
var ops: RowsPatch = []
if r.close("]") { return ops }
repeat {
guard let op = try rowPatchOp(&r) else { return nil }
ops.append(op)
} while r.read(",")
return r.close("]") ? ops : nil
}

/// A `put` of a row whose columns are all its table's, in its layout;
/// any other op as the decoder reads it.
private func rowPatchOp(_ r: inout JSONParser.Reader) throws(JSONParser.Error) -> RowPatchOp? {
let start = r.mark
if try r.open("{"), try StringCompare.equal(r.key(), "op"),
let op = try r.string(), StringCompare.equal(op, "put"), r.read(","),
try StringCompare.equal(r.key(), "tableName"), let table = try r.string(), r.read(","),
try StringCompare.equal(r.key(), "value"), let layout = layouts[table],
let row = try r.row(layout), r.close("}")
{
return .putRow(tableName: table, row: row)
}
r.reset(to: start)
var json = try r.value()
defer { JSONValue.discard(&json) }
return try? RowPatchOp(json: json)
}
}
7 changes: 5 additions & 2 deletions swift/Sources/Zero/Client/ReplicaStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,8 @@ final class KVWrite {

/// A patch operation of a pull response (`PatchOperationInternal`).
enum KVPatchOp {
case put(key: String, value: JSONValue)
/// A row the poke's reader read into its layout is `.row`.
case put(key: String, value: KVValue)
case update(key: String, merge: RowRecord?, constrain: [String]?)
case del(key: String)
case clear
Expand Down Expand Up @@ -309,8 +310,10 @@ final class ReplicaStore {
switch op {
case .clear:
write.clear(keysOf: write.map)
case .put(let key, let value):
case .put(let key, .json(let value)):
write.set(key, KVValue(value, at: key, layouts: layouts))
case .put(let key, let value):
write.set(key, value)
case .update(let key, let merge, let constrain):
var entries: [(String, JSONValue)] = []
switch write.get(key) {
Expand Down
Loading
Loading