Functions.swift 29 KB

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