Functions.swift 29 KB

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