Functions.swift 30 KB

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