Functions.swift 30 KB

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