HTTPSCallable.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. /// A `HTTPSCallableResult` contains the result of calling a `HTTPSCallable`.
  16. @objc(FIRHTTPSCallableResult)
  17. open class HTTPSCallableResult: NSObject {
  18. /// The data that was returned from the Callable HTTPS trigger.
  19. ///
  20. /// The data is in the form of native objects. For example, if your trigger returned an
  21. /// array, this object would be an `Array<Any>`. If your trigger returned a JavaScript object with
  22. /// keys and values, this object would be an instance of `[String: Any]`.
  23. @objc public let data: Any
  24. init(data: Any) {
  25. self.data = data
  26. }
  27. }
  28. /// A `HTTPSCallable` is a reference to a particular Callable HTTPS trigger in Cloud Functions.
  29. @objc(FIRHTTPSCallable)
  30. open class HTTPSCallable: NSObject, @unchecked Sendable {
  31. // MARK: - Private Properties
  32. /// Until this class can be marked *checked* `Sendable`, it's implementation
  33. /// is delegated to an auxiliary class that is checked Sendable.
  34. private let sendableCallable: SendableHTTPSCallable
  35. // MARK: - Public Properties
  36. /// The timeout to use when calling the function. Defaults to 70 seconds.
  37. @objc open var timeoutInterval: TimeInterval {
  38. get { sendableCallable.timeoutInterval }
  39. set { sendableCallable.timeoutInterval = newValue }
  40. }
  41. init(functions: Functions, url: URL, options: HTTPSCallableOptions? = nil) {
  42. sendableCallable = SendableHTTPSCallable(functions: functions, url: url, options: options)
  43. }
  44. /// Executes this Callable HTTPS trigger asynchronously.
  45. ///
  46. /// The data passed into the trigger can be any of the following types:
  47. /// - `nil` or `NSNull`
  48. /// - `String`
  49. /// - `NSNumber`, or any Swift numeric type bridgeable to `NSNumber`
  50. /// - `[Any]`, where the contained objects are also one of these types.
  51. /// - `[String: Any]` where the values are also one of these types.
  52. ///
  53. /// The request to the Cloud Functions backend made by this method automatically includes a
  54. /// Firebase Installations ID token to identify the app instance. If a user is logged in with
  55. /// Firebase Auth, an auth ID token for the user is also automatically included.
  56. ///
  57. /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect
  58. /// information
  59. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  60. /// resumes with a new FCM Token the next time you call this method.
  61. ///
  62. /// - Parameters:
  63. /// - data: Parameters to pass to the trigger.
  64. /// - completion: The block to call when the HTTPS request has completed.
  65. @available(swift 1000.0) // Objective-C only API
  66. @objc(callWithObject:completion:) open func call(_ data: Any? = nil,
  67. completion: @escaping @MainActor (HTTPSCallableResult?,
  68. Error?)
  69. -> Void) {
  70. sendableCallable.call(SendableWrapper(value: data as Any), completion: completion)
  71. }
  72. /// Executes this Callable HTTPS trigger asynchronously.
  73. ///
  74. /// The data passed into the trigger can be any of the following types:
  75. /// - `nil` or `NSNull`
  76. /// - `String`
  77. /// - `NSNumber`, or any Swift numeric type bridgeable to `NSNumber`
  78. /// - `[Any]`, where the contained objects are also one of these types.
  79. /// - `[String: Any]` where the values are also one of these types.
  80. ///
  81. /// The request to the Cloud Functions backend made by this method automatically includes a
  82. /// Firebase Installations ID token to identify the app instance. If a user is logged in with
  83. /// Firebase Auth, an auth ID token for the user is also automatically included.
  84. ///
  85. /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect
  86. /// information
  87. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  88. /// resumes with a new FCM Token the next time you call this method.
  89. ///
  90. /// - Parameters:
  91. /// - data: Parameters to pass to the trigger.
  92. /// - completion: The block to call when the HTTPS request has completed.
  93. @nonobjc open func call(_ data: sending Any? = nil,
  94. completion: @escaping @MainActor (HTTPSCallableResult?,
  95. Error?)
  96. -> Void) {
  97. sendableCallable.call(data, completion: completion)
  98. }
  99. /// Executes this Callable HTTPS trigger asynchronously. This API should only be used from
  100. /// Objective-C.
  101. ///
  102. /// The request to the Cloud Functions backend made by this method automatically includes a
  103. /// Firebase Installations ID token to identify the app instance. If a user is logged in with
  104. /// Firebase Auth, an auth ID token for the user is also automatically included.
  105. ///
  106. /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect
  107. /// information
  108. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  109. /// resumes with a new FCM Token the next time you call this method.
  110. ///
  111. /// - Parameter completion: The block to call when the HTTPS request has completed.
  112. @objc(callWithCompletion:) public func __call(completion: @escaping @MainActor (HTTPSCallableResult?,
  113. Error?) -> Void) {
  114. call(nil, completion: completion)
  115. }
  116. /// Executes this Callable HTTPS trigger asynchronously.
  117. ///
  118. /// The request to the Cloud Functions backend made by this method automatically includes a
  119. /// FCM token to identify the app instance. If a user is logged in with Firebase
  120. /// Auth, an auth ID token for the user is also automatically included.
  121. ///
  122. /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect
  123. /// information
  124. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  125. /// resumes with a new FCM Token the next time you call this method.
  126. ///
  127. /// - Parameter data: Parameters to pass to the trigger.
  128. /// - Throws: An error if the Cloud Functions invocation failed.
  129. /// - Returns: The result of the call.
  130. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  131. open func call(_ data: Any? = nil) async throws -> sending HTTPSCallableResult {
  132. try await sendableCallable.call(data)
  133. }
  134. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  135. func stream(_ data: SendableWrapper? = nil) -> AsyncThrowingStream<JSONStreamResponse, Error> {
  136. sendableCallable.stream(data)
  137. }
  138. }
  139. private extension HTTPSCallable {
  140. final class SendableHTTPSCallable: Sendable {
  141. // MARK: - Private Properties
  142. // The functions client to use for making calls.
  143. private let functions: Functions
  144. private let url: URL
  145. private let options: HTTPSCallableOptions?
  146. // MARK: - Public Properties
  147. let _timeoutInterval: AtomicBox<TimeInterval> = .init(70)
  148. /// The timeout to use when calling the function. Defaults to 70 seconds.
  149. var timeoutInterval: TimeInterval {
  150. get { _timeoutInterval.value() }
  151. set {
  152. _timeoutInterval.withLock { timeoutInterval in
  153. timeoutInterval = newValue
  154. }
  155. }
  156. }
  157. init(functions: Functions, url: URL, options: HTTPSCallableOptions? = nil) {
  158. self.functions = functions
  159. self.url = url
  160. self.options = options
  161. }
  162. func call(_ data: sending Any? = nil,
  163. completion: @escaping @MainActor (HTTPSCallableResult?, Error?) -> Void) {
  164. let data = (data as? SendableWrapper)?.value ?? data
  165. if #available(iOS 13, macCatalyst 13, macOS 10.15, tvOS 13, watchOS 7, *) {
  166. Task {
  167. do {
  168. let result = try await call(data)
  169. await completion(result, nil)
  170. } catch {
  171. await completion(nil, error)
  172. }
  173. }
  174. } else {
  175. // This isn’t expected to ever be called because Functions
  176. // doesn’t officially support the older platforms.
  177. functions.callFunction(
  178. at: url,
  179. withObject: data,
  180. options: options,
  181. timeout: timeoutInterval
  182. ) { result in
  183. switch result {
  184. case let .success(callableResult):
  185. DispatchQueue.main.async {
  186. completion(callableResult, nil)
  187. }
  188. case let .failure(error):
  189. DispatchQueue.main.async {
  190. completion(nil, error)
  191. }
  192. }
  193. }
  194. }
  195. }
  196. func __call(completion: @escaping @MainActor (HTTPSCallableResult?, Error?) -> Void) {
  197. call(nil, completion: completion)
  198. }
  199. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  200. func call(_ data: Any? = nil) async throws -> sending HTTPSCallableResult {
  201. try await functions
  202. .callFunction(at: url, withObject: data, options: options, timeout: timeoutInterval)
  203. }
  204. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  205. func stream(_ data: SendableWrapper? = nil) -> AsyncThrowingStream<JSONStreamResponse, Error> {
  206. functions.stream(at: url, data: data, options: options, timeout: timeoutInterval)
  207. }
  208. }
  209. }