Functions.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. func callFunction(at url: URL,
  350. withObject data: Any?,
  351. options: HTTPSCallableOptions?,
  352. timeout: TimeInterval,
  353. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  354. // Get context first.
  355. contextProvider.getContext(options: options) { context, error in
  356. // Note: context is always non-nil since some checks could succeed, we're only failing if
  357. // there's an error.
  358. if let error {
  359. completion(.failure(error))
  360. } else {
  361. self.callFunction(url: url,
  362. withObject: data,
  363. options: options,
  364. timeout: timeout,
  365. context: context,
  366. completion: completion)
  367. }
  368. }
  369. }
  370. private func callFunction(url: URL,
  371. withObject data: Any?,
  372. options: HTTPSCallableOptions?,
  373. timeout: TimeInterval,
  374. context: FunctionsContext,
  375. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  376. let request = URLRequest(url: url,
  377. cachePolicy: .useProtocolCachePolicy,
  378. timeoutInterval: timeout)
  379. let fetcher = fetcherService.fetcher(with: request)
  380. do {
  381. let data = data ?? NSNull()
  382. let encoded = try serializer.encode(data)
  383. let body = ["data": encoded]
  384. let payload = try JSONSerialization.data(withJSONObject: body)
  385. fetcher.bodyData = payload
  386. } catch {
  387. DispatchQueue.main.async {
  388. completion(.failure(error))
  389. }
  390. return
  391. }
  392. // Set the headers.
  393. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  394. if let authToken = context.authToken {
  395. let value = "Bearer \(authToken)"
  396. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  397. }
  398. if let fcmToken = context.fcmToken {
  399. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  400. }
  401. if options?.requireLimitedUseAppCheckTokens == true {
  402. if let appCheckToken = context.limitedUseAppCheckToken {
  403. fetcher.setRequestValue(
  404. appCheckToken,
  405. forHTTPHeaderField: Constants.appCheckTokenHeader
  406. )
  407. }
  408. } else if let appCheckToken = context.appCheckToken {
  409. fetcher.setRequestValue(
  410. appCheckToken,
  411. forHTTPHeaderField: Constants.appCheckTokenHeader
  412. )
  413. }
  414. // Override normal security rules if this is a local test.
  415. if emulatorOrigin != nil {
  416. fetcher.allowLocalhostRequest = true
  417. fetcher.allowedInsecureSchemes = ["http"]
  418. }
  419. fetcher.beginFetch { [self] data, error in
  420. let result: Result<HTTPSCallableResult, any Error>
  421. do {
  422. let data = try responseData(data: data, error: error)
  423. let json = try responseDataJSON(from: data)
  424. // TODO: Refactor `decode(_:)` so it either returns a non-optional object or throws
  425. let payload = try serializer.decode(json)
  426. // TODO: Remove `as Any` once `decode(_:)` is refactored
  427. result = .success(HTTPSCallableResult(data: payload as Any))
  428. } catch {
  429. result = .failure(error)
  430. }
  431. DispatchQueue.main.async {
  432. completion(result)
  433. }
  434. }
  435. }
  436. private func responseData(data: Data?, error: (any Error)?) throws -> Data {
  437. // Case 1: `error` is not `nil` -> always throws
  438. if let error = error as NSError? {
  439. let localError: (any Error)?
  440. if error.domain == kGTMSessionFetcherStatusDomain {
  441. localError = FunctionsError(
  442. httpStatusCode: error.code,
  443. body: data,
  444. serializer: serializer
  445. )
  446. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  447. localError = FunctionsError(.deadlineExceeded)
  448. } else {
  449. localError = nil
  450. }
  451. throw localError ?? error
  452. }
  453. // Case 2: `data` is `nil` -> always throws
  454. guard let data else {
  455. throw FunctionsError(.internal)
  456. }
  457. // Case 3: `data` is not `nil` but might specify a custom error -> throws conditionally
  458. if let bodyError = FunctionsError(httpStatusCode: 200, body: data, serializer: serializer) {
  459. throw bodyError
  460. }
  461. // Case 4: `error` is `nil`; `data` is not `nil`; `data` doesn’t specify an error -> OK
  462. return data
  463. }
  464. private func responseDataJSON(from data: Data) throws -> Any {
  465. let responseJSONObject = try JSONSerialization.jsonObject(with: data)
  466. guard let responseJSON = responseJSONObject as? NSDictionary else {
  467. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  468. throw FunctionsError(.internal, userInfo: userInfo)
  469. }
  470. // `result` is checked for backwards compatibility:
  471. guard let dataJSON = responseJSON["data"] ?? responseJSON["result"] else {
  472. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  473. throw FunctionsError(.internal, userInfo: userInfo)
  474. }
  475. return dataJSON
  476. }
  477. }