Functions.swift 31 KB

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