Functions.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. @preconcurrency import GTMSessionFetcher
  22. #else
  23. @preconcurrency import GTMSessionFetcherCore
  24. #endif
  25. internal import FirebaseCoreExtension
  26. private import FirebaseCoreInternal
  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, @unchecked Sendable {
  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 let instances = UnfairLock<[String: [Functions]]>([:])
  50. /// The custom domain to use for all functions references (optional).
  51. let customDomain: String?
  52. /// The region to use for all function references.
  53. let region: String
  54. private let _emulatorOrigin: UnfairLock<String?>
  55. // MARK: - Public APIs
  56. /// The current emulator origin, or `nil` if it is not set.
  57. open var emulatorOrigin: String? {
  58. _emulatorOrigin.value()
  59. }
  60. /// Creates a Cloud Functions client using the default or returns a pre-existing instance if it
  61. /// already exists.
  62. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp`.
  63. @objc(functions) open class func functions() -> Functions {
  64. return functions(
  65. app: FirebaseApp.app(),
  66. region: FunctionsConstants.defaultRegion,
  67. customDomain: nil
  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. @objc(functionsForApp:) open class func functions(app: FirebaseApp) -> Functions {
  75. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: nil)
  76. }
  77. /// Creates a Cloud Functions client with the default app and given region.
  78. /// - Parameter region: The region for the HTTP trigger, such as `us-central1`.
  79. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  80. /// custom region.
  81. @objc(functionsForRegion:) open class func functions(region: String) -> Functions {
  82. return functions(app: FirebaseApp.app(), region: region, customDomain: nil)
  83. }
  84. /// Creates a Cloud Functions client with the given custom domain or returns a pre-existing
  85. /// instance if one already exists.
  86. /// - Parameter customDomain: A custom domain for the HTTP trigger, such as
  87. /// "https://mydomain.com".
  88. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  89. /// custom HTTP trigger domain.
  90. @objc(functionsForCustomDomain:) open class func functions(customDomain: String) -> Functions {
  91. return functions(app: FirebaseApp.app(),
  92. region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  93. }
  94. /// Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  95. /// instance if one already exists.
  96. /// - Parameters:
  97. /// - app: The app for the Firebase project.
  98. /// - region: The region for the HTTP trigger, such as `us-central1`.
  99. /// - Returns: An instance of `Functions` with a custom app and region.
  100. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp,
  101. region: String) -> Functions {
  102. return functions(app: app, region: region, customDomain: nil)
  103. }
  104. /// Creates a Cloud Functions client with the given app and custom domain, or returns a
  105. /// pre-existing
  106. /// instance if one already exists.
  107. /// - Parameters:
  108. /// - app: The app for the Firebase project.
  109. /// - customDomain: A custom domain for the HTTP trigger, such as `https://mydomain.com`.
  110. /// - Returns: An instance of `Functions` with a custom app and HTTP trigger domain.
  111. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp,
  112. customDomain: String)
  113. -> Functions {
  114. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  115. }
  116. /// Creates a reference to the Callable HTTPS trigger with the given name.
  117. /// - Parameter name: The name of the Callable HTTPS trigger.
  118. /// - Returns: A reference to a Callable HTTPS trigger.
  119. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  120. HTTPSCallable(functions: self, url: functionURL(for: name)!)
  121. }
  122. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  123. /// options.
  124. /// - Parameters:
  125. /// - name: The name of the Callable HTTPS trigger.
  126. /// - options: The options with which to customize the Callable HTTPS trigger.
  127. /// - Returns: A reference to a Callable HTTPS trigger.
  128. @objc(HTTPSCallableWithName:options:) public func httpsCallable(_ name: String,
  129. options: HTTPSCallableOptions)
  130. -> HTTPSCallable {
  131. HTTPSCallable(functions: self, url: functionURL(for: name)!, options: options)
  132. }
  133. /// Creates a reference to the Callable HTTPS trigger with the given name.
  134. /// - Parameter url: The URL of the Callable HTTPS trigger.
  135. /// - Returns: A reference to a Callable HTTPS trigger.
  136. @objc(HTTPSCallableWithURL:) open func httpsCallable(_ url: URL) -> HTTPSCallable {
  137. return HTTPSCallable(functions: self, url: url)
  138. }
  139. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  140. /// options.
  141. /// - Parameters:
  142. /// - url: The URL of the Callable HTTPS trigger.
  143. /// - options: The options with which to customize the Callable HTTPS trigger.
  144. /// - Returns: A reference to a Callable HTTPS trigger.
  145. @objc(HTTPSCallableWithURL:options:) public func httpsCallable(_ url: URL,
  146. options: HTTPSCallableOptions)
  147. -> HTTPSCallable {
  148. return HTTPSCallable(functions: self, url: url, options: options)
  149. }
  150. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  151. /// `Encodable`
  152. /// request and the type of a `Decodable` response.
  153. /// - Parameters:
  154. /// - name: The name of the Callable HTTPS trigger
  155. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  156. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  157. /// - encoder: The encoder instance to use to perform encoding.
  158. /// - decoder: The decoder instance to use to perform decoding.
  159. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  160. /// Functions invocations.
  161. open func httpsCallable<Request: Encodable,
  162. Response: Decodable>(_ name: String,
  163. requestAs: Request.Type = Request.self,
  164. responseAs: Response.Type = Response.self,
  165. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  166. ),
  167. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  168. ))
  169. -> Callable<Request, Response> {
  170. return Callable(
  171. callable: httpsCallable(name),
  172. encoder: encoder,
  173. decoder: decoder
  174. )
  175. }
  176. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  177. /// `Encodable`
  178. /// request and the type of a `Decodable` response.
  179. /// - Parameters:
  180. /// - name: The name of the Callable HTTPS trigger
  181. /// - options: The options with which to customize the Callable HTTPS trigger.
  182. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  183. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  184. /// - encoder: The encoder instance to use to perform encoding.
  185. /// - decoder: The decoder instance to use to perform decoding.
  186. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  187. /// Functions invocations.
  188. open func httpsCallable<Request: Encodable,
  189. Response: Decodable>(_ name: String,
  190. options: HTTPSCallableOptions,
  191. requestAs: Request.Type = Request.self,
  192. responseAs: Response.Type = Response.self,
  193. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  194. ),
  195. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  196. ))
  197. -> Callable<Request, Response> {
  198. return Callable(
  199. callable: httpsCallable(name, options: options),
  200. encoder: encoder,
  201. decoder: decoder
  202. )
  203. }
  204. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  205. /// `Encodable`
  206. /// request and the type of a `Decodable` response.
  207. /// - Parameters:
  208. /// - url: The url of the Callable HTTPS trigger
  209. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  210. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  211. /// - encoder: The encoder instance to use to perform encoding.
  212. /// - decoder: The decoder instance to use to perform decoding.
  213. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  214. /// Functions invocations.
  215. open func httpsCallable<Request: Encodable,
  216. Response: Decodable>(_ url: URL,
  217. requestAs: Request.Type = Request.self,
  218. responseAs: Response.Type = Response.self,
  219. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  220. ),
  221. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  222. ))
  223. -> Callable<Request, Response> {
  224. return Callable(
  225. callable: httpsCallable(url),
  226. encoder: encoder,
  227. decoder: decoder
  228. )
  229. }
  230. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  231. /// `Encodable`
  232. /// request and the type of a `Decodable` response.
  233. /// - Parameters:
  234. /// - url: The url of the Callable HTTPS trigger
  235. /// - options: The options with which to customize the Callable HTTPS trigger.
  236. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  237. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  238. /// - encoder: The encoder instance to use to perform encoding.
  239. /// - decoder: The decoder instance to use to perform decoding.
  240. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  241. /// Functions invocations.
  242. open func httpsCallable<Request: Encodable,
  243. Response: Decodable>(_ url: URL,
  244. options: HTTPSCallableOptions,
  245. requestAs: Request.Type = Request.self,
  246. responseAs: Response.Type = Response.self,
  247. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  248. ),
  249. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  250. ))
  251. -> Callable<Request, Response> {
  252. return Callable(
  253. callable: httpsCallable(url, options: options),
  254. encoder: encoder,
  255. decoder: decoder
  256. )
  257. }
  258. /**
  259. * Changes this instance to point to a Cloud Functions emulator running locally.
  260. * See https://firebase.google.com/docs/functions/local-emulator
  261. * - Parameters:
  262. * - host: The host of the local emulator, such as "localhost".
  263. * - port: The port of the local emulator, for example 5005.
  264. */
  265. @objc open func useEmulator(withHost host: String, port: Int) {
  266. let prefix = host.hasPrefix("http") ? "" : "http://"
  267. let origin = String(format: "\(prefix)\(host):%li", port)
  268. _emulatorOrigin.withLock { emulatorOrigin in
  269. emulatorOrigin = origin
  270. }
  271. }
  272. // MARK: - Private Funcs (or Internal for tests)
  273. /// Solely used to have one precondition and one location where we fetch from the container. This
  274. /// previously was avoided due to default arguments but that doesn't work well with Obj-C
  275. /// compatibility.
  276. private class func functions(app: FirebaseApp?, region: String,
  277. customDomain: String?) -> Functions {
  278. guard let app else {
  279. fatalError("`FirebaseApp.configure()` needs to be called before using Functions.")
  280. }
  281. return instances.withLock { instances in
  282. if let associatedInstances = instances[app.name] {
  283. for instance in associatedInstances {
  284. // Domains may be nil, so handle with care.
  285. var equalDomains = false
  286. if let instanceCustomDomain = instance.customDomain {
  287. equalDomains = instanceCustomDomain == customDomain
  288. } else {
  289. equalDomains = customDomain == nil
  290. }
  291. // Check if it's a match.
  292. if instance.region == region, equalDomains {
  293. return instance
  294. }
  295. }
  296. }
  297. let newInstance = Functions(app: app, region: region, customDomain: customDomain)
  298. let existingInstances = instances[app.name, default: []]
  299. instances[app.name] = existingInstances + [newInstance]
  300. return newInstance
  301. }
  302. }
  303. @objc init(projectID: String,
  304. region: String,
  305. customDomain: String?,
  306. auth: AuthInterop?,
  307. messaging: MessagingInterop?,
  308. appCheck: AppCheckInterop?,
  309. fetcherService: GTMSessionFetcherService = GTMSessionFetcherService()) {
  310. self.projectID = projectID
  311. self.region = region
  312. self.customDomain = customDomain
  313. _emulatorOrigin = UnfairLock(nil)
  314. contextProvider = FunctionsContextProvider(auth: auth,
  315. messaging: messaging,
  316. appCheck: appCheck)
  317. self.fetcherService = fetcherService
  318. }
  319. /// Using the component system for initialization.
  320. convenience init(app: FirebaseApp,
  321. region: String,
  322. customDomain: String?) {
  323. // TODO: These are not optionals, but they should be.
  324. let auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  325. let messaging = ComponentType<MessagingInterop>.instance(for: MessagingInterop.self,
  326. in: app.container)
  327. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  328. in: app.container)
  329. guard let projectID = app.options.projectID else {
  330. fatalError("Firebase Functions requires the projectID to be set in the App's Options.")
  331. }
  332. self.init(projectID: projectID,
  333. region: region,
  334. customDomain: customDomain,
  335. auth: auth,
  336. messaging: messaging,
  337. appCheck: appCheck)
  338. }
  339. func functionURL(for name: String) -> URL? {
  340. assert(!name.isEmpty, "Name cannot be empty")
  341. // Check if we're using the emulator
  342. if let emulatorOrigin {
  343. return URL(string: "\(emulatorOrigin)/\(projectID)/\(region)/\(name)")
  344. }
  345. // Check the custom domain.
  346. if let customDomain {
  347. return URL(string: "\(customDomain)/\(name)")
  348. }
  349. return URL(string: "https://\(region)-\(projectID).cloudfunctions.net/\(name)")
  350. }
  351. func callFunction(at url: URL,
  352. withObject data: Any?,
  353. options: HTTPSCallableOptions?,
  354. timeout: TimeInterval) async throws -> sending HTTPSCallableResult {
  355. let context = try await contextProvider.context(options: options)
  356. let fetcher = try makeFetcher(
  357. url: url,
  358. data: data,
  359. options: options,
  360. timeout: timeout,
  361. context: context
  362. )
  363. do {
  364. let rawData = try await fetcher.beginFetch()
  365. return try callableResult(fromResponseData: rawData, endpointURL: url)
  366. } catch {
  367. throw processedError(fromResponseError: error, endpointURL: url)
  368. }
  369. }
  370. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  371. func stream(at url: URL,
  372. data: SendableWrapper?,
  373. options: HTTPSCallableOptions?,
  374. timeout: TimeInterval)
  375. -> AsyncThrowingStream<JSONStreamResponse, Error> {
  376. AsyncThrowingStream { continuation in
  377. Task {
  378. let urlRequest: URLRequest
  379. do {
  380. let context = try await contextProvider.context(options: options)
  381. urlRequest = try makeRequestForStreamableContent(
  382. url: url,
  383. data: data?.value,
  384. options: options,
  385. timeout: timeout,
  386. context: context
  387. )
  388. } catch {
  389. continuation.finish(throwing: FunctionsError(
  390. .invalidArgument,
  391. userInfo: [NSUnderlyingErrorKey: error]
  392. ))
  393. return
  394. }
  395. let stream: URLSession.AsyncBytes
  396. let rawResponse: URLResponse
  397. do {
  398. (stream, rawResponse) = try await URLSession.shared.bytes(for: urlRequest)
  399. } catch {
  400. continuation.finish(throwing: FunctionsError(
  401. .unavailable,
  402. userInfo: [NSUnderlyingErrorKey: error]
  403. ))
  404. return
  405. }
  406. // Verify the status code is an HTTP response.
  407. guard let response = rawResponse as? HTTPURLResponse else {
  408. continuation.finish(
  409. throwing: FunctionsError(
  410. .unavailable,
  411. userInfo: [NSLocalizedDescriptionKey: "Response was not an HTTP response."]
  412. )
  413. )
  414. return
  415. }
  416. // Verify the status code is a 200.
  417. guard response.statusCode == 200 else {
  418. continuation.finish(
  419. throwing: FunctionsError(
  420. httpStatusCode: response.statusCode,
  421. region: region,
  422. url: url,
  423. body: nil,
  424. serializer: serializer
  425. )
  426. )
  427. return
  428. }
  429. do {
  430. for try await line in stream.lines {
  431. guard line.hasPrefix("data:") else {
  432. continuation.finish(
  433. throwing: FunctionsError(
  434. .dataLoss,
  435. userInfo: [NSLocalizedDescriptionKey: "Unexpected format for streamed response."]
  436. )
  437. )
  438. return
  439. }
  440. do {
  441. // We can assume 5 characters since it's utf-8 encoded, removing `data:`.
  442. let jsonText = String(line.dropFirst(5))
  443. let data = try jsonData(jsonText: jsonText)
  444. // Handle the content and parse it.
  445. let content = try callableStreamResult(fromResponseData: data, endpointURL: url)
  446. continuation.yield(content)
  447. } catch {
  448. continuation.finish(throwing: error)
  449. return
  450. }
  451. }
  452. } catch {
  453. continuation.finish(
  454. throwing: FunctionsError(
  455. .dataLoss,
  456. userInfo: [
  457. NSLocalizedDescriptionKey: "Unexpected format for streamed response.",
  458. NSUnderlyingErrorKey: error,
  459. ]
  460. )
  461. )
  462. return
  463. }
  464. continuation.finish()
  465. }
  466. }
  467. }
  468. @available(macOS 12.0, watchOS 8.0, *)
  469. private func callableStreamResult(fromResponseData data: Data,
  470. endpointURL url: URL) throws -> sending JSONStreamResponse {
  471. let data = try processedData(fromResponseData: data, endpointURL: url)
  472. let responseJSONObject: Any
  473. do {
  474. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  475. } catch {
  476. throw FunctionsError(.dataLoss, userInfo: [NSUnderlyingErrorKey: error])
  477. }
  478. guard let responseJSON = responseJSONObject as? [String: Any] else {
  479. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  480. throw FunctionsError(.dataLoss, userInfo: userInfo)
  481. }
  482. if let _ = responseJSON["result"] {
  483. return .result(responseJSON)
  484. } else if let _ = responseJSON["message"] {
  485. return .message(responseJSON)
  486. } else {
  487. throw FunctionsError(
  488. .dataLoss,
  489. userInfo: [NSLocalizedDescriptionKey: "Response is missing result or message field."]
  490. )
  491. }
  492. }
  493. private func jsonData(jsonText: String) throws -> Data {
  494. guard let data = jsonText.data(using: .utf8) else {
  495. throw FunctionsError(.dataLoss, userInfo: [
  496. NSUnderlyingErrorKey: DecodingError.dataCorrupted(DecodingError.Context(
  497. codingPath: [],
  498. debugDescription: "Could not parse response as UTF8."
  499. )),
  500. ])
  501. }
  502. return data
  503. }
  504. private func makeRequestForStreamableContent(url: URL,
  505. data: Any?,
  506. options: HTTPSCallableOptions?,
  507. timeout: TimeInterval,
  508. context: FunctionsContext) throws
  509. -> URLRequest {
  510. var urlRequest = URLRequest(
  511. url: url,
  512. cachePolicy: .useProtocolCachePolicy,
  513. timeoutInterval: timeout
  514. )
  515. let data = data ?? NSNull()
  516. let encoded = try serializer.encode(data)
  517. let body = ["data": encoded]
  518. let payload = try JSONSerialization.data(withJSONObject: body, options: [.fragmentsAllowed])
  519. urlRequest.httpBody = payload
  520. // Set the headers for starting a streaming session.
  521. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  522. urlRequest.setValue("text/event-stream", forHTTPHeaderField: "Accept")
  523. urlRequest.httpMethod = "POST"
  524. if let authToken = context.authToken {
  525. let value = "Bearer \(authToken)"
  526. urlRequest.setValue(value, forHTTPHeaderField: "Authorization")
  527. }
  528. if let fcmToken = context.fcmToken {
  529. urlRequest.setValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  530. }
  531. if options?.requireLimitedUseAppCheckTokens == true {
  532. if let appCheckToken = context.limitedUseAppCheckToken {
  533. urlRequest.setValue(
  534. appCheckToken,
  535. forHTTPHeaderField: Constants.appCheckTokenHeader
  536. )
  537. }
  538. } else if let appCheckToken = context.appCheckToken {
  539. urlRequest.setValue(
  540. appCheckToken,
  541. forHTTPHeaderField: Constants.appCheckTokenHeader
  542. )
  543. }
  544. return urlRequest
  545. }
  546. private func makeFetcher(url: URL,
  547. data: Any?,
  548. options: HTTPSCallableOptions?,
  549. timeout: TimeInterval,
  550. context: FunctionsContext) throws -> GTMSessionFetcher {
  551. let request = URLRequest(
  552. url: url,
  553. cachePolicy: .useProtocolCachePolicy,
  554. timeoutInterval: timeout
  555. )
  556. let fetcher = fetcherService.fetcher(with: request)
  557. let data = data ?? NSNull()
  558. let encoded = try serializer.encode(data)
  559. let body = ["data": encoded]
  560. let payload = try JSONSerialization.data(withJSONObject: body)
  561. fetcher.bodyData = payload
  562. // Set the headers.
  563. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  564. if let authToken = context.authToken {
  565. let value = "Bearer \(authToken)"
  566. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  567. }
  568. if let fcmToken = context.fcmToken {
  569. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  570. }
  571. if options?.requireLimitedUseAppCheckTokens == true {
  572. if let appCheckToken = context.limitedUseAppCheckToken {
  573. fetcher.setRequestValue(
  574. appCheckToken,
  575. forHTTPHeaderField: Constants.appCheckTokenHeader
  576. )
  577. }
  578. } else if let appCheckToken = context.appCheckToken {
  579. fetcher.setRequestValue(
  580. appCheckToken,
  581. forHTTPHeaderField: Constants.appCheckTokenHeader
  582. )
  583. }
  584. // Override normal security rules if this is a local test.
  585. if emulatorOrigin != nil {
  586. fetcher.allowLocalhostRequest = true
  587. fetcher.allowedInsecureSchemes = ["http"]
  588. }
  589. return fetcher
  590. }
  591. private func processedError(fromResponseError error: any Error,
  592. endpointURL url: URL) -> any Error {
  593. let error = error as NSError
  594. let localError: (any Error)? = if error.domain == kGTMSessionFetcherStatusDomain {
  595. FunctionsError(
  596. httpStatusCode: error.code,
  597. region: region,
  598. url: url,
  599. body: error.userInfo["data"] as? Data,
  600. serializer: serializer
  601. )
  602. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  603. FunctionsError(.deadlineExceeded)
  604. } else { nil }
  605. return localError ?? error
  606. }
  607. private func callableResult(fromResponseData data: Data,
  608. endpointURL url: URL) throws -> sending HTTPSCallableResult {
  609. let processedData = try processedData(fromResponseData: data, endpointURL: url)
  610. let json = try responseDataJSON(from: processedData)
  611. let payload = try serializer.decode(json)
  612. return HTTPSCallableResult(data: payload)
  613. }
  614. private func processedData(fromResponseData data: Data, endpointURL url: URL) throws -> Data {
  615. // `data` might specify a custom error. If so, throw the error.
  616. if let bodyError = FunctionsError(
  617. httpStatusCode: 200,
  618. region: region,
  619. url: url,
  620. body: data,
  621. serializer: serializer
  622. ) {
  623. throw bodyError
  624. }
  625. return data
  626. }
  627. private func responseDataJSON(from data: Data) throws -> sending Any {
  628. let responseJSONObject = try JSONSerialization.jsonObject(with: data)
  629. guard let responseJSON = responseJSONObject as? NSDictionary else {
  630. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  631. throw FunctionsError(.internal, userInfo: userInfo)
  632. }
  633. // `result` is checked for backwards compatibility:
  634. guard let dataJSON = responseJSON["data"] ?? responseJSON["result"] else {
  635. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  636. throw FunctionsError(.internal, userInfo: userInfo)
  637. }
  638. return dataJSON
  639. }
  640. }