Files
t3code/apps/swift-ios/Core/JSONValue.swift
T
Theo BrowneandClaude Fable 5 99f78a7d1f perf(swift-ios): cut hot-path waste in networking, state, and caches
- Cache EnvironmentStore's decoded document; publishes read it several
  times per second and previously hit disk + JSON decode every time
- Memoize parsed ISO8601 dates in NativeFeatureClient; every publish
  re-parsed ~10 timestamps per thread through two formatters
- Cache the mapped provider catalog per environment, invalidated on
  server config writes, instead of rebuilding hundreds of structs per
  publish
- Sort activity logs by raw ISO string instead of parsing dates inside
  the comparator (O(n log n) formatter calls per detail rebuild)
- Skip attachment hydration entirely for text-only threads
- Dedupe emitConnection so per-event yields only publish transitions
- Early-out acknowledgeDeliveredMessages when the outbox is empty
- Cap terminal buffers at 256KB; unbounded append could OOM on verbose
  commands and re-layout megabyte strings per chunk
- Key the markdown document cache by content fingerprint instead of the
  whole source string, stop inserting streaming intermediates (which
  churned completed messages out), and promote the final streamed render
  on completion instead of reparsing on the main thread
- Throttle streaming markdown renders (150ms leading-edge) instead of a
  200ms trailing debounce that never fired at an 80ms publish cadence,
  which left streaming messages as plain text for whole turns
- Share JSONEncoder/Decoder.t3 instances (were rebuilt per call) and
  skip sortedKeys on throwaway JSONValue bridging encodes
- Weak-capture the RPC connection loop and keepalive so released
  clients can actually deinit; snapshot dictionary keys before
  reentrant iteration in connected(); scope subscription Interrupts to
  the connection that assigned the request ID; add reconnect jitter
- Cache DPoP JWK + thumbprint (SHA-256 per managed request before) and
  the proof encoder; reuse ISO8601 formatter in command builders
- Replace crash-prone Dictionary(uniqueKeysWithValues:) on
  server-supplied IDs with first-wins reduces (model picker, agent
  awareness); retain per-thread states instead of full FeatureThread
  copies for transition signals; idle the home list timer to 60s when
  nothing is working

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-09 20:53:11 -07:00

112 lines
3.8 KiB
Swift

import Foundation
/// A lossless, Sendable JSON representation used at protocol boundaries that
/// intentionally carry provider-defined payloads.
public enum JSONValue: Codable, Equatable, Sendable {
case null
case bool(Bool)
case integer(Int64)
case unsignedInteger(UInt64)
case number(Double)
case string(String)
case array([JSONValue])
case object([String: JSONValue])
public init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .null
} else if let value = try? container.decode(Bool.self) {
self = .bool(value)
} else if let value = try? container.decode(Int64.self) {
let double = Double(value)
self = Int64(exactly: double) == value ? .number(double) : .integer(value)
} else if let value = try? container.decode(UInt64.self) {
let double = Double(value)
self = UInt64(exactly: double) == value
? .number(double)
: .unsignedInteger(value)
} else if let value = try? container.decode(Double.self) {
self = .number(value)
} else if let value = try? container.decode(String.self) {
self = .string(value)
} else if let value = try? container.decode([JSONValue].self) {
self = .array(value)
} else {
self = .object(try container.decode([String: JSONValue].self))
}
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .null:
try container.encodeNil()
case let .bool(value):
try container.encode(value)
case let .integer(value):
try container.encode(value)
case let .unsignedInteger(value):
try container.encode(value)
case let .number(value):
try container.encode(value)
case let .string(value):
try container.encode(value)
case let .array(value):
try container.encode(value)
case let .object(value):
try container.encode(value)
}
}
public subscript(key: String) -> JSONValue? {
guard case let .object(object) = self else { return nil }
return object[key]
}
public var stringValue: String? {
guard case let .string(value) = self else { return nil }
return value
}
public static func encode<T: Encodable & Sendable>(
_ value: T,
encoder: JSONEncoder = .t3
) throws -> JSONValue {
let data = try encoder.encode(value)
return try JSONDecoder.t3.decode(JSONValue.self, from: data)
}
public func decode<T: Decodable & Sendable>(
_ type: T.Type,
decoder: JSONDecoder = .t3
) throws -> T {
// The intermediate bytes are discarded immediately, so skip the
// deterministic-output formatting the wire encoder pays for.
try decoder.decode(type, from: JSONEncoder.t3Intermediate.encode(self))
}
}
// Encoders and decoders are configured once and never mutated afterwards, so
// shared instances are safe for concurrent use and avoid rebuilding coder
// state on every RPC message.
extension JSONEncoder {
/// Deterministic output for wire payloads.
public static let t3: JSONEncoder = {
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
return encoder
}()
/// Throwaway intermediate encoding (JSONValue -> concrete type bridging).
static let t3Intermediate: JSONEncoder = {
let encoder = JSONEncoder()
encoder.outputFormatting = [.withoutEscapingSlashes]
return encoder
}()
}
extension JSONDecoder {
public static let t3 = JSONDecoder()
}