Functions.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. import FirebaseCore
  16. import FirebaseSharedSwift
  17. #if COCOAPODS
  18. import GTMSessionFetcher
  19. #else
  20. import GTMSessionFetcherCore
  21. #endif
  22. // PLACEHOLDERS
  23. protocol AuthInterop {
  24. func getToken(forcingRefresh: Bool, callback: (Result<String, Error>) -> Void)
  25. }
  26. protocol MessagingInterop {
  27. var fcmToken: String { get }
  28. }
  29. protocol AppCheckInterop {
  30. func getToken(forcingRefresh: Bool, callback: (Result<String, Error>) -> Void)
  31. }
  32. // END PLACEHOLDERS
  33. private enum Constants {
  34. static let appCheckTokenHeader = "X-Firebase-AppCheck"
  35. static let fcmTokenHeader = "Firebase-Instance-ID-Token"
  36. }
  37. /**
  38. * `Functions` is the client for Cloud Functions for a Firebase project.
  39. */
  40. @objc public class Functions: NSObject {
  41. // MARK: - Private Variables
  42. /// The network client to use for http requests.
  43. private let fetcherService: GTMSessionFetcherService
  44. // The projectID to use for all function references.
  45. private let projectID: String
  46. // The region to use for all function references.
  47. private let region: String
  48. // The custom domain to use for all functions references (optional).
  49. private let customDomain: String?
  50. // A serializer to encode/decode data and return values.
  51. private let serializer = FUNSerializer()
  52. // A factory for getting the metadata to include with function calls.
  53. private let contextProvider: FunctionsContextProvider
  54. /**
  55. * The current emulator origin, or nil if it is not set.
  56. */
  57. public private(set) var emulatorOrigin: String?
  58. /**
  59. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  60. * instance if one already exists.
  61. * @param app The app for the Firebase project.
  62. * @param region The region for the http trigger, such as "us-central1".
  63. */
  64. public class func functions(app: FirebaseApp = FirebaseApp.app()!,
  65. region: String = "us-central1") -> Functions {
  66. return Functions(app: app, region: region, customDomain: nil)
  67. }
  68. /**
  69. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  70. * instance if one already exists.
  71. * @param app The app for the Firebase project.
  72. * @param customDomain A custom domain for the http trigger, such as "https://mydomain.com".
  73. */
  74. public class func functions(app: FirebaseApp = FirebaseApp.app()!,
  75. customDomain: String) -> Functions {
  76. return Functions(app: app, region: "us-central1", customDomain: customDomain)
  77. }
  78. internal convenience init(app: FirebaseApp,
  79. region: String,
  80. customDomain: String?) {
  81. #warning("Should be fetched from the App's component container instead.")
  82. /*
  83. id<FIRFunctionsProvider> provider = FIR_COMPONENT(FIRFunctionsProvider, app.container);
  84. return [provider functionsForApp:app region:region customDomain:customDomain type:[self class]];
  85. */
  86. self.init(projectID: app.options.projectID!,
  87. region: region,
  88. customDomain: customDomain,
  89. // TODO: Get this out of the app.
  90. auth: nil,
  91. messaging: nil,
  92. appCheck: nil)
  93. }
  94. internal init(projectID: String,
  95. region: String,
  96. customDomain: String?,
  97. auth: AuthInterop?,
  98. messaging: MessagingInterop?,
  99. appCheck: AppCheckInterop?,
  100. fetcherService: GTMSessionFetcherService = GTMSessionFetcherService()) {
  101. self.projectID = projectID
  102. self.region = region
  103. self.customDomain = customDomain
  104. emulatorOrigin = nil
  105. contextProvider = FunctionsContextProvider(auth: auth,
  106. messaging: messaging,
  107. appCheck: appCheck)
  108. self.fetcherService = fetcherService
  109. }
  110. /**
  111. * Creates a reference to the Callable HTTPS trigger with the given name.
  112. * @param name The name of the Callable HTTPS trigger.
  113. */
  114. public func httpsCallable(_ name: String) -> HTTPSCallable {
  115. return HTTPSCallable(functions: self, name: name)
  116. }
  117. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  118. /// request and the type of a `Decodable` response.
  119. /// - Parameter name: The name of the Callable HTTPS trigger
  120. /// - Parameter requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  121. /// - Parameter responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  122. /// - Parameter encoder: The encoder instance to use to run the encoding.
  123. /// - Parameter decoder: The decoder instance to use to run the decoding.
  124. public func httpsCallable<Request: Encodable,
  125. Response: Decodable>(_ name: String,
  126. requestAs: Request.Type = Request.self,
  127. responseAs: Response.Type = Response.self,
  128. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  129. ),
  130. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  131. ))
  132. -> Callable<Request, Response> {
  133. return Callable(callable: httpsCallable(name), encoder: encoder, decoder: decoder)
  134. }
  135. /**
  136. * Changes this instance to point to a Cloud Functions emulator running locally.
  137. * See https://firebase.google.com/docs/functions/local-emulator
  138. * @param host The host of the local emulator, such as "localhost".
  139. * @param port The port of the local emulator, for example 5005.
  140. */
  141. public func useEmulator(withHost host: String, port: Int) {
  142. let prefix = host.hasPrefix("http") ? "" : "http://"
  143. let origin = String(format: "\(prefix)\(host):%li", port)
  144. emulatorOrigin = origin
  145. }
  146. // MARK: - Private Funcs
  147. private func urlWithName(_ name: String) -> String {
  148. assert(!name.isEmpty, "Name cannot be empty")
  149. // Check if we're using the emulator
  150. if let emulatorOrigin = emulatorOrigin {
  151. return "\(emulatorOrigin)/\(projectID)/\(region)/\(name)"
  152. }
  153. // Check the custom domain.
  154. if let customDomain = customDomain {
  155. return "\(customDomain)/\(name)"
  156. }
  157. return "https://\(region)-\(projectID).cloudfunctions.net/\(name)"
  158. }
  159. internal func callFunction(name: String,
  160. withObject data: Any?,
  161. timeout: TimeInterval,
  162. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  163. // Get context first.
  164. contextProvider.getContext { context, error in
  165. // Note: context is always non-nil since some checks could succeed, we're only failing if
  166. // there's an error.
  167. if let error = error {
  168. completion(.failure(error))
  169. } else {
  170. self.callFunction(name: name,
  171. withObject: data,
  172. timeout: timeout,
  173. context: context,
  174. completion: completion)
  175. }
  176. }
  177. }
  178. private func callFunction(name: String,
  179. withObject data: Any?,
  180. timeout: TimeInterval,
  181. context: FunctionsContext,
  182. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  183. let url = URL(string: urlWithName(name))!
  184. let request = URLRequest(url: url,
  185. cachePolicy: .useProtocolCachePolicy,
  186. timeoutInterval: timeout)
  187. let fetcher = fetcherService.fetcher(with: request)
  188. let body = NSMutableDictionary()
  189. // Encode the data in the body.
  190. var localData = data
  191. if data == nil {
  192. localData = NSNull()
  193. }
  194. // Force unwrap to match the old invalid argument thrown.
  195. let encoded = try! serializer.encode(localData!)
  196. body["data"] = encoded
  197. do {
  198. let payload = try JSONSerialization.data(withJSONObject: body)
  199. fetcher.bodyData = payload
  200. } catch {
  201. DispatchQueue.main.async {
  202. completion(.failure(error))
  203. }
  204. return
  205. }
  206. // Set the headers.
  207. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  208. if let authToken = context.authToken {
  209. let value = "Bearer \(authToken)"
  210. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  211. }
  212. if let fcmToken = context.fcmToken {
  213. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  214. }
  215. if let appCheckToken = context.appCheckToken {
  216. fetcher.setRequestValue(appCheckToken, forHTTPHeaderField: Constants.appCheckTokenHeader)
  217. }
  218. // Override normal security rules if this is a local test.
  219. if emulatorOrigin != nil {
  220. fetcher.allowLocalhostRequest = true
  221. fetcher.allowedInsecureSchemes = ["http"]
  222. }
  223. fetcher.beginFetch { data, error in
  224. // If there was an HTTP error, convert it to our own error domain.
  225. var localError: Error?
  226. if let error = error as NSError? {
  227. if error.domain == kGTMSessionFetcherStatusDomain {
  228. localError = FunctionsErrorForResponse(
  229. status: error.code,
  230. body: data,
  231. serializer: self.serializer
  232. )
  233. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  234. localError = FunctionsErrorCode.deadlineExceeded.generatedError(userInfo: nil)
  235. }
  236. } else {
  237. // If there wasn't an HTTP error, see if there was an error in the body.
  238. localError = FunctionsErrorForResponse(status: 200, body: data, serializer: self.serializer)
  239. }
  240. // If there was an error, report it to the user and stop.
  241. if let localError = localError {
  242. completion(.failure(localError))
  243. return
  244. }
  245. // Porting: this check is new since we didn't previously check if `data` was nil.
  246. guard let data = data else {
  247. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: nil)))
  248. return
  249. }
  250. let responseJSONObject: Any
  251. do {
  252. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  253. } catch {
  254. completion(.failure(error))
  255. return
  256. }
  257. guard let responseJSON = responseJSONObject as? NSDictionary else {
  258. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  259. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  260. return
  261. }
  262. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  263. let dataJSON = responseJSON["data"] ?? responseJSON["result"]
  264. guard let dataJSON = dataJSON as AnyObject? else {
  265. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  266. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  267. return
  268. }
  269. let resultData: Any?
  270. do {
  271. resultData = try self.serializer.decode(dataJSON)
  272. } catch {
  273. completion(.failure(error))
  274. return
  275. }
  276. // TODO: Force unwrap... gross
  277. let result = HTTPSCallableResult(data: resultData!)
  278. #warning(
  279. "This copied comment appears to be incorrect - it's impossible to have a nil callable result."
  280. )
  281. // If there's no result field, this will return nil, which is fine.
  282. completion(.success(result))
  283. }
  284. }
  285. }