From a261571934b0dd5b89de1c19d993a2cd5828bd94 Mon Sep 17 00:00:00 2001 From: Daniel Rochetti Date: Tue, 12 Dec 2023 10:46:58 -0800 Subject: [PATCH] chore: rename ObjectValue to Payload --- Sources/FalClient/Client.swift | 12 ++--- Sources/FalClient/FalClient.swift | 12 ++--- .../{ObjectValue.swift => Payload.swift} | 46 +++++++++---------- Sources/FalClient/Queue.swift | 12 ++--- Sources/FalClient/Realtime.swift | 26 ++++++----- .../FalCameraSampleApp/ContentView.swift | 2 +- .../ImageStreamingModel.swift | 2 + .../xcshareddata/swiftpm/Package.resolved | 8 ++-- 8 files changed, 60 insertions(+), 60 deletions(-) rename Sources/FalClient/{ObjectValue.swift => Payload.swift} (81%) diff --git a/Sources/FalClient/Client.swift b/Sources/FalClient/Client.swift index f02335c..1a2f3c6 100644 --- a/Sources/FalClient/Client.swift +++ b/Sources/FalClient/Client.swift @@ -37,16 +37,16 @@ public protocol Client { var realtime: Realtime { get } - func run(_ id: String, input: ObjectValue?, options: RunOptions) async throws -> ObjectValue + func run(_ id: String, input: Payload?, options: RunOptions) async throws -> Payload func subscribe( to app: String, - input: ObjectValue?, + input: Payload?, pollInterval: DispatchTimeInterval, timeout: DispatchTimeInterval, includeLogs: Bool, onQueueUpdate: OnQueueUpdate? - ) async throws -> ObjectValue + ) async throws -> Payload } public extension Client { @@ -61,7 +61,7 @@ public extension Client { /// - app: The id of the model app. /// - input: The input to the model. /// - options: The request options. - func run(_ app: String, input: ObjectValue? = nil, options: RunOptions = DefaultRunOptions) async throws -> ObjectValue { + func run(_ app: String, input: Payload? = nil, options: RunOptions = DefaultRunOptions) async throws -> Payload { try await run(app, input: input, options: options) } @@ -80,12 +80,12 @@ public extension Client { /// - onQueueUpdate: A callback to be called when the queue status is updated. func subscribe( to app: String, - input: ObjectValue? = nil, + input: Payload? = nil, pollInterval: DispatchTimeInterval = .seconds(1), timeout: DispatchTimeInterval = .minutes(3), includeLogs: Bool = false, onQueueUpdate: OnQueueUpdate? = nil - ) async throws -> ObjectValue { + ) async throws -> Payload { try await subscribe(to: app, input: input, pollInterval: pollInterval, diff --git a/Sources/FalClient/FalClient.swift b/Sources/FalClient/FalClient.swift index c9b5256..49b34f1 100644 --- a/Sources/FalClient/FalClient.swift +++ b/Sources/FalClient/FalClient.swift @@ -31,27 +31,23 @@ public struct FalClient: Client { public var realtime: Realtime { RealtimeClient(client: self) } - public func run(_ app: String, input: ObjectValue?, options: RunOptions) async throws -> ObjectValue { + public func run(_ app: String, input: Payload?, options: RunOptions) async throws -> Payload { let inputData = input != nil ? try JSONEncoder().encode(input) : nil let queryParams = options.httpMethod == .get ? input : nil let url = buildUrl(fromId: app, path: options.path) let data = try await sendRequest(url, input: inputData, queryParams: queryParams?.asDictionary, options: options) -// guard let result = try? JSON(data: data) else { -// throw FalError.invalidResultFormat -// } -// return result let decoder = JSONDecoder() - return try decoder.decode(ObjectValue.self, from: data) + return try decoder.decode(Payload.self, from: data) } public func subscribe( to app: String, - input: ObjectValue?, + input: Payload?, pollInterval: DispatchTimeInterval, timeout: DispatchTimeInterval, includeLogs: Bool, onQueueUpdate: OnQueueUpdate? - ) async throws -> ObjectValue { + ) async throws -> Payload { let requestId = try await queue.submit(app, input: input) let start = Int(Date().timeIntervalSince1970 * 1000) var elapsed = 0 diff --git a/Sources/FalClient/ObjectValue.swift b/Sources/FalClient/Payload.swift similarity index 81% rename from Sources/FalClient/ObjectValue.swift rename to Sources/FalClient/Payload.swift index 69a1309..c3b351b 100644 --- a/Sources/FalClient/ObjectValue.swift +++ b/Sources/FalClient/Payload.swift @@ -2,19 +2,19 @@ import Foundation /// Represents a value that can be encoded and decoded. This data structure /// is used to represent the input and output of the model API and closely -/// matches the JSON data structure. +/// matches a JSON data structure. /// /// It supports binary data as well, so it can be kept and transformed if needed /// before it's encoded to JSON or any other supported format (e.g. msgpack). -public enum ObjectValue: Codable { +public enum Payload: Codable { case string(String) case int(Int) case bool(Bool) case double(Double) case date(Date) case data(Data) - case array([ObjectValue]) - case dict([String: ObjectValue]) + case array([Payload]) + case dict([String: Payload]) case nilValue public init(from decoder: Decoder) throws { @@ -31,9 +31,9 @@ public enum ObjectValue: Codable { self = .date(date) } else if let data = try? container.decode(Data.self) { self = .data(data) - } else if let array = try? container.decode([ObjectValue].self) { + } else if let array = try? container.decode([Payload].self) { self = .array(array) - } else if let dict = try? container.decode([String: ObjectValue].self) { + } else if let dict = try? container.decode([String: Payload].self) { self = .dict(dict) } else { self = .nilValue @@ -72,7 +72,7 @@ public enum ObjectValue: Codable { // MARK: - Expressible -extension ObjectValue: ExpressibleByStringLiteral { +extension Payload: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self = .string(value) } @@ -85,53 +85,53 @@ extension ObjectValue: ExpressibleByStringLiteral { } } -extension ObjectValue: ExpressibleByIntegerLiteral { +extension Payload: ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self = .int(value) } } -extension ObjectValue: ExpressibleByBooleanLiteral { +extension Payload: ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self = .bool(value) } } -extension ObjectValue: ExpressibleByNilLiteral { +extension Payload: ExpressibleByNilLiteral { public init(nilLiteral _: ()) { self = .nilValue } } -extension ObjectValue: ExpressibleByFloatLiteral { +extension Payload: ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self = .double(value) } } -extension ObjectValue: ExpressibleByArrayLiteral { - public init(arrayLiteral elements: ObjectValue...) { +extension Payload: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: Payload...) { self = .array(elements) } } -extension ObjectValue: ExpressibleByDictionaryLiteral { - public init(dictionaryLiteral elements: (String, ObjectValue)...) { +extension Payload: ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, Payload)...) { self = .dict(Dictionary(uniqueKeysWithValues: elements)) } } // MARK: - Subscript -public extension ObjectValue { - subscript(key: String) -> ObjectValue { +public extension Payload { + subscript(key: String) -> Payload { if case let .dict(dict) = self, let value = dict[key] { return value } return .nilValue } - subscript(index: Int) -> ObjectValue { + subscript(index: Int) -> Payload { if case let .array(arr) = self, arr.indices.contains(index) { return arr[index] } @@ -141,8 +141,8 @@ public extension ObjectValue { // MARK: - Equatable -extension ObjectValue: Equatable { - public static func == (lhs: ObjectValue, rhs: ObjectValue) -> Bool { +extension Payload: Equatable { + public static func == (lhs: Payload, rhs: Payload) -> Bool { switch (lhs, rhs) { case let (.string(a), .string(b)): return a == b @@ -168,7 +168,7 @@ extension ObjectValue: Equatable { } // Special handling to compare .nilValue with nil - static func == (lhs: ObjectValue?, rhs: ObjectValue) -> Bool { + static func == (lhs: Payload?, rhs: Payload) -> Bool { if let lhs { return lhs == rhs } else { @@ -176,14 +176,14 @@ extension ObjectValue: Equatable { } } - static func == (lhs: ObjectValue, rhs: ObjectValue?) -> Bool { + static func == (lhs: Payload, rhs: Payload?) -> Bool { rhs == lhs } } // MARK: - Converto to native types -extension ObjectValue { +extension Payload { var nativeValue: Any { switch self { case let .string(value): diff --git a/Sources/FalClient/Queue.swift b/Sources/FalClient/Queue.swift index 8e9d140..8022c89 100644 --- a/Sources/FalClient/Queue.swift +++ b/Sources/FalClient/Queue.swift @@ -7,7 +7,7 @@ public protocol Queue { /// Submits a request to the given [id], an optional [path]. This method /// uses the [queue] API to initiate the request. Next you need to rely on /// [status] and [result] to poll for the result. - func submit(_ id: String, input: ObjectValue?, webhookUrl: String?) async throws -> String + func submit(_ id: String, input: Payload?, webhookUrl: String?) async throws -> String /// Checks the queue for the status of the request with the given [requestId]. /// See [QueueStatus] for the different statuses. @@ -15,7 +15,7 @@ public protocol Queue { /// Retrieves the result of the request with the given [requestId] once /// the queue status is [QueueStatus.completed]. - func response(_ id: String, of requestId: String) async throws -> ObjectValue + func response(_ id: String, of requestId: String) async throws -> Payload /// Retrieves the result of the request with the given [requestId] once /// the queue status is [QueueStatus.completed]. This method is type-safe @@ -24,7 +24,7 @@ public protocol Queue { } public extension Queue { - func submit(_ id: String, input: ObjectValue? = nil, webhookUrl: String? = nil) async throws -> String { + func submit(_ id: String, input: Payload? = nil, webhookUrl: String? = nil) async throws -> String { try await submit(id, input: input, webhookUrl: webhookUrl) } @@ -49,7 +49,7 @@ public struct QueueStatusInput: Encodable { public struct QueueClient: Queue { public let client: Client - public func submit(_ id: String, input: ObjectValue?, webhookUrl _: String?) async throws -> String { + public func submit(_ id: String, input: Payload?, webhookUrl _: String?) async throws -> String { let result = try await client.run(id, input: input, options: .route("/fal/queue/submit")) guard case let .string(requestId) = result["request_id"] else { throw FalError.invalidResultFormat @@ -65,10 +65,10 @@ public struct QueueClient: Queue { ) } - public func response(_ id: String, of requestId: String) async throws -> ObjectValue { + public func response(_ id: String, of requestId: String) async throws -> Payload { try await client.run( id, - input: nil as ObjectValue?, + input: nil as Payload?, options: .route("/fal/queue/requests/\(requestId)/response", withMethod: .get) ) } diff --git a/Sources/FalClient/Realtime.swift b/Sources/FalClient/Realtime.swift index 1809499..77530cc 100644 --- a/Sources/FalClient/Realtime.swift +++ b/Sources/FalClient/Realtime.swift @@ -45,7 +45,7 @@ typealias SendFunction = (URLSessionWebSocketTask.Message) throws -> Void typealias CloseFunction = () -> Void func hasBinaryField(_ type: Encodable) -> Bool { - if let object = type as? ObjectValue, + if let object = type as? Payload, case let .dict(dict) = object { return dict.values.contains { @@ -106,8 +106,10 @@ public class BaseRealtimeConnection { } } -public class RealtimeConnection: BaseRealtimeConnection {} +/// Connection implementation that can be used to send messages using the `Payload` type. +public class RealtimeConnection: BaseRealtimeConnection {} +/// Connection implementation that can be used to send messages using a custom `Encodable` type. public class TypedRealtimeConnection: BaseRealtimeConnection {} func buildRealtimeUrl(forApp app: String, host: String, token: String? = nil) -> URL { @@ -235,7 +237,7 @@ class WebSocketConnection: NSObject, URLSessionWebSocketDelegate { do { self?.receiveMessage() - var object = try message.decode(to: ObjectValue.self) + var object = try message.decode(to: Payload.self) if isSuccessResult(object) { self?.onMessage(message) return @@ -310,17 +312,17 @@ public protocol Realtime { to app: String, connectionKey: String, throttleInterval: DispatchTimeInterval, - onResult completion: @escaping (Result) -> Void + onResult completion: @escaping (Result) -> Void ) throws -> RealtimeConnection } -func isSuccessResult(_ message: ObjectValue) -> Bool { +func isSuccessResult(_ message: Payload) -> Bool { message["status"].stringValue != "error" && message["type"].stringValue != "x-fal-message" && message["type"].stringValue != "x-fal-error" } -func getError(_ message: ObjectValue) -> FalRealtimeError? { +func getError(_ message: Payload) -> FalRealtimeError? { if message["type"].stringValue != "x-fal-error", let error = message["error"].stringValue, let reason = message["reason"].stringValue @@ -345,14 +347,14 @@ extension WebSocketMessage { } } - func decode(to _: Type.Type) throws -> Type { + func decode(to type: Type.Type) throws -> Type { switch self { case let .data(data): - return try MessagePackDecoder().decode(Type.self, from: data) + return try MessagePackDecoder().decode(type, from: data) case .string: - return try JSONDecoder().decode(Type.self, from: data()) + return try JSONDecoder().decode(type, from: data()) @unknown default: - return try JSONDecoder().decode(Type.self, from: data()) + return try JSONDecoder().decode(type, from: data()) } } } @@ -371,7 +373,7 @@ public struct RealtimeClient: Realtime { to app: String, connectionKey: String, throttleInterval: DispatchTimeInterval, - onResult completion: @escaping (Result) -> Void + onResult completion: @escaping (Result) -> Void ) throws -> RealtimeConnection { handleConnection( to: app, @@ -445,7 +447,7 @@ public extension Realtime { to app: String, connectionKey: String = UUID().uuidString, throttleInterval: DispatchTimeInterval = .milliseconds(64), - onResult completion: @escaping (Result) -> Void + onResult completion: @escaping (Result) -> Void ) throws -> RealtimeConnection { try connect( to: app, diff --git a/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ContentView.swift b/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ContentView.swift index e5e8494..fc0beca 100644 --- a/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ContentView.swift +++ b/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ContentView.swift @@ -10,7 +10,7 @@ struct ContentView: View { .font(.largeTitle) .textFieldStyle(.roundedBorder) .padding() - + if sizeClass == .regular { HStack(alignment: .center) { cameraView diff --git a/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ImageStreamingModel.swift b/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ImageStreamingModel.swift index 3b94266..9cd8ca7 100644 --- a/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ImageStreamingModel.swift +++ b/Sources/Samples/FalCameraSampleApp/FalCameraSampleApp/ImageStreamingModel.swift @@ -13,6 +13,7 @@ class ImageStreamingModel: ObservableObject, ImageStreamingDelegate { } } } + @Published var prompt: String = "photo of george clooney, sharp focus, intricate, elegant, realistic, 8k ultra hd" { didSet { if let frame = currentCapturedFrame { @@ -20,6 +21,7 @@ class ImageStreamingModel: ObservableObject, ImageStreamingDelegate { } } } + @Published var currentProcessedFrame: UIImage? @Published var currentFPS: Double = 0.0 @Published var active: Bool = false diff --git a/Sources/Samples/FalSampleApp/FalSampleApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Sources/Samples/FalSampleApp/FalSampleApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index cd2ec89..073d75d 100644 --- a/Sources/Samples/FalSampleApp/FalSampleApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Sources/Samples/FalSampleApp/FalSampleApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -10,12 +10,12 @@ } }, { - "identity" : "swift-msgpack", + "identity" : "msgpack-swift", "kind" : "remoteSourceControl", - "location" : "https://github.com/nnabeyang/swift-msgpack.git", + "location" : "https://github.com/fumoboy007/msgpack-swift.git", "state" : { - "revision" : "65cd65da19270953b72767a71fb1c1d99ea26340", - "version" : "0.2.8" + "revision" : "1e3124367973f45955f27f49a617862605e55288", + "version" : "2.0.0" } } ],