Functions.swift 31 KB

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