Functions.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. import FirebaseMessagingInterop
  19. import FirebaseSharedSwift
  20. #if COCOAPODS
  21. import GTMSessionFetcher
  22. #else
  23. import GTMSessionFetcherCore
  24. #endif
  25. // Avoids exposing internal FirebaseCore APIs to Swift users.
  26. @_implementationOnly import FirebaseCoreExtension
  27. /// File specific constants.
  28. private enum Constants {
  29. static let appCheckTokenHeader = "X-Firebase-AppCheck"
  30. static let fcmTokenHeader = "Firebase-Instance-ID-Token"
  31. }
  32. /// Cross SDK constants.
  33. internal enum FunctionsConstants {
  34. static let defaultRegion = "us-central1"
  35. }
  36. /**
  37. * `Functions` is the client for Cloud Functions for a Firebase project.
  38. */
  39. @objc(FIRFunctions) open class Functions: NSObject {
  40. // MARK: - Private Variables
  41. /// The network client to use for http requests.
  42. private let fetcherService: GTMSessionFetcherService
  43. /// The projectID to use for all function references.
  44. private let projectID: String
  45. /// A serializer to encode/decode data and return values.
  46. private let serializer = FUNSerializer()
  47. /// A factory for getting the metadata to include with function calls.
  48. private let contextProvider: FunctionsContextProvider
  49. /// The custom domain to use for all functions references (optional).
  50. internal let customDomain: String?
  51. /// The region to use for all function references.
  52. internal let region: String
  53. // MARK: - Public APIs
  54. /**
  55. * The current emulator origin, or `nil` if it is not set.
  56. */
  57. open private(set) var emulatorOrigin: String?
  58. /**
  59. * Creates a Cloud Functions client using the default or returns a pre-existing instance if it already exists.
  60. * - Returns: A shared Functions instance initialized with the default `FirebaseApp`.
  61. */
  62. @objc(functions) open class func functions() -> Functions {
  63. return functions(
  64. app: FirebaseApp.app(),
  65. region: FunctionsConstants.defaultRegion,
  66. customDomain: nil
  67. )
  68. }
  69. /**
  70. * Creates a Cloud Functions client with the given app, or returns a pre-existing
  71. * instance if one already exists.
  72. * - Parameter app The app for the Firebase project.
  73. * - Returns: A shared Functions instance initialized with the specified `FirebaseApp`.
  74. */
  75. @objc(functionsForApp:) open class func functions(app: FirebaseApp) -> Functions {
  76. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: nil)
  77. }
  78. /**
  79. * Creates a Cloud Functions client with the default app and given region.
  80. * - Parameter region The region for the HTTP trigger, such as `us-central1`.
  81. * - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a custom region.
  82. */
  83. @objc(functionsForRegion:) open class func functions(region: String) -> Functions {
  84. return functions(app: FirebaseApp.app(), region: region, customDomain: nil)
  85. }
  86. /**
  87. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  88. * instance if one already exists.
  89. * - Parameter customDomain A custom domain for the HTTP trigger, such as "https://mydomain.com".
  90. * - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a custom HTTP trigger domain.
  91. */
  92. @objc(functionsForCustomDomain:) open class func functions(customDomain: String) -> Functions {
  93. return functions(app: FirebaseApp.app(),
  94. region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  95. }
  96. /**
  97. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  98. * instance if one already exists.
  99. * - Parameters:
  100. * - app: The app for the Firebase project.
  101. * - region: The region for the HTTP trigger, such as `us-central1`.
  102. * - Returns: An instance of `Functions` with a custom app and region.
  103. */
  104. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp,
  105. region: String) -> Functions {
  106. return functions(app: app, region: region, customDomain: nil)
  107. }
  108. /**
  109. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  110. * instance if one already exists.
  111. * - Parameters:
  112. * - app The app for the Firebase project.
  113. * - customDomain A custom domain for the HTTP trigger, such as `https://mydomain.com`.
  114. * - Returns: An instance of `Functions` with a custom app and HTTP trigger domain.
  115. */
  116. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp,
  117. customDomain: String)
  118. -> Functions {
  119. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  120. }
  121. /**
  122. * Creates a reference to the Callable HTTPS trigger with the given name.
  123. * - Parameter name The name of the Callable HTTPS trigger.
  124. */
  125. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  126. return HTTPSCallable(functions: self, name: name)
  127. }
  128. @objc(HTTPSCallableWithURL:) open func httpsCallable(_ url: URL) -> HTTPSCallable {
  129. return HTTPSCallable(functions: self, url: url)
  130. }
  131. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  132. /// request and the type of a `Decodable` response.
  133. /// - Parameter name: The name of the Callable HTTPS trigger
  134. /// - Parameter requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  135. /// - Parameter responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  136. /// - Parameter encoder: The encoder instance to use to run the encoding.
  137. /// - Parameter decoder: The decoder instance to use to run the decoding.
  138. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations.
  139. open func httpsCallable<Request: Encodable,
  140. Response: Decodable>(_ name: String,
  141. requestAs: Request.Type = Request.self,
  142. responseAs: Response.Type = Response.self,
  143. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  144. ),
  145. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  146. ))
  147. -> Callable<Request, Response> {
  148. return Callable(callable: httpsCallable(name), encoder: encoder, decoder: decoder)
  149. }
  150. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  151. /// request and the type of a `Decodable` response.
  152. /// - Parameter url: The url of the Callable HTTPS trigger
  153. /// - Parameter requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  154. /// - Parameter responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  155. /// - Parameter encoder: The encoder instance to use to run the encoding.
  156. /// - Parameter decoder: The decoder instance to use to run the decoding.
  157. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations.
  158. open func httpsCallable<Request: Encodable,
  159. Response: Decodable>(_ url: URL,
  160. requestAs: Request.Type = Request.self,
  161. responseAs: Response.Type = Response.self,
  162. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  163. ),
  164. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  165. ))
  166. -> Callable<Request, Response> {
  167. return Callable(callable: httpsCallable(url), encoder: encoder, decoder: decoder)
  168. }
  169. /**
  170. * Changes this instance to point to a Cloud Functions emulator running locally.
  171. * See https://firebase.google.com/docs/functions/local-emulator
  172. * - Parameters:
  173. * - host: The host of the local emulator, such as "localhost".
  174. * - port: The port of the local emulator, for example 5005.
  175. */
  176. @objc open func useEmulator(withHost host: String, port: Int) {
  177. let prefix = host.hasPrefix("http") ? "" : "http://"
  178. let origin = String(format: "\(prefix)\(host):%li", port)
  179. emulatorOrigin = origin
  180. }
  181. // MARK: - Private Funcs (or Internal for tests)
  182. /// Solely used to have one precondition and one location where we fetch from the container. This
  183. /// previously was avoided due to default arguments but that doesn't work well with Obj-C compatibility.
  184. private class func functions(app: FirebaseApp?, region: String,
  185. customDomain: String?) -> Functions {
  186. precondition(app != nil,
  187. "`FirebaseApp.configure()` needs to be called before using Functions.")
  188. let provider = app!.container.instance(for: FunctionsProvider.self) as? FunctionsProvider
  189. return provider!.functions(for: app!,
  190. region: region,
  191. customDomain: customDomain,
  192. type: self)
  193. }
  194. @objc internal init(projectID: String,
  195. region: String,
  196. customDomain: String?,
  197. auth: AuthInterop?,
  198. messaging: MessagingInterop?,
  199. appCheck: AppCheckInterop?,
  200. fetcherService: GTMSessionFetcherService = GTMSessionFetcherService()) {
  201. self.projectID = projectID
  202. self.region = region
  203. self.customDomain = customDomain
  204. emulatorOrigin = nil
  205. contextProvider = FunctionsContextProvider(auth: auth,
  206. messaging: messaging,
  207. appCheck: appCheck)
  208. self.fetcherService = fetcherService
  209. }
  210. /// Using the component system for initialization.
  211. internal convenience init(app: FirebaseApp,
  212. region: String,
  213. customDomain: String?) {
  214. // TODO: These are not optionals, but they should be.
  215. let auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  216. let messaging = ComponentType<MessagingInterop>.instance(for: MessagingInterop.self,
  217. in: app.container)
  218. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  219. in: app.container)
  220. guard let projectID = app.options.projectID else {
  221. fatalError("Firebase Functions requires the projectID to be set in the App's Options.")
  222. }
  223. self.init(projectID: projectID,
  224. region: region,
  225. customDomain: customDomain,
  226. auth: auth,
  227. messaging: messaging,
  228. appCheck: appCheck)
  229. }
  230. internal func urlWithName(_ name: String) -> String {
  231. assert(!name.isEmpty, "Name cannot be empty")
  232. // Check if we're using the emulator
  233. if let emulatorOrigin = emulatorOrigin {
  234. return "\(emulatorOrigin)/\(projectID)/\(region)/\(name)"
  235. }
  236. // Check the custom domain.
  237. if let customDomain = customDomain {
  238. return "\(customDomain)/\(name)"
  239. }
  240. return "https://\(region)-\(projectID).cloudfunctions.net/\(name)"
  241. }
  242. internal func callFunction(name: String,
  243. withObject data: Any?,
  244. timeout: TimeInterval,
  245. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  246. // Get context first.
  247. contextProvider.getContext { context, error in
  248. // Note: context is always non-nil since some checks could succeed, we're only failing if
  249. // there's an error.
  250. if let error = error {
  251. completion(.failure(error))
  252. } else {
  253. let url = self.urlWithName(name)
  254. self.callFunction(url: URL(string: url)!,
  255. withObject: data,
  256. timeout: timeout,
  257. context: context,
  258. completion: completion)
  259. }
  260. }
  261. }
  262. internal func callFunction(url: URL,
  263. withObject data: Any?,
  264. timeout: TimeInterval,
  265. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  266. // Get context first.
  267. contextProvider.getContext { context, error in
  268. // Note: context is always non-nil since some checks could succeed, we're only failing if
  269. // there's an error.
  270. if let error = error {
  271. completion(.failure(error))
  272. } else {
  273. self.callFunction(url: url,
  274. withObject: data,
  275. timeout: timeout,
  276. context: context,
  277. completion: completion)
  278. }
  279. }
  280. }
  281. private func callFunction(url: URL,
  282. withObject data: Any?,
  283. timeout: TimeInterval,
  284. context: FunctionsContext,
  285. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  286. let request = URLRequest(url: url,
  287. cachePolicy: .useProtocolCachePolicy,
  288. timeoutInterval: timeout)
  289. let fetcher = fetcherService.fetcher(with: request)
  290. let body = NSMutableDictionary()
  291. // Encode the data in the body.
  292. var localData = data
  293. if data == nil {
  294. localData = NSNull()
  295. }
  296. // Force unwrap to match the old invalid argument thrown.
  297. let encoded = try! serializer.encode(localData!)
  298. body["data"] = encoded
  299. do {
  300. let payload = try JSONSerialization.data(withJSONObject: body)
  301. fetcher.bodyData = payload
  302. } catch {
  303. DispatchQueue.main.async {
  304. completion(.failure(error))
  305. }
  306. return
  307. }
  308. // Set the headers.
  309. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  310. if let authToken = context.authToken {
  311. let value = "Bearer \(authToken)"
  312. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  313. }
  314. if let fcmToken = context.fcmToken {
  315. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  316. }
  317. if let appCheckToken = context.appCheckToken {
  318. fetcher.setRequestValue(appCheckToken, forHTTPHeaderField: Constants.appCheckTokenHeader)
  319. }
  320. // Override normal security rules if this is a local test.
  321. if emulatorOrigin != nil {
  322. fetcher.allowLocalhostRequest = true
  323. fetcher.allowedInsecureSchemes = ["http"]
  324. }
  325. fetcher.beginFetch { data, error in
  326. // If there was an HTTP error, convert it to our own error domain.
  327. var localError: Error?
  328. if let error = error as NSError? {
  329. if error.domain == kGTMSessionFetcherStatusDomain {
  330. localError = FunctionsErrorForResponse(
  331. status: error.code,
  332. body: data,
  333. serializer: self.serializer
  334. )
  335. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  336. localError = FunctionsErrorCode.deadlineExceeded.generatedError(userInfo: nil)
  337. }
  338. // If there was an error, report it to the user and stop.
  339. if let localError = localError {
  340. completion(.failure(localError))
  341. } else {
  342. completion(.failure(error))
  343. }
  344. return
  345. } else {
  346. // If there wasn't an HTTP error, see if there was an error in the body.
  347. if let bodyError = FunctionsErrorForResponse(
  348. status: 200,
  349. body: data,
  350. serializer: self.serializer
  351. ) {
  352. completion(.failure(bodyError))
  353. return
  354. }
  355. }
  356. // Porting: this check is new since we didn't previously check if `data` was nil.
  357. guard let data = data else {
  358. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: nil)))
  359. return
  360. }
  361. let responseJSONObject: Any
  362. do {
  363. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  364. } catch {
  365. completion(.failure(error))
  366. return
  367. }
  368. guard let responseJSON = responseJSONObject as? NSDictionary else {
  369. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  370. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  371. return
  372. }
  373. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  374. let dataJSON = responseJSON["data"] ?? responseJSON["result"]
  375. guard let dataJSON = dataJSON as AnyObject? else {
  376. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  377. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  378. return
  379. }
  380. let resultData: Any?
  381. do {
  382. resultData = try self.serializer.decode(dataJSON)
  383. } catch {
  384. completion(.failure(error))
  385. return
  386. }
  387. // TODO: Force unwrap... gross
  388. let result = HTTPSCallableResult(data: resultData!)
  389. // TODO: This copied comment appears to be incorrect - it's impossible to have a nil callable result
  390. // If there's no result field, this will return nil, which is fine.
  391. completion(.success(result))
  392. }
  393. }
  394. }