SPB Git

Repository Public

VQObjectStoreClient.swift 4.3 KB 81 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Sync/VQObjectStoreClient.swift3// Description: The object store and change feed routes (CONTRACT §1.2), one call each. The sync engine is built on it;4//              apps can also call it directly for one-off reads (versions).5import Foundation67public struct VQObjectStoreClient: Sendable {8    public let client: VQClient9    public init(client: VQClient) { self.client = client }10    public init(transport: any VQTransport) { self.client = VQClient(transport: transport) }1112    /// `data` above this size is refused by the server with 413.13    public static let maxDataBytes = 256 * 10241415    private func path(_ kind: VQObjectKind, _ id: String? = nil) -> String {16        "/api/v2/objects/\(VQRequest.segment(kind.rawValue))" + (id.map { "/\(VQRequest.segment($0))" } ?? "")17    }1819    /// Live objects of a kind, newest first.20    public func list(_ kind: VQObjectKind) async throws -> [VQObjectEnvelope] {21        try await client.json(.get(path(kind))).models("objects")22    }2324    /// One object; `VQError.notFound` when missing or deleted.25    public func get(_ kind: VQObjectKind, _ id: String) async throws -> VQObjectEnvelope {26        let j = try await client.json(.get(path(kind, id)))27        return VQObjectEnvelope(json: j["object"] ?? j)       // the server wraps it in { object }28    }2930    /// Writes `data`. `baseRev: 0` creates (or re-creates over a tombstone); otherwise the write is accepted only if31    /// `baseRev` equals the stored `rev`. A 409 is thrown as `VQError.conflict`; read the stored object with32    /// `VQObjectStoreClient.current(of:)`.33    public func put(_ kind: VQObjectKind, _ id: String, data: VQJSON, baseRev: Int) async throws -> VQObjectEnvelope {34        let j = try await client.json(VQRequest(.put, path(kind, id), body: ["data": data, "baseRev": .number(Double(baseRev))]))35        return VQObjectEnvelope(json: j["object"] ?? j)36    }3738    /// Tombstones the object (its content and archived versions are erased). `baseRev` must equal the stored `rev`.39    public func delete(_ kind: VQObjectKind, _ id: String, baseRev: Int) async throws -> VQObjectEnvelope {40        let j = try await client.json(VQRequest(.delete, path(kind, id), query: [VQQueryItem("baseRev", String(baseRev))]))41        return VQObjectEnvelope(json: j["object"] ?? j)42    }4344    /// Replaced revisions, newest first (kinds `VQObjectKind.versioned`).45    public func versions(_ kind: VQObjectKind, _ id: String) async throws -> [VQObjectVersion] {46        try await client.json(.get(path(kind, id) + "/versions")).models("versions")47    }4849    public func version(_ kind: VQObjectKind, _ id: String, rev: Int) async throws -> VQObjectEnvelope {50        let j = try await client.json(.get(path(kind, id) + "/versions/\(rev)"))51        return VQObjectEnvelope(json: j["object"] ?? j)52    }5354    /// One page of the change feed. When `more` is true ask again with `since` = the `seq` of the last entry.55    public func changes(since: Int, kinds: [VQObjectKind]? = nil, limit: Int = 500) async throws -> VQChangesPage {56        var q = [VQQueryItem("since", String(since)), VQQueryItem("limit", String(min(1000, max(1, limit))))]57        if let kinds, !kinds.isEmpty { q.append(VQQueryItem("kinds", kinds.map(\.rawValue).joined(separator: ","))) }58        return try await client.decode(.get("/api/v2/sync/changes", q))59    }6061    /// The sync stream: `hello`, `change`, `hint` (heartbeats are consumed by the parser).62    public func stream() async throws -> AsyncThrowingStream<VQSyncStreamEvent, Error> {63        let events = try await client.events(VQRequest(.get, "/api/v2/sync/stream", timeout: 90))64        return AsyncThrowingStream { continuation in65            let task = Task {66                do {67                    for try await e in events { continuation.yield(VQSyncStreamEvent(e)) }68                    continuation.finish()69                } catch { continuation.finish(throwing: error) }70            }71            continuation.onTermination = { _ in task.cancel() }72        }73    }7475    /// The stored envelope carried by a 409 (`{ "error": "conflict", "current": … }`).76    public static func current(of error: VQError) -> VQObjectEnvelope? {77        guard error.kind == .conflict, let c = error.body?["current"], c.objectValue != nil else { return nil }78        return VQObjectEnvelope(json: c)79    }80}81
Files main
Menu

Theme