Functions.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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 FirebaseAppCheckInterop
  15. import FirebaseAuthInterop
  16. import FirebaseCore
  17. import FirebaseMessagingInterop
  18. import FirebaseSharedSwift
  19. import Foundation
  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. enum FunctionsConstants {
  34. static let defaultRegion = "us-central1"
  35. }
  36. /// `Functions` is the client for Cloud Functions for a Firebase project.
  37. @objc(FIRFunctions) open class Functions: NSObject {
  38. // MARK: - Private Variables
  39. /// The network client to use for http requests.
  40. private let fetcherService: GTMSessionFetcherService
  41. /// The projectID to use for all function references.
  42. private let projectID: String
  43. /// A serializer to encode/decode data and return values.
  44. private let serializer = FunctionsSerializer()
  45. /// A factory for getting the metadata to include with function calls.
  46. private let contextProvider: FunctionsContextProvider
  47. /// A map of active instances, grouped by app. Keys are FirebaseApp names and values are arrays
  48. /// containing all instances of Functions associated with the given app.
  49. private static var instances: [String: [Functions]] = [:]
  50. /// Lock to manage access to the instances array to avoid race conditions.
  51. private static var instancesLock: os_unfair_lock = .init()
  52. /// The custom domain to use for all functions references (optional).
  53. let customDomain: String?
  54. /// The region to use for all function references.
  55. let region: String
  56. // MARK: - Public APIs
  57. /// The current emulator origin, or `nil` if it is not set.
  58. open private(set) var emulatorOrigin: String?
  59. /// Creates a Cloud Functions client using the default or returns a pre-existing instance if it
  60. /// already exists.
  61. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp`.
  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. /// Creates a Cloud Functions client with the given app, or returns a pre-existing
  70. /// instance if one already exists.
  71. /// - Parameter app: The app for the Firebase project.
  72. /// - Returns: A shared Functions instance initialized with the specified `FirebaseApp`.
  73. @objc(functionsForApp:) open class func functions(app: FirebaseApp) -> Functions {
  74. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: nil)
  75. }
  76. /// Creates a Cloud Functions client with the default app and given region.
  77. /// - Parameter region: The region for the HTTP trigger, such as `us-central1`.
  78. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  79. /// custom region.
  80. @objc(functionsForRegion:) open class func functions(region: String) -> Functions {
  81. return functions(app: FirebaseApp.app(), region: region, customDomain: nil)
  82. }
  83. /// Creates a Cloud Functions client with the given custom domain or returns a pre-existing
  84. /// instance if one already exists.
  85. /// - Parameter customDomain: A custom domain for the HTTP trigger, such as
  86. /// "https://mydomain.com".
  87. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  88. /// custom HTTP trigger domain.
  89. @objc(functionsForCustomDomain:) open class func functions(customDomain: String) -> Functions {
  90. return functions(app: FirebaseApp.app(),
  91. region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  92. }
  93. /// Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  94. /// instance if one already exists.
  95. /// - Parameters:
  96. /// - app: The app for the Firebase project.
  97. /// - region: The region for the HTTP trigger, such as `us-central1`.
  98. /// - Returns: An instance of `Functions` with a custom app and region.
  99. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp,
  100. region: String) -> Functions {
  101. return functions(app: app, region: region, customDomain: nil)
  102. }
  103. /// Creates a Cloud Functions client with the given app and custom domain, or returns a
  104. /// pre-existing
  105. /// instance if one already exists.
  106. /// - Parameters:
  107. /// - app: The app for the Firebase project.
  108. /// - customDomain: A custom domain for the HTTP trigger, such as `https://mydomain.com`.
  109. /// - Returns: An instance of `Functions` with a custom app and HTTP trigger domain.
  110. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp,
  111. customDomain: String)
  112. -> Functions {
  113. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  114. }
  115. /// Creates a reference to the Callable HTTPS trigger with the given name.
  116. /// - Parameter name: The name of the Callable HTTPS trigger.
  117. /// - Returns: A reference to a Callable HTTPS trigger.
  118. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  119. HTTPSCallable(functions: self, url: functionURL(for: name)!)
  120. }
  121. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  122. /// options.
  123. /// - Parameters:
  124. /// - name: The name of the Callable HTTPS trigger.
  125. /// - options: The options with which to customize the Callable HTTPS trigger.
  126. /// - Returns: A reference to a Callable HTTPS trigger.
  127. @objc(HTTPSCallableWithName:options:) public func httpsCallable(_ name: String,
  128. options: HTTPSCallableOptions)
  129. -> HTTPSCallable {
  130. HTTPSCallable(functions: self, url: functionURL(for: name)!, options: options)
  131. }
  132. /// Creates a reference to the Callable HTTPS trigger with the given name.
  133. /// - Parameter url: The URL of the Callable HTTPS trigger.
  134. /// - Returns: A reference to a Callable HTTPS trigger.
  135. @objc(HTTPSCallableWithURL:) open func httpsCallable(_ url: URL) -> HTTPSCallable {
  136. return HTTPSCallable(functions: self, url: url)
  137. }
  138. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  139. /// options.
  140. /// - Parameters:
  141. /// - url: The URL of the Callable HTTPS trigger.
  142. /// - options: The options with which to customize the Callable HTTPS trigger.
  143. /// - Returns: A reference to a Callable HTTPS trigger.
  144. @objc(HTTPSCallableWithURL:options:) public func httpsCallable(_ url: URL,
  145. options: HTTPSCallableOptions)
  146. -> HTTPSCallable {
  147. return HTTPSCallable(functions: self, url: url, options: options)
  148. }
  149. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  150. /// `Encodable`
  151. /// request and the type of a `Decodable` response.
  152. /// - Parameters:
  153. /// - name: The name of the Callable HTTPS trigger
  154. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  155. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  156. /// - encoder: The encoder instance to use to perform encoding.
  157. /// - decoder: The decoder instance to use to perform decoding.
  158. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  159. /// Functions invocations.
  160. open func httpsCallable<Request: Encodable,
  161. Response: Decodable>(_ name: String,
  162. requestAs: Request.Type = Request.self,
  163. responseAs: Response.Type = Response.self,
  164. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  165. ),
  166. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  167. ))
  168. -> Callable<Request, Response> {
  169. return Callable(
  170. callable: httpsCallable(name),
  171. encoder: encoder,
  172. decoder: decoder
  173. )
  174. }
  175. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  176. /// `Encodable`
  177. /// request and the type of a `Decodable` response.
  178. /// - Parameters:
  179. /// - name: The name of the Callable HTTPS trigger
  180. /// - options: The options with which to customize the Callable HTTPS trigger.
  181. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  182. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  183. /// - encoder: The encoder instance to use to perform encoding.
  184. /// - decoder: The decoder instance to use to perform decoding.
  185. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  186. /// Functions invocations.
  187. open func httpsCallable<Request: Encodable,
  188. Response: Decodable>(_ name: String,
  189. options: HTTPSCallableOptions,
  190. requestAs: Request.Type = Request.self,
  191. responseAs: Response.Type = Response.self,
  192. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  193. ),
  194. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  195. ))
  196. -> Callable<Request, Response> {
  197. return Callable(
  198. callable: httpsCallable(name, options: options),
  199. encoder: encoder,
  200. decoder: decoder
  201. )
  202. }
  203. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  204. /// `Encodable`
  205. /// request and the type of a `Decodable` response.
  206. /// - Parameters:
  207. /// - url: The url of the Callable HTTPS trigger
  208. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  209. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  210. /// - encoder: The encoder instance to use to perform encoding.
  211. /// - decoder: The decoder instance to use to perform decoding.
  212. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  213. /// Functions invocations.
  214. open func httpsCallable<Request: Encodable,
  215. Response: Decodable>(_ url: URL,
  216. requestAs: Request.Type = Request.self,
  217. responseAs: Response.Type = Response.self,
  218. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  219. ),
  220. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  221. ))
  222. -> Callable<Request, Response> {
  223. return Callable(
  224. callable: httpsCallable(url),
  225. encoder: encoder,
  226. decoder: decoder
  227. )
  228. }
  229. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  230. /// `Encodable`
  231. /// request and the type of a `Decodable` response.
  232. /// - Parameters:
  233. /// - url: The url of the Callable HTTPS trigger
  234. /// - options: The options with which to customize the Callable HTTPS trigger.
  235. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  236. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  237. /// - encoder: The encoder instance to use to perform encoding.
  238. /// - decoder: The decoder instance to use to perform decoding.
  239. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  240. /// Functions invocations.
  241. open func httpsCallable<Request: Encodable,
  242. Response: Decodable>(_ url: URL,
  243. options: HTTPSCallableOptions,
  244. requestAs: Request.Type = Request.self,
  245. responseAs: Response.Type = Response.self,
  246. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  247. ),
  248. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  249. ))
  250. -> Callable<Request, Response> {
  251. return Callable(
  252. callable: httpsCallable(url, options: options),
  253. encoder: encoder,
  254. decoder: decoder
  255. )
  256. }
  257. /**
  258. * Changes this instance to point to a Cloud Functions emulator running locally.
  259. * See https://firebase.google.com/docs/functions/local-emulator
  260. * - Parameters:
  261. * - host: The host of the local emulator, such as "localhost".
  262. * - port: The port of the local emulator, for example 5005.
  263. */
  264. @objc open func useEmulator(withHost host: String, port: Int) {
  265. let prefix = host.hasPrefix("http") ? "" : "http://"
  266. let origin = String(format: "\(prefix)\(host):%li", port)
  267. emulatorOrigin = origin
  268. }
  269. // MARK: - Private Funcs (or Internal for tests)
  270. /// Solely used to have one precondition and one location where we fetch from the container. This
  271. /// previously was avoided due to default arguments but that doesn't work well with Obj-C
  272. /// compatibility.
  273. private class func functions(app: FirebaseApp?, region: String,
  274. customDomain: String?) -> Functions {
  275. guard let app else {
  276. fatalError("`FirebaseApp.configure()` needs to be called before using Functions.")
  277. }
  278. os_unfair_lock_lock(&instancesLock)
  279. // Unlock before the function returns.
  280. defer { os_unfair_lock_unlock(&instancesLock) }
  281. if let associatedInstances = instances[app.name] {
  282. for instance in associatedInstances {
  283. // Domains may be nil, so handle with care.
  284. var equalDomains = false
  285. if let instanceCustomDomain = instance.customDomain {
  286. equalDomains = instanceCustomDomain == customDomain
  287. } else {
  288. equalDomains = customDomain == nil
  289. }
  290. // Check if it's a match.
  291. if instance.region == region, equalDomains {
  292. return instance
  293. }
  294. }
  295. }
  296. let newInstance = Functions(app: app, region: region, customDomain: customDomain)
  297. let existingInstances = instances[app.name, default: []]
  298. instances[app.name] = existingInstances + [newInstance]
  299. return newInstance
  300. }
  301. @objc init(projectID: String,
  302. region: String,
  303. customDomain: String?,
  304. auth: AuthInterop?,
  305. messaging: MessagingInterop?,
  306. appCheck: AppCheckInterop?,
  307. fetcherService: GTMSessionFetcherService = GTMSessionFetcherService()) {
  308. self.projectID = projectID
  309. self.region = region
  310. self.customDomain = customDomain
  311. emulatorOrigin = nil
  312. contextProvider = FunctionsContextProvider(auth: auth,
  313. messaging: messaging,
  314. appCheck: appCheck)
  315. self.fetcherService = fetcherService
  316. }
  317. /// Using the component system for initialization.
  318. convenience init(app: FirebaseApp,
  319. region: String,
  320. customDomain: String?) {
  321. // TODO: These are not optionals, but they should be.
  322. let auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  323. let messaging = ComponentType<MessagingInterop>.instance(for: MessagingInterop.self,
  324. in: app.container)
  325. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  326. in: app.container)
  327. guard let projectID = app.options.projectID else {
  328. fatalError("Firebase Functions requires the projectID to be set in the App's Options.")
  329. }
  330. self.init(projectID: projectID,
  331. region: region,
  332. customDomain: customDomain,
  333. auth: auth,
  334. messaging: messaging,
  335. appCheck: appCheck)
  336. }
  337. func functionURL(for name: String) -> URL? {
  338. assert(!name.isEmpty, "Name cannot be empty")
  339. // Check if we're using the emulator
  340. if let emulatorOrigin {
  341. return URL(string: "\(emulatorOrigin)/\(projectID)/\(region)/\(name)")
  342. }
  343. // Check the custom domain.
  344. if let customDomain {
  345. return URL(string: "\(customDomain)/\(name)")
  346. }
  347. return URL(string: "https://\(region)-\(projectID).cloudfunctions.net/\(name)")
  348. }
  349. @available(iOS 13, macCatalyst 13, macOS 10.15, tvOS 13, watchOS 7, *)
  350. func callFunction(at url: URL,
  351. withObject data: Any?,
  352. options: HTTPSCallableOptions?,
  353. timeout: TimeInterval) async throws -> HTTPSCallableResult {
  354. let context = try await contextProvider.context(options: options)
  355. let fetcher = try makeFetcher(
  356. url: url,
  357. data: data,
  358. options: options,
  359. timeout: timeout,
  360. context: context
  361. )
  362. do {
  363. let rawData = try await fetcher.beginFetch()
  364. return try callableResult(fromResponseData: rawData)
  365. } catch {
  366. throw processedError(fromResponseError: error)
  367. }
  368. }
  369. func callFunction(at url: URL,
  370. withObject data: Any?,
  371. options: HTTPSCallableOptions?,
  372. timeout: TimeInterval,
  373. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  374. // Get context first.
  375. contextProvider.getContext(options: options) { context, error in
  376. // Note: context is always non-nil since some checks could succeed, we're only failing if
  377. // there's an error.
  378. if let error {
  379. completion(.failure(error))
  380. } else {
  381. self.callFunction(url: url,
  382. withObject: data,
  383. options: options,
  384. timeout: timeout,
  385. context: context,
  386. completion: completion)
  387. }
  388. }
  389. }
  390. private func callFunction(url: URL,
  391. withObject data: Any?,
  392. options: HTTPSCallableOptions?,
  393. timeout: TimeInterval,
  394. context: FunctionsContext,
  395. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  396. let fetcher: GTMSessionFetcher
  397. do {
  398. fetcher = try makeFetcher(
  399. url: url,
  400. data: data,
  401. options: options,
  402. timeout: timeout,
  403. context: context
  404. )
  405. } catch {
  406. DispatchQueue.main.async {
  407. completion(.failure(error))
  408. }
  409. return
  410. }
  411. fetcher.beginFetch { [self] data, error in
  412. let result: Result<HTTPSCallableResult, any Error>
  413. if let error {
  414. result = .failure(processedError(fromResponseError: error))
  415. } else if let data {
  416. do {
  417. result = try .success(callableResult(fromResponseData: data))
  418. } catch {
  419. result = .failure(error)
  420. }
  421. } else {
  422. result = .failure(FunctionsError(.internal))
  423. }
  424. DispatchQueue.main.async {
  425. completion(result)
  426. }
  427. }
  428. }
  429. private func makeFetcher(url: URL,
  430. data: Any?,
  431. options: HTTPSCallableOptions?,
  432. timeout: TimeInterval,
  433. context: FunctionsContext) throws -> GTMSessionFetcher {
  434. let request = URLRequest(
  435. url: url,
  436. cachePolicy: .useProtocolCachePolicy,
  437. timeoutInterval: timeout
  438. )
  439. let fetcher = fetcherService.fetcher(with: request)
  440. let data = data ?? NSNull()
  441. let encoded = try serializer.encode(data)
  442. let body = ["data": encoded]
  443. let payload = try JSONSerialization.data(withJSONObject: body)
  444. fetcher.bodyData = payload
  445. // Set the headers.
  446. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  447. if let authToken = context.authToken {
  448. let value = "Bearer \(authToken)"
  449. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  450. }
  451. if let fcmToken = context.fcmToken {
  452. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  453. }
  454. if options?.requireLimitedUseAppCheckTokens == true {
  455. if let appCheckToken = context.limitedUseAppCheckToken {
  456. fetcher.setRequestValue(
  457. appCheckToken,
  458. forHTTPHeaderField: Constants.appCheckTokenHeader
  459. )
  460. }
  461. } else if let appCheckToken = context.appCheckToken {
  462. fetcher.setRequestValue(
  463. appCheckToken,
  464. forHTTPHeaderField: Constants.appCheckTokenHeader
  465. )
  466. }
  467. // Override normal security rules if this is a local test.
  468. if emulatorOrigin != nil {
  469. fetcher.allowLocalhostRequest = true
  470. fetcher.allowedInsecureSchemes = ["http"]
  471. }
  472. return fetcher
  473. }
  474. private func processedError(fromResponseError error: any Error) -> any Error {
  475. let error = error as NSError
  476. let localError: (any Error)? = if error.domain == kGTMSessionFetcherStatusDomain {
  477. FunctionsError(
  478. httpStatusCode: error.code,
  479. body: error.userInfo["data"] as? Data,
  480. serializer: serializer
  481. )
  482. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  483. FunctionsError(.deadlineExceeded)
  484. } else { nil }
  485. return localError ?? error
  486. }
  487. private func callableResult(fromResponseData data: Data) throws -> HTTPSCallableResult {
  488. let processedData = try processedData(fromResponseData: data)
  489. let json = try responseDataJSON(from: processedData)
  490. // TODO: Refactor `decode(_:)` so it either returns a non-optional object or throws
  491. let payload = try serializer.decode(json)
  492. // TODO: Remove `as Any` once `decode(_:)` is refactored
  493. return HTTPSCallableResult(data: payload as Any)
  494. }
  495. private func processedData(fromResponseData data: Data) throws -> Data {
  496. // `data` might specify a custom error. If so, throw the error.
  497. if let bodyError = FunctionsError(httpStatusCode: 200, body: data, serializer: serializer) {
  498. throw bodyError
  499. }
  500. return data
  501. }
  502. private func responseDataJSON(from data: Data) throws -> Any {
  503. let responseJSONObject = try JSONSerialization.jsonObject(with: data)
  504. guard let responseJSON = responseJSONObject as? NSDictionary else {
  505. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  506. throw FunctionsError(.internal, userInfo: userInfo)
  507. }
  508. // `result` is checked for backwards compatibility:
  509. guard let dataJSON = responseJSON["data"] ?? responseJSON["result"] else {
  510. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  511. throw FunctionsError(.internal, userInfo: userInfo)
  512. }
  513. return dataJSON
  514. }
  515. }