Functions.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. public import FirebaseCore
  17. import FirebaseMessagingInterop
  18. public import FirebaseSharedSwift
  19. import Foundation
  20. #if COCOAPODS
  21. @preconcurrency import GTMSessionFetcher
  22. #else
  23. @preconcurrency import GTMSessionFetcherCore
  24. #endif
  25. import FirebaseCoreExtension
  26. 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. @available(iOS 13, macCatalyst 13, macOS 10.15, tvOS 13, watchOS 7, *)
  352. func callFunction(at url: URL,
  353. withObject data: Any?,
  354. options: HTTPSCallableOptions?,
  355. timeout: TimeInterval) async throws -> sending HTTPSCallableResult {
  356. let context = try await contextProvider.context(options: options)
  357. let fetcher = try makeFetcher(
  358. url: url,
  359. data: data,
  360. options: options,
  361. timeout: timeout,
  362. context: context
  363. )
  364. do {
  365. let rawData = try await fetcher.beginFetch()
  366. return try callableResult(fromResponseData: rawData, endpointURL: url)
  367. } catch {
  368. throw processedError(fromResponseError: error, endpointURL: url)
  369. }
  370. }
  371. private func callFunction(url: URL,
  372. withObject data: Any?,
  373. options: HTTPSCallableOptions?,
  374. timeout: TimeInterval,
  375. context: FunctionsContext,
  376. completion: @escaping @MainActor (Result<HTTPSCallableResult, Error>)
  377. -> Void) {
  378. let fetcher: GTMSessionFetcher
  379. do {
  380. fetcher = try makeFetcher(
  381. url: url,
  382. data: data,
  383. options: options,
  384. timeout: timeout,
  385. context: context
  386. )
  387. } catch {
  388. DispatchQueue.main.async {
  389. completion(.failure(error))
  390. }
  391. return
  392. }
  393. fetcher.beginFetch { [self] data, error in
  394. let result: Result<HTTPSCallableResult, any Error>
  395. if let error {
  396. result = .failure(processedError(fromResponseError: error, endpointURL: url))
  397. } else if let data {
  398. do {
  399. result = try .success(callableResult(fromResponseData: data, endpointURL: url))
  400. } catch {
  401. result = .failure(error)
  402. }
  403. } else {
  404. result = .failure(FunctionsError(.internal))
  405. }
  406. DispatchQueue.main.async {
  407. completion(result)
  408. }
  409. }
  410. }
  411. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  412. func stream(at url: URL,
  413. data: SendableWrapper?,
  414. options: HTTPSCallableOptions?,
  415. timeout: TimeInterval)
  416. -> AsyncThrowingStream<JSONStreamResponse, Error> {
  417. AsyncThrowingStream { continuation in
  418. Task {
  419. let urlRequest: URLRequest
  420. do {
  421. let context = try await contextProvider.context(options: options)
  422. urlRequest = try makeRequestForStreamableContent(
  423. url: url,
  424. data: data?.value,
  425. options: options,
  426. timeout: timeout,
  427. context: context
  428. )
  429. } catch {
  430. continuation.finish(throwing: FunctionsError(
  431. .invalidArgument,
  432. userInfo: [NSUnderlyingErrorKey: error]
  433. ))
  434. return
  435. }
  436. let stream: URLSession.AsyncBytes
  437. let rawResponse: URLResponse
  438. do {
  439. (stream, rawResponse) = try await URLSession.shared.bytes(for: urlRequest)
  440. } catch {
  441. continuation.finish(throwing: FunctionsError(
  442. .unavailable,
  443. userInfo: [NSUnderlyingErrorKey: error]
  444. ))
  445. return
  446. }
  447. // Verify the status code is an HTTP response.
  448. guard let response = rawResponse as? HTTPURLResponse else {
  449. continuation.finish(
  450. throwing: FunctionsError(
  451. .unavailable,
  452. userInfo: [NSLocalizedDescriptionKey: "Response was not an HTTP response."]
  453. )
  454. )
  455. return
  456. }
  457. // Verify the status code is a 200.
  458. guard response.statusCode == 200 else {
  459. continuation.finish(
  460. throwing: FunctionsError(
  461. httpStatusCode: response.statusCode,
  462. region: region,
  463. url: url,
  464. body: nil,
  465. serializer: serializer
  466. )
  467. )
  468. return
  469. }
  470. do {
  471. for try await line in stream.lines {
  472. guard line.hasPrefix("data:") else {
  473. continuation.finish(
  474. throwing: FunctionsError(
  475. .dataLoss,
  476. userInfo: [NSLocalizedDescriptionKey: "Unexpected format for streamed response."]
  477. )
  478. )
  479. return
  480. }
  481. do {
  482. // We can assume 5 characters since it's utf-8 encoded, removing `data:`.
  483. let jsonText = String(line.dropFirst(5))
  484. let data = try jsonData(jsonText: jsonText)
  485. // Handle the content and parse it.
  486. let content = try callableStreamResult(fromResponseData: data, endpointURL: url)
  487. continuation.yield(content)
  488. } catch {
  489. continuation.finish(throwing: error)
  490. return
  491. }
  492. }
  493. } catch {
  494. continuation.finish(
  495. throwing: FunctionsError(
  496. .dataLoss,
  497. userInfo: [
  498. NSLocalizedDescriptionKey: "Unexpected format for streamed response.",
  499. NSUnderlyingErrorKey: error,
  500. ]
  501. )
  502. )
  503. return
  504. }
  505. continuation.finish()
  506. }
  507. }
  508. }
  509. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  510. private func callableStreamResult(fromResponseData data: Data,
  511. endpointURL url: URL) throws -> sending JSONStreamResponse {
  512. let data = try processedData(fromResponseData: data, endpointURL: url)
  513. let responseJSONObject: Any
  514. do {
  515. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  516. } catch {
  517. throw FunctionsError(.dataLoss, userInfo: [NSUnderlyingErrorKey: error])
  518. }
  519. guard let responseJSON = responseJSONObject as? [String: Any] else {
  520. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  521. throw FunctionsError(.dataLoss, userInfo: userInfo)
  522. }
  523. if let _ = responseJSON["result"] {
  524. return .result(responseJSON)
  525. } else if let _ = responseJSON["message"] {
  526. return .message(responseJSON)
  527. } else {
  528. throw FunctionsError(
  529. .dataLoss,
  530. userInfo: [NSLocalizedDescriptionKey: "Response is missing result or message field."]
  531. )
  532. }
  533. }
  534. private func jsonData(jsonText: String) throws -> Data {
  535. guard let data = jsonText.data(using: .utf8) else {
  536. throw FunctionsError(.dataLoss, userInfo: [
  537. NSUnderlyingErrorKey: DecodingError.dataCorrupted(DecodingError.Context(
  538. codingPath: [],
  539. debugDescription: "Could not parse response as UTF8."
  540. )),
  541. ])
  542. }
  543. return data
  544. }
  545. private func makeRequestForStreamableContent(url: URL,
  546. data: Any?,
  547. options: HTTPSCallableOptions?,
  548. timeout: TimeInterval,
  549. context: FunctionsContext) throws
  550. -> URLRequest {
  551. var urlRequest = URLRequest(
  552. url: url,
  553. cachePolicy: .useProtocolCachePolicy,
  554. timeoutInterval: timeout
  555. )
  556. let data = data ?? NSNull()
  557. let encoded = try serializer.encode(data)
  558. let body = ["data": encoded]
  559. let payload = try JSONSerialization.data(withJSONObject: body, options: [.fragmentsAllowed])
  560. urlRequest.httpBody = payload
  561. // Set the headers for starting a streaming session.
  562. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  563. urlRequest.setValue("text/event-stream", forHTTPHeaderField: "Accept")
  564. urlRequest.httpMethod = "POST"
  565. if let authToken = context.authToken {
  566. let value = "Bearer \(authToken)"
  567. urlRequest.setValue(value, forHTTPHeaderField: "Authorization")
  568. }
  569. if let fcmToken = context.fcmToken {
  570. urlRequest.setValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  571. }
  572. if options?.requireLimitedUseAppCheckTokens == true {
  573. if let appCheckToken = context.limitedUseAppCheckToken {
  574. urlRequest.setValue(
  575. appCheckToken,
  576. forHTTPHeaderField: Constants.appCheckTokenHeader
  577. )
  578. }
  579. } else if let appCheckToken = context.appCheckToken {
  580. urlRequest.setValue(
  581. appCheckToken,
  582. forHTTPHeaderField: Constants.appCheckTokenHeader
  583. )
  584. }
  585. return urlRequest
  586. }
  587. private func makeFetcher(url: URL,
  588. data: Any?,
  589. options: HTTPSCallableOptions?,
  590. timeout: TimeInterval,
  591. context: FunctionsContext) throws -> GTMSessionFetcher {
  592. let request = URLRequest(
  593. url: url,
  594. cachePolicy: .useProtocolCachePolicy,
  595. timeoutInterval: timeout
  596. )
  597. let fetcher = fetcherService.fetcher(with: request)
  598. let data = data ?? NSNull()
  599. let encoded = try serializer.encode(data)
  600. let body = ["data": encoded]
  601. let payload = try JSONSerialization.data(withJSONObject: body)
  602. fetcher.bodyData = payload
  603. // Set the headers.
  604. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  605. if let authToken = context.authToken {
  606. let value = "Bearer \(authToken)"
  607. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  608. }
  609. if let fcmToken = context.fcmToken {
  610. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  611. }
  612. if options?.requireLimitedUseAppCheckTokens == true {
  613. if let appCheckToken = context.limitedUseAppCheckToken {
  614. fetcher.setRequestValue(
  615. appCheckToken,
  616. forHTTPHeaderField: Constants.appCheckTokenHeader
  617. )
  618. }
  619. } else if let appCheckToken = context.appCheckToken {
  620. fetcher.setRequestValue(
  621. appCheckToken,
  622. forHTTPHeaderField: Constants.appCheckTokenHeader
  623. )
  624. }
  625. // Override normal security rules if this is a local test.
  626. if emulatorOrigin != nil {
  627. fetcher.allowLocalhostRequest = true
  628. fetcher.allowedInsecureSchemes = ["http"]
  629. }
  630. return fetcher
  631. }
  632. private func processedError(fromResponseError error: any Error,
  633. endpointURL url: URL) -> any Error {
  634. let error = error as NSError
  635. let localError: (any Error)? = if error.domain == kGTMSessionFetcherStatusDomain {
  636. FunctionsError(
  637. httpStatusCode: error.code,
  638. region: region,
  639. url: url,
  640. body: error.userInfo["data"] as? Data,
  641. serializer: serializer
  642. )
  643. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  644. FunctionsError(.deadlineExceeded)
  645. } else { nil }
  646. return localError ?? error
  647. }
  648. private func callableResult(fromResponseData data: Data,
  649. endpointURL url: URL) throws -> sending HTTPSCallableResult {
  650. let processedData = try processedData(fromResponseData: data, endpointURL: url)
  651. let json = try responseDataJSON(from: processedData)
  652. let payload = try serializer.decode(json)
  653. return HTTPSCallableResult(data: payload)
  654. }
  655. private func processedData(fromResponseData data: Data, endpointURL url: URL) throws -> Data {
  656. // `data` might specify a custom error. If so, throw the error.
  657. if let bodyError = FunctionsError(
  658. httpStatusCode: 200,
  659. region: region,
  660. url: url,
  661. body: data,
  662. serializer: serializer
  663. ) {
  664. throw bodyError
  665. }
  666. return data
  667. }
  668. private func responseDataJSON(from data: Data) throws -> sending Any {
  669. let responseJSONObject = try JSONSerialization.jsonObject(with: data)
  670. guard let responseJSON = responseJSONObject as? NSDictionary else {
  671. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  672. throw FunctionsError(.internal, userInfo: userInfo)
  673. }
  674. // `result` is checked for backwards compatibility:
  675. guard let dataJSON = responseJSON["data"] ?? responseJSON["result"] else {
  676. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  677. throw FunctionsError(.internal, userInfo: userInfo)
  678. }
  679. return dataJSON
  680. }
  681. }