Functions.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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. @preconcurrency import GTMSessionFetcher
  22. #else
  23. @preconcurrency import GTMSessionFetcherCore
  24. #endif
  25. internal import FirebaseCoreExtension
  26. final class AtomicBox<T>: Sendable {
  27. private nonisolated(unsafe) var _value: T
  28. private let lock = NSLock()
  29. public init(_ value: T) where T: Sendable {
  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, @unchecked Sendable {
  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 static let 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. private let _emulatorOrigin: AtomicBox<String?>
  80. // MARK: - Public APIs
  81. /// The current emulator origin, or `nil` if it is not set.
  82. open var emulatorOrigin: String? {
  83. _emulatorOrigin.value()
  84. }
  85. /// Creates a Cloud Functions client using the default or returns a pre-existing instance if it
  86. /// already exists.
  87. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp`.
  88. @objc(functions) open class func functions() -> Functions {
  89. return functions(
  90. app: FirebaseApp.app(),
  91. region: FunctionsConstants.defaultRegion,
  92. customDomain: nil
  93. )
  94. }
  95. /// Creates a Cloud Functions client with the given app, or returns a pre-existing
  96. /// instance if one already exists.
  97. /// - Parameter app: The app for the Firebase project.
  98. /// - Returns: A shared Functions instance initialized with the specified `FirebaseApp`.
  99. @objc(functionsForApp:) open class func functions(app: FirebaseApp) -> Functions {
  100. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: nil)
  101. }
  102. /// Creates a Cloud Functions client with the default app and given region.
  103. /// - Parameter region: The region for the HTTP trigger, such as `us-central1`.
  104. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  105. /// custom region.
  106. @objc(functionsForRegion:) open class func functions(region: String) -> Functions {
  107. return functions(app: FirebaseApp.app(), region: region, customDomain: nil)
  108. }
  109. /// Creates a Cloud Functions client with the given custom domain or returns a pre-existing
  110. /// instance if one already exists.
  111. /// - Parameter customDomain: A custom domain for the HTTP trigger, such as
  112. /// "https://mydomain.com".
  113. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  114. /// custom HTTP trigger domain.
  115. @objc(functionsForCustomDomain:) open class func functions(customDomain: String) -> Functions {
  116. return functions(app: FirebaseApp.app(),
  117. region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  118. }
  119. /// Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  120. /// instance if one already exists.
  121. /// - Parameters:
  122. /// - app: The app for the Firebase project.
  123. /// - region: The region for the HTTP trigger, such as `us-central1`.
  124. /// - Returns: An instance of `Functions` with a custom app and region.
  125. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp,
  126. region: String) -> Functions {
  127. return functions(app: app, region: region, customDomain: nil)
  128. }
  129. /// Creates a Cloud Functions client with the given app and custom domain, or returns a
  130. /// pre-existing
  131. /// instance if one already exists.
  132. /// - Parameters:
  133. /// - app: The app for the Firebase project.
  134. /// - customDomain: A custom domain for the HTTP trigger, such as `https://mydomain.com`.
  135. /// - Returns: An instance of `Functions` with a custom app and HTTP trigger domain.
  136. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp,
  137. customDomain: String)
  138. -> Functions {
  139. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  140. }
  141. /// Creates a reference to the Callable HTTPS trigger with the given name.
  142. /// - Parameter name: The name of the Callable HTTPS trigger.
  143. /// - Returns: A reference to a Callable HTTPS trigger.
  144. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  145. HTTPSCallable(functions: self, url: functionURL(for: name)!)
  146. }
  147. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  148. /// options.
  149. /// - Parameters:
  150. /// - name: The name of the Callable HTTPS trigger.
  151. /// - options: The options with which to customize the Callable HTTPS trigger.
  152. /// - Returns: A reference to a Callable HTTPS trigger.
  153. @objc(HTTPSCallableWithName:options:) public func httpsCallable(_ name: String,
  154. options: HTTPSCallableOptions)
  155. -> HTTPSCallable {
  156. HTTPSCallable(functions: self, url: functionURL(for: name)!, options: options)
  157. }
  158. /// Creates a reference to the Callable HTTPS trigger with the given name.
  159. /// - Parameter url: The URL of the Callable HTTPS trigger.
  160. /// - Returns: A reference to a Callable HTTPS trigger.
  161. @objc(HTTPSCallableWithURL:) open func httpsCallable(_ url: URL) -> HTTPSCallable {
  162. return HTTPSCallable(functions: self, url: url)
  163. }
  164. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  165. /// options.
  166. /// - Parameters:
  167. /// - url: The URL of the Callable HTTPS trigger.
  168. /// - options: The options with which to customize the Callable HTTPS trigger.
  169. /// - Returns: A reference to a Callable HTTPS trigger.
  170. @objc(HTTPSCallableWithURL:options:) public func httpsCallable(_ url: URL,
  171. options: HTTPSCallableOptions)
  172. -> HTTPSCallable {
  173. return HTTPSCallable(functions: self, url: url, options: options)
  174. }
  175. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  176. /// `Encodable`
  177. /// request and the type of a `Decodable` response.
  178. /// - Parameters:
  179. /// - name: The name of the Callable HTTPS trigger
  180. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  181. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  182. /// - encoder: The encoder instance to use to perform encoding.
  183. /// - decoder: The decoder instance to use to perform decoding.
  184. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  185. /// Functions invocations.
  186. open func httpsCallable<Request: Encodable,
  187. Response: Decodable>(_ name: String,
  188. requestAs: Request.Type = Request.self,
  189. responseAs: Response.Type = Response.self,
  190. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  191. ),
  192. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  193. ))
  194. -> Callable<Request, Response> {
  195. return Callable(
  196. callable: httpsCallable(name),
  197. encoder: encoder,
  198. decoder: decoder
  199. )
  200. }
  201. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  202. /// `Encodable`
  203. /// request and the type of a `Decodable` response.
  204. /// - Parameters:
  205. /// - name: The name of the Callable HTTPS trigger
  206. /// - options: The options with which to customize the Callable HTTPS trigger.
  207. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  208. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  209. /// - encoder: The encoder instance to use to perform encoding.
  210. /// - decoder: The decoder instance to use to perform decoding.
  211. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  212. /// Functions invocations.
  213. open func httpsCallable<Request: Encodable,
  214. Response: Decodable>(_ name: String,
  215. options: HTTPSCallableOptions,
  216. requestAs: Request.Type = Request.self,
  217. responseAs: Response.Type = Response.self,
  218. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  219. ),
  220. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  221. ))
  222. -> Callable<Request, Response> {
  223. return Callable(
  224. callable: httpsCallable(name, options: options),
  225. encoder: encoder,
  226. decoder: decoder
  227. )
  228. }
  229. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  230. /// `Encodable`
  231. /// request and the type of a `Decodable` response.
  232. /// - Parameters:
  233. /// - url: The url of the Callable HTTPS trigger
  234. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  235. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  236. /// - encoder: The encoder instance to use to perform encoding.
  237. /// - decoder: The decoder instance to use to perform decoding.
  238. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  239. /// Functions invocations.
  240. open func httpsCallable<Request: Encodable,
  241. Response: Decodable>(_ url: URL,
  242. requestAs: Request.Type = Request.self,
  243. responseAs: Response.Type = Response.self,
  244. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  245. ),
  246. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  247. ))
  248. -> Callable<Request, Response> {
  249. return Callable(
  250. callable: httpsCallable(url),
  251. encoder: encoder,
  252. decoder: decoder
  253. )
  254. }
  255. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  256. /// `Encodable`
  257. /// request and the type of a `Decodable` response.
  258. /// - Parameters:
  259. /// - url: The url of the Callable HTTPS trigger
  260. /// - options: The options with which to customize the Callable HTTPS trigger.
  261. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  262. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  263. /// - encoder: The encoder instance to use to perform encoding.
  264. /// - decoder: The decoder instance to use to perform decoding.
  265. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  266. /// Functions invocations.
  267. open func httpsCallable<Request: Encodable,
  268. Response: Decodable>(_ url: URL,
  269. options: HTTPSCallableOptions,
  270. requestAs: Request.Type = Request.self,
  271. responseAs: Response.Type = Response.self,
  272. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  273. ),
  274. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  275. ))
  276. -> Callable<Request, Response> {
  277. return Callable(
  278. callable: httpsCallable(url, options: options),
  279. encoder: encoder,
  280. decoder: decoder
  281. )
  282. }
  283. /**
  284. * Changes this instance to point to a Cloud Functions emulator running locally.
  285. * See https://firebase.google.com/docs/functions/local-emulator
  286. * - Parameters:
  287. * - host: The host of the local emulator, such as "localhost".
  288. * - port: The port of the local emulator, for example 5005.
  289. */
  290. @objc open func useEmulator(withHost host: String, port: Int) {
  291. let prefix = host.hasPrefix("http") ? "" : "http://"
  292. let origin = String(format: "\(prefix)\(host):%li", port)
  293. _emulatorOrigin.withLock { emulatorOrigin in
  294. emulatorOrigin = origin
  295. }
  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 = AtomicBox(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 -> sending 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 @MainActor (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. DispatchQueue.main.async {
  407. completion(.failure(error))
  408. }
  409. } else {
  410. self.callFunction(url: url,
  411. withObject: data,
  412. options: options,
  413. timeout: timeout,
  414. context: context,
  415. completion: completion)
  416. }
  417. }
  418. }
  419. private func callFunction(url: URL,
  420. withObject data: Any?,
  421. options: HTTPSCallableOptions?,
  422. timeout: TimeInterval,
  423. context: FunctionsContext,
  424. completion: @escaping @MainActor (Result<HTTPSCallableResult, Error>)
  425. -> Void) {
  426. let fetcher: GTMSessionFetcher
  427. do {
  428. fetcher = try makeFetcher(
  429. url: url,
  430. data: data,
  431. options: options,
  432. timeout: timeout,
  433. context: context
  434. )
  435. } catch {
  436. DispatchQueue.main.async {
  437. completion(.failure(error))
  438. }
  439. return
  440. }
  441. fetcher.beginFetch { [self] data, error in
  442. let result: Result<HTTPSCallableResult, any Error>
  443. if let error {
  444. result = .failure(processedError(fromResponseError: error, endpointURL: url))
  445. } else if let data {
  446. do {
  447. result = try .success(callableResult(fromResponseData: data, endpointURL: url))
  448. } catch {
  449. result = .failure(error)
  450. }
  451. } else {
  452. result = .failure(FunctionsError(.internal))
  453. }
  454. DispatchQueue.main.async {
  455. completion(result)
  456. }
  457. }
  458. }
  459. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  460. func stream(at url: URL,
  461. data: SendableWrapper?,
  462. options: HTTPSCallableOptions?,
  463. timeout: TimeInterval)
  464. -> AsyncThrowingStream<JSONStreamResponse, Error> {
  465. AsyncThrowingStream { continuation in
  466. Task {
  467. let urlRequest: URLRequest
  468. do {
  469. let context = try await contextProvider.context(options: options)
  470. urlRequest = try makeRequestForStreamableContent(
  471. url: url,
  472. data: data?.value,
  473. options: options,
  474. timeout: timeout,
  475. context: context
  476. )
  477. } catch {
  478. continuation.finish(throwing: FunctionsError(
  479. .invalidArgument,
  480. userInfo: [NSUnderlyingErrorKey: error]
  481. ))
  482. return
  483. }
  484. let stream: URLSession.AsyncBytes
  485. let rawResponse: URLResponse
  486. do {
  487. (stream, rawResponse) = try await URLSession.shared.bytes(for: urlRequest)
  488. } catch {
  489. continuation.finish(throwing: FunctionsError(
  490. .unavailable,
  491. userInfo: [NSUnderlyingErrorKey: error]
  492. ))
  493. return
  494. }
  495. // Verify the status code is an HTTP response.
  496. guard let response = rawResponse as? HTTPURLResponse else {
  497. continuation.finish(
  498. throwing: FunctionsError(
  499. .unavailable,
  500. userInfo: [NSLocalizedDescriptionKey: "Response was not an HTTP response."]
  501. )
  502. )
  503. return
  504. }
  505. // Verify the status code is a 200.
  506. guard response.statusCode == 200 else {
  507. continuation.finish(
  508. throwing: FunctionsError(
  509. httpStatusCode: response.statusCode,
  510. region: region,
  511. url: url,
  512. body: nil,
  513. serializer: serializer
  514. )
  515. )
  516. return
  517. }
  518. do {
  519. for try await line in stream.lines {
  520. guard line.hasPrefix("data:") else {
  521. continuation.finish(
  522. throwing: FunctionsError(
  523. .dataLoss,
  524. userInfo: [NSLocalizedDescriptionKey: "Unexpected format for streamed response."]
  525. )
  526. )
  527. return
  528. }
  529. do {
  530. // We can assume 5 characters since it's utf-8 encoded, removing `data:`.
  531. let jsonText = String(line.dropFirst(5))
  532. let data = try jsonData(jsonText: jsonText)
  533. // Handle the content and parse it.
  534. let content = try callableStreamResult(fromResponseData: data, endpointURL: url)
  535. continuation.yield(content)
  536. } catch {
  537. continuation.finish(throwing: error)
  538. return
  539. }
  540. }
  541. } catch {
  542. continuation.finish(
  543. throwing: FunctionsError(
  544. .dataLoss,
  545. userInfo: [
  546. NSLocalizedDescriptionKey: "Unexpected format for streamed response.",
  547. NSUnderlyingErrorKey: error,
  548. ]
  549. )
  550. )
  551. return
  552. }
  553. continuation.finish()
  554. }
  555. }
  556. }
  557. @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
  558. private func callableStreamResult(fromResponseData data: Data,
  559. endpointURL url: URL) throws -> sending JSONStreamResponse {
  560. let data = try processedData(fromResponseData: data, endpointURL: url)
  561. let responseJSONObject: Any
  562. do {
  563. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  564. } catch {
  565. throw FunctionsError(.dataLoss, userInfo: [NSUnderlyingErrorKey: error])
  566. }
  567. guard let responseJSON = responseJSONObject as? [String: Any] else {
  568. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  569. throw FunctionsError(.dataLoss, userInfo: userInfo)
  570. }
  571. if let _ = responseJSON["result"] {
  572. return .result(responseJSON)
  573. } else if let _ = responseJSON["message"] {
  574. return .message(responseJSON)
  575. } else {
  576. throw FunctionsError(
  577. .dataLoss,
  578. userInfo: [NSLocalizedDescriptionKey: "Response is missing result or message field."]
  579. )
  580. }
  581. }
  582. private func jsonData(jsonText: String) throws -> Data {
  583. guard let data = jsonText.data(using: .utf8) else {
  584. throw FunctionsError(.dataLoss, userInfo: [
  585. NSUnderlyingErrorKey: DecodingError.dataCorrupted(DecodingError.Context(
  586. codingPath: [],
  587. debugDescription: "Could not parse response as UTF8."
  588. )),
  589. ])
  590. }
  591. return data
  592. }
  593. private func makeRequestForStreamableContent(url: URL,
  594. data: Any?,
  595. options: HTTPSCallableOptions?,
  596. timeout: TimeInterval,
  597. context: FunctionsContext) throws
  598. -> URLRequest {
  599. var urlRequest = URLRequest(
  600. url: url,
  601. cachePolicy: .useProtocolCachePolicy,
  602. timeoutInterval: timeout
  603. )
  604. let data = data ?? NSNull()
  605. let encoded = try serializer.encode(data)
  606. let body = ["data": encoded]
  607. let payload = try JSONSerialization.data(withJSONObject: body, options: [.fragmentsAllowed])
  608. urlRequest.httpBody = payload
  609. // Set the headers for starting a streaming session.
  610. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  611. urlRequest.setValue("text/event-stream", forHTTPHeaderField: "Accept")
  612. urlRequest.httpMethod = "POST"
  613. if let authToken = context.authToken {
  614. let value = "Bearer \(authToken)"
  615. urlRequest.setValue(value, forHTTPHeaderField: "Authorization")
  616. }
  617. if let fcmToken = context.fcmToken {
  618. urlRequest.setValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  619. }
  620. if options?.requireLimitedUseAppCheckTokens == true {
  621. if let appCheckToken = context.limitedUseAppCheckToken {
  622. urlRequest.setValue(
  623. appCheckToken,
  624. forHTTPHeaderField: Constants.appCheckTokenHeader
  625. )
  626. }
  627. } else if let appCheckToken = context.appCheckToken {
  628. urlRequest.setValue(
  629. appCheckToken,
  630. forHTTPHeaderField: Constants.appCheckTokenHeader
  631. )
  632. }
  633. return urlRequest
  634. }
  635. private func makeFetcher(url: URL,
  636. data: Any?,
  637. options: HTTPSCallableOptions?,
  638. timeout: TimeInterval,
  639. context: FunctionsContext) throws -> GTMSessionFetcher {
  640. let request = URLRequest(
  641. url: url,
  642. cachePolicy: .useProtocolCachePolicy,
  643. timeoutInterval: timeout
  644. )
  645. let fetcher = fetcherService.fetcher(with: request)
  646. let data = data ?? NSNull()
  647. let encoded = try serializer.encode(data)
  648. let body = ["data": encoded]
  649. let payload = try JSONSerialization.data(withJSONObject: body)
  650. fetcher.bodyData = payload
  651. // Set the headers.
  652. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  653. if let authToken = context.authToken {
  654. let value = "Bearer \(authToken)"
  655. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  656. }
  657. if let fcmToken = context.fcmToken {
  658. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  659. }
  660. if options?.requireLimitedUseAppCheckTokens == true {
  661. if let appCheckToken = context.limitedUseAppCheckToken {
  662. fetcher.setRequestValue(
  663. appCheckToken,
  664. forHTTPHeaderField: Constants.appCheckTokenHeader
  665. )
  666. }
  667. } else if let appCheckToken = context.appCheckToken {
  668. fetcher.setRequestValue(
  669. appCheckToken,
  670. forHTTPHeaderField: Constants.appCheckTokenHeader
  671. )
  672. }
  673. // Override normal security rules if this is a local test.
  674. if emulatorOrigin != nil {
  675. fetcher.allowLocalhostRequest = true
  676. fetcher.allowedInsecureSchemes = ["http"]
  677. }
  678. return fetcher
  679. }
  680. private func processedError(fromResponseError error: any Error,
  681. endpointURL url: URL) -> any Error {
  682. let error = error as NSError
  683. let localError: (any Error)? = if error.domain == kGTMSessionFetcherStatusDomain {
  684. FunctionsError(
  685. httpStatusCode: error.code,
  686. region: region,
  687. url: url,
  688. body: error.userInfo["data"] as? Data,
  689. serializer: serializer
  690. )
  691. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  692. FunctionsError(.deadlineExceeded)
  693. } else { nil }
  694. return localError ?? error
  695. }
  696. private func callableResult(fromResponseData data: Data,
  697. endpointURL url: URL) throws -> sending HTTPSCallableResult {
  698. let processedData = try processedData(fromResponseData: data, endpointURL: url)
  699. let json = try responseDataJSON(from: processedData)
  700. let payload = try serializer.decode(json)
  701. return HTTPSCallableResult(data: payload)
  702. }
  703. private func processedData(fromResponseData data: Data, endpointURL url: URL) throws -> Data {
  704. // `data` might specify a custom error. If so, throw the error.
  705. if let bodyError = FunctionsError(
  706. httpStatusCode: 200,
  707. region: region,
  708. url: url,
  709. body: data,
  710. serializer: serializer
  711. ) {
  712. throw bodyError
  713. }
  714. return data
  715. }
  716. private func responseDataJSON(from data: Data) throws -> sending Any {
  717. let responseJSONObject = try JSONSerialization.jsonObject(with: data)
  718. guard let responseJSON = responseJSONObject as? NSDictionary else {
  719. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  720. throw FunctionsError(.internal, userInfo: userInfo)
  721. }
  722. // `result` is checked for backwards compatibility:
  723. guard let dataJSON = responseJSON["data"] ?? responseJSON["result"] else {
  724. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  725. throw FunctionsError(.internal, userInfo: userInfo)
  726. }
  727. return dataJSON
  728. }
  729. }