HeartbeatsPayload.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // Copyright 2021 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 Foundation
  15. #if SWIFT_PACKAGE
  16. import GoogleUtilities_NSData
  17. #else
  18. import GoogleUtilities
  19. #endif // SWIFT_PACKAGE
  20. /// A type that provides a string representation for use in an HTTP header.
  21. public protocol HTTPHeaderRepresentable {
  22. func headerValue() -> String
  23. }
  24. /// A value type representing a payload of heartbeat data intended for sending in network requests.
  25. ///
  26. /// This type's structure is optimized for type-safe encoding into a HTTP payload format.
  27. /// The current encoding format for the payload's current version is:
  28. ///
  29. /// {
  30. /// "version": 2,
  31. /// "heartbeats": [
  32. /// {
  33. /// "agent": "dummy_agent_1",
  34. /// "dates": ["2021-11-01", "2021-11-02"]
  35. /// },
  36. /// {
  37. /// "agent": "dummy_agent_2",
  38. /// "dates": ["2021-11-03"]
  39. /// }
  40. /// ]
  41. /// }
  42. ///
  43. public struct HeartbeatsPayload: Codable {
  44. /// The version of the payload. See go/firebase-apple-heartbeats for details regarding current
  45. /// version.
  46. static let version: Int = 2
  47. /// A payload component composed of a user agent and array of dates (heartbeats).
  48. struct UserAgentPayload: Codable {
  49. /// An anonymous agent string.
  50. let agent: String
  51. /// An array of dates where each date represents a "heartbeat".
  52. let dates: [Date]
  53. }
  54. /// An array of user agent payloads.
  55. let userAgentPayloads: [UserAgentPayload]
  56. /// The version of the payload structure.
  57. let version: Int
  58. /// Alternative keys for properties so encoding follows platform-wide payload structure.
  59. enum CodingKeys: String, CodingKey {
  60. case userAgentPayloads = "heartbeats"
  61. case version
  62. }
  63. /// Designated initializer.
  64. /// - Parameters:
  65. /// - userAgentPayloads: An array of payloads containing heartbeat data corresponding to a
  66. /// given user agent.
  67. /// - version: A version of the payload. Defaults to the static default.
  68. init(userAgentPayloads: [UserAgentPayload] = [], version: Int = version) {
  69. self.userAgentPayloads = userAgentPayloads
  70. self.version = version
  71. }
  72. /// A Boolean value indicating whether the payload is empty.
  73. public var isEmpty: Bool {
  74. userAgentPayloads.isEmpty
  75. }
  76. }
  77. // MARK: - HTTPHeaderRepresentable
  78. extension HeartbeatsPayload: HTTPHeaderRepresentable {
  79. /// Returns a processed payload string intended for use in a HTTP header.
  80. /// - Returns: A string value from the heartbeats payload.
  81. public func headerValue() -> String {
  82. let encoder = JSONEncoder()
  83. encoder.dateEncodingStrategy = .formatted(Self.dateFormatter)
  84. #if DEBUG
  85. // TODO: Remove the following #available check when FirebaseCore's minimum deployment target
  86. // is iOS 11+; all other supported platforms already meet the minimum for `.sortedKeys`.
  87. if #available(iOS 11, *) {
  88. // Sort keys in debug builds to simplify output comparisons in unit tests.
  89. encoder.outputFormatting = .sortedKeys
  90. }
  91. #endif // DEBUG
  92. guard let data = try? encoder.encode(self) else {
  93. // If encoding fails, fall back to encoding with an empty payload.
  94. return Self.emptyPayload.headerValue()
  95. }
  96. do {
  97. let gzippedData = try data.zipped()
  98. return gzippedData.base64URLEncodedString()
  99. } catch {
  100. // If gzipping fails, fall back to encoding with base64URL.
  101. return data.base64URLEncodedString()
  102. }
  103. }
  104. }
  105. // MARK: - Static Defaults
  106. extension HeartbeatsPayload {
  107. /// Convenience instance that represents an empty payload.
  108. static let emptyPayload = HeartbeatsPayload()
  109. /// A default date formatter that uses `yyyy-MM-dd` format.
  110. public static let dateFormatter: DateFormatter = {
  111. let formatter = DateFormatter()
  112. formatter.dateFormat = "yyyy-MM-dd"
  113. formatter.locale = Locale(identifier: "en_US_POSIX")
  114. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  115. return formatter
  116. }()
  117. }
  118. // MARK: - Equatable
  119. extension HeartbeatsPayload: Equatable {}
  120. extension HeartbeatsPayload.UserAgentPayload: Equatable {}
  121. // MARK: - Data
  122. public extension Data {
  123. /// Returns a Base-64 URL-safe encoded string.
  124. ///
  125. /// - parameter options: The options to use for the encoding. Default value is `[]`.
  126. /// - returns: The Base-64 URL-safe encoded string.
  127. func base64URLEncodedString(options: Data.Base64EncodingOptions = []) -> String {
  128. base64EncodedString()
  129. .replacingOccurrences(of: "/", with: "_")
  130. .replacingOccurrences(of: "+", with: "-")
  131. .replacingOccurrences(of: "=", with: "")
  132. }
  133. /// Initialize a `Data` from a Base-64 URL encoded String using the given options.
  134. ///
  135. /// Returns nil when the input is not recognized as valid Base-64.
  136. /// - parameter base64URLString: The string to parse.
  137. /// - parameter options: Encoding options. Default value is `[]`.
  138. init?(base64URLEncoded base64URLString: String, options: Data.Base64DecodingOptions = []) {
  139. var base64Encoded = base64URLString
  140. .replacingOccurrences(of: "_", with: "/")
  141. .replacingOccurrences(of: "-", with: "+")
  142. // Pad the string with "=" signs until the string's length is a multiple of 4.
  143. while !base64Encoded.count.isMultiple(of: 4) {
  144. base64Encoded.append("=")
  145. }
  146. self.init(base64Encoded: base64Encoded, options: options)
  147. }
  148. /// Returns the compressed data.
  149. /// - Returns: The compressed data.
  150. /// - Throws: An error if compression failed.
  151. func zipped() throws -> Data {
  152. try NSData.gul_data(byGzippingData: self)
  153. }
  154. /// Returns the uncompressed data.
  155. /// - Returns: The decompressed data.
  156. /// - Throws: An error if decompression failed.
  157. func unzipped() throws -> Data {
  158. try NSData.gul_data(byInflatingGzippedData: self)
  159. }
  160. }