Functions.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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>)
  420. -> Void) {
  421. let fetcher: GTMSessionFetcher
  422. do {
  423. fetcher = try makeFetcher(
  424. url: url,
  425. data: data,
  426. options: options,
  427. timeout: timeout,
  428. context: context
  429. )
  430. } catch {
  431. DispatchQueue.main.async {
  432. completion(.failure(error))
  433. }
  434. return
  435. }
  436. fetcher.beginFetch { [self] data, error in
  437. let result: Result<HTTPSCallableResult, any Error>
  438. if let error {
  439. result = .failure(processedError(fromResponseError: error, endpointURL: url))
  440. } else if let data {
  441. do {
  442. result = try .success(callableResult(fromResponseData: data, endpointURL: url))
  443. } catch {
  444. result = .failure(error)
  445. }
  446. } else {
  447. result = .failure(FunctionsError(.internal))
  448. }
  449. DispatchQueue.main.async {
  450. completion(result)
  451. }
  452. }
  453. }
  454. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  455. func stream(at url: URL,
  456. data: Any?,
  457. options: HTTPSCallableOptions?,
  458. timeout: TimeInterval)
  459. -> AsyncThrowingStream<JSONStreamResponse, Error> {
  460. AsyncThrowingStream { continuation in
  461. Task {
  462. let urlRequest: URLRequest
  463. do {
  464. let context = try await contextProvider.context(options: options)
  465. urlRequest = try makeRequestForStreamableContent(
  466. url: url,
  467. data: data,
  468. options: options,
  469. timeout: timeout,
  470. context: context
  471. )
  472. } catch {
  473. continuation.finish(throwing: FunctionsError(
  474. .invalidArgument,
  475. userInfo: [NSUnderlyingErrorKey: error]
  476. ))
  477. return
  478. }
  479. let stream: URLSession.AsyncBytes
  480. let rawResponse: URLResponse
  481. do {
  482. (stream, rawResponse) = try await URLSession.shared.bytes(for: urlRequest)
  483. } catch {
  484. continuation.finish(throwing: FunctionsError(
  485. .unavailable,
  486. userInfo: [NSUnderlyingErrorKey: error]
  487. ))
  488. return
  489. }
  490. // Verify the status code is an HTTP response.
  491. guard let response = rawResponse as? HTTPURLResponse else {
  492. continuation.finish(
  493. throwing: FunctionsError(
  494. .unavailable,
  495. userInfo: [NSLocalizedDescriptionKey: "Response was not an HTTP response."]
  496. )
  497. )
  498. return
  499. }
  500. // Verify the status code is a 200.
  501. guard response.statusCode == 200 else {
  502. continuation.finish(
  503. throwing: FunctionsError(
  504. httpStatusCode: response.statusCode,
  505. region: region,
  506. url: url,
  507. body: nil,
  508. serializer: serializer
  509. )
  510. )
  511. return
  512. }
  513. do {
  514. for try await line in stream.lines {
  515. guard line.hasPrefix("data:") else {
  516. continuation.finish(
  517. throwing: FunctionsError(
  518. .dataLoss,
  519. userInfo: [NSLocalizedDescriptionKey: "Unexpected format for streamed response."]
  520. )
  521. )
  522. return
  523. }
  524. do {
  525. // We can assume 5 characters since it's utf-8 encoded, removing `data:`.
  526. let jsonText = String(line.dropFirst(5))
  527. let data = try jsonData(jsonText: jsonText)
  528. // Handle the content and parse it.
  529. let content = try callableStreamResult(fromResponseData: data, endpointURL: url)
  530. continuation.yield(content)
  531. } catch {
  532. continuation.finish(throwing: error)
  533. return
  534. }
  535. }
  536. } catch {
  537. continuation.finish(
  538. throwing: FunctionsError(
  539. .dataLoss,
  540. userInfo: [
  541. NSLocalizedDescriptionKey: "Unexpected format for streamed response.",
  542. NSUnderlyingErrorKey: error,
  543. ]
  544. )
  545. )
  546. return
  547. }
  548. continuation.finish()
  549. }
  550. }
  551. }
  552. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  553. private func callableStreamResult(fromResponseData data: Data,
  554. endpointURL url: URL) throws -> sending JSONStreamResponse {
  555. let data = try processedData(fromResponseData: data, endpointURL: url)
  556. let responseJSONObject: Any
  557. do {
  558. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  559. } catch {
  560. throw FunctionsError(.dataLoss, userInfo: [NSUnderlyingErrorKey: error])
  561. }
  562. guard let responseJSON = responseJSONObject as? [String: Any] else {
  563. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  564. throw FunctionsError(.dataLoss, userInfo: userInfo)
  565. }
  566. if let _ = responseJSON["result"] {
  567. return .result(responseJSON)
  568. } else if let _ = responseJSON["message"] {
  569. return .message(responseJSON)
  570. } else {
  571. throw FunctionsError(
  572. .dataLoss,
  573. userInfo: [NSLocalizedDescriptionKey: "Response is missing result or message field."]
  574. )
  575. }
  576. }
  577. private func jsonData(jsonText: String) throws -> Data {
  578. guard let data = jsonText.data(using: .utf8) else {
  579. throw FunctionsError(.dataLoss, userInfo: [
  580. NSUnderlyingErrorKey: DecodingError.dataCorrupted(DecodingError.Context(
  581. codingPath: [],
  582. debugDescription: "Could not parse response as UTF8."
  583. )),
  584. ])
  585. }
  586. return data
  587. }
  588. private func makeRequestForStreamableContent(url: URL,
  589. data: Any?,
  590. options: HTTPSCallableOptions?,
  591. timeout: TimeInterval,
  592. context: FunctionsContext) throws
  593. -> URLRequest {
  594. var urlRequest = URLRequest(
  595. url: url,
  596. cachePolicy: .useProtocolCachePolicy,
  597. timeoutInterval: timeout
  598. )
  599. let data = data ?? NSNull()
  600. let encoded = try serializer.encode(data)
  601. let body = ["data": encoded]
  602. let payload = try JSONSerialization.data(withJSONObject: body, options: [.fragmentsAllowed])
  603. urlRequest.httpBody = payload
  604. // Set the headers for starting a streaming session.
  605. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  606. urlRequest.setValue("text/event-stream", forHTTPHeaderField: "Accept")
  607. urlRequest.httpMethod = "POST"
  608. if let authToken = context.authToken {
  609. let value = "Bearer \(authToken)"
  610. urlRequest.setValue(value, forHTTPHeaderField: "Authorization")
  611. }
  612. if let fcmToken = context.fcmToken {
  613. urlRequest.setValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  614. }
  615. if options?.requireLimitedUseAppCheckTokens == true {
  616. if let appCheckToken = context.limitedUseAppCheckToken {
  617. urlRequest.setValue(
  618. appCheckToken,
  619. forHTTPHeaderField: Constants.appCheckTokenHeader
  620. )
  621. }
  622. } else if let appCheckToken = context.appCheckToken {
  623. urlRequest.setValue(
  624. appCheckToken,
  625. forHTTPHeaderField: Constants.appCheckTokenHeader
  626. )
  627. }
  628. return urlRequest
  629. }
  630. private func makeFetcher(url: URL,
  631. data: Any?,
  632. options: HTTPSCallableOptions?,
  633. timeout: TimeInterval,
  634. context: FunctionsContext) throws -> GTMSessionFetcher {
  635. let request = URLRequest(
  636. url: url,
  637. cachePolicy: .useProtocolCachePolicy,
  638. timeoutInterval: timeout
  639. )
  640. let fetcher = fetcherService.fetcher(with: request)
  641. let data = data ?? NSNull()
  642. let encoded = try serializer.encode(data)
  643. let body = ["data": encoded]
  644. let payload = try JSONSerialization.data(withJSONObject: body)
  645. fetcher.bodyData = payload
  646. // Set the headers.
  647. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  648. if let authToken = context.authToken {
  649. let value = "Bearer \(authToken)"
  650. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  651. }
  652. if let fcmToken = context.fcmToken {
  653. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  654. }
  655. if options?.requireLimitedUseAppCheckTokens == true {
  656. if let appCheckToken = context.limitedUseAppCheckToken {
  657. fetcher.setRequestValue(
  658. appCheckToken,
  659. forHTTPHeaderField: Constants.appCheckTokenHeader
  660. )
  661. }
  662. } else if let appCheckToken = context.appCheckToken {
  663. fetcher.setRequestValue(
  664. appCheckToken,
  665. forHTTPHeaderField: Constants.appCheckTokenHeader
  666. )
  667. }
  668. // Override normal security rules if this is a local test.
  669. if emulatorOrigin != nil {
  670. fetcher.allowLocalhostRequest = true
  671. fetcher.allowedInsecureSchemes = ["http"]
  672. }
  673. return fetcher
  674. }
  675. private func processedError(fromResponseError error: any Error,
  676. endpointURL url: URL) -> any Error {
  677. let error = error as NSError
  678. let localError: (any Error)? = if error.domain == kGTMSessionFetcherStatusDomain {
  679. FunctionsError(
  680. httpStatusCode: error.code,
  681. region: region,
  682. url: url,
  683. body: error.userInfo["data"] as? Data,
  684. serializer: serializer
  685. )
  686. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  687. FunctionsError(.deadlineExceeded)
  688. } else { nil }
  689. return localError ?? error
  690. }
  691. private func callableResult(fromResponseData data: Data,
  692. endpointURL url: URL) throws -> sending HTTPSCallableResult {
  693. let processedData = try processedData(fromResponseData: data, endpointURL: url)
  694. let json = try responseDataJSON(from: processedData)
  695. let payload = try serializer.decode(json)
  696. return HTTPSCallableResult(data: payload)
  697. }
  698. private func processedData(fromResponseData data: Data, endpointURL url: URL) throws -> Data {
  699. // `data` might specify a custom error. If so, throw the error.
  700. if let bodyError = FunctionsError(
  701. httpStatusCode: 200,
  702. region: region,
  703. url: url,
  704. body: data,
  705. serializer: serializer
  706. ) {
  707. throw bodyError
  708. }
  709. return data
  710. }
  711. private func responseDataJSON(from data: Data) throws -> sending Any {
  712. let responseJSONObject = try JSONSerialization.jsonObject(with: data)
  713. guard let responseJSON = responseJSONObject as? NSDictionary else {
  714. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  715. throw FunctionsError(.internal, userInfo: userInfo)
  716. }
  717. // `result` is checked for backwards compatibility:
  718. guard let dataJSON = responseJSON["data"] ?? responseJSON["result"] else {
  719. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  720. throw FunctionsError(.internal, userInfo: userInfo)
  721. }
  722. return dataJSON
  723. }
  724. }