Skip to content

Commit

Permalink
chore: rename ObjectValue to Payload
Browse files Browse the repository at this point in the history
  • Loading branch information
drochetti committed Dec 12, 2023
1 parent 012a765 commit a261571
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 60 deletions.
12 changes: 6 additions & 6 deletions Sources/FalClient/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}

Expand All @@ -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,
Expand Down
12 changes: 4 additions & 8 deletions Sources/FalClient/FalClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -72,7 +72,7 @@ public enum ObjectValue: Codable {

// MARK: - Expressible

extension ObjectValue: ExpressibleByStringLiteral {
extension Payload: ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self = .string(value)
}
Expand All @@ -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]
}
Expand All @@ -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
Expand All @@ -168,22 +168,22 @@ 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 {
return rhs == .nilValue
}
}

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):
Expand Down
12 changes: 6 additions & 6 deletions Sources/FalClient/Queue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ 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.
func status(_ id: String, of requestId: String, includeLogs: Bool) async throws -> QueueStatus

/// 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
Expand All @@ -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)
}

Expand All @@ -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
Expand All @@ -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)
)
}
Expand Down
26 changes: 14 additions & 12 deletions Sources/FalClient/Realtime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -106,8 +106,10 @@ public class BaseRealtimeConnection<Input: Encodable> {
}
}

public class RealtimeConnection: BaseRealtimeConnection<ObjectValue> {}
/// Connection implementation that can be used to send messages using the `Payload` type.
public class RealtimeConnection: BaseRealtimeConnection<Payload> {}

/// Connection implementation that can be used to send messages using a custom `Encodable` type.
public class TypedRealtimeConnection<Input: Encodable>: BaseRealtimeConnection<Input> {}

func buildRealtimeUrl(forApp app: String, host: String, token: String? = nil) -> URL {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -310,17 +312,17 @@ public protocol Realtime {
to app: String,
connectionKey: String,
throttleInterval: DispatchTimeInterval,
onResult completion: @escaping (Result<ObjectValue, Error>) -> Void
onResult completion: @escaping (Result<Payload, Error>) -> 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
Expand All @@ -345,14 +347,14 @@ extension WebSocketMessage {
}
}

func decode<Type: Decodable>(to _: Type.Type) throws -> Type {
func decode<Type: Decodable>(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())
}
}
}
Expand All @@ -371,7 +373,7 @@ public struct RealtimeClient: Realtime {
to app: String,
connectionKey: String,
throttleInterval: DispatchTimeInterval,
onResult completion: @escaping (Result<ObjectValue, Error>) -> Void
onResult completion: @escaping (Result<Payload, Error>) -> Void
) throws -> RealtimeConnection {
handleConnection(
to: app,
Expand Down Expand Up @@ -445,7 +447,7 @@ public extension Realtime {
to app: String,
connectionKey: String = UUID().uuidString,
throttleInterval: DispatchTimeInterval = .milliseconds(64),
onResult completion: @escaping (Result<ObjectValue, Error>) -> Void
onResult completion: @escaping (Result<Payload, Error>) -> Void
) throws -> RealtimeConnection {
try connect(
to: app,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct ContentView: View {
.font(.largeTitle)
.textFieldStyle(.roundedBorder)
.padding()

if sizeClass == .regular {
HStack(alignment: .center) {
cameraView
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ 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 {
process(image: frame)
}
}
}

@Published var currentProcessedFrame: UIImage?
@Published var currentFPS: Double = 0.0
@Published var active: Bool = false
Expand Down
Loading

0 comments on commit a261571

Please sign in to comment.