HeartbeatsPayload.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. @_implementationOnly import GoogleUtilities_NSData
  17. #else
  18. @_implementationOnly 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, Sendable {
  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. // Sort keys in debug builds to simplify output comparisons in unit tests.
  86. encoder.outputFormatting = .sortedKeys
  87. #endif // DEBUG
  88. guard let data = try? encoder.encode(self) else {
  89. // If encoding fails, fall back to encoding with an empty payload.
  90. return Self.emptyPayload.headerValue()
  91. }
  92. do {
  93. let gzippedData = try data.zipped()
  94. return gzippedData.base64URLEncodedString()
  95. } catch {
  96. // If gzipping fails, fall back to encoding with base64URL.
  97. return data.base64URLEncodedString()
  98. }
  99. }
  100. }
  101. // MARK: - Static Defaults
  102. extension HeartbeatsPayload {
  103. /// Convenience instance that represents an empty payload.
  104. static let emptyPayload = HeartbeatsPayload()
  105. /// A default date formatter that uses `yyyy-MM-dd` format.
  106. public static let dateFormatter: DateFormatter = {
  107. let formatter = DateFormatter()
  108. formatter.dateFormat = "yyyy-MM-dd"
  109. formatter.locale = Locale(identifier: "en_US_POSIX")
  110. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  111. return formatter
  112. }()
  113. }
  114. // MARK: - Equatable
  115. extension HeartbeatsPayload: Equatable {}
  116. extension HeartbeatsPayload.UserAgentPayload: Equatable {}
  117. // MARK: - Data
  118. public extension Data {
  119. /// Returns a Base-64 URL-safe encoded string.
  120. ///
  121. /// - parameter options: The options to use for the encoding. Default value is `[]`.
  122. /// - returns: The Base-64 URL-safe encoded string.
  123. func base64URLEncodedString(options: Data.Base64EncodingOptions = []) -> String {
  124. base64EncodedString()
  125. .replacingOccurrences(of: "/", with: "_")
  126. .replacingOccurrences(of: "+", with: "-")
  127. .replacingOccurrences(of: "=", with: "")
  128. }
  129. /// Initialize a `Data` from a Base-64 URL encoded String using the given options.
  130. ///
  131. /// Returns nil when the input is not recognized as valid Base-64.
  132. /// - parameter base64URLString: The string to parse.
  133. /// - parameter options: Encoding options. Default value is `[]`.
  134. init?(base64URLEncoded base64URLString: String, options: Data.Base64DecodingOptions = []) {
  135. var base64Encoded = base64URLString
  136. .replacingOccurrences(of: "_", with: "/")
  137. .replacingOccurrences(of: "-", with: "+")
  138. // Pad the string with "=" signs until the string's length is a multiple of 4.
  139. while !base64Encoded.count.isMultiple(of: 4) {
  140. base64Encoded.append("=")
  141. }
  142. self.init(base64Encoded: base64Encoded, options: options)
  143. }
  144. /// Returns the compressed data.
  145. /// - Returns: The compressed data.
  146. /// - Throws: An error if compression failed.
  147. func zipped() throws -> Data {
  148. try NSData.gul_data(byGzippingData: self)
  149. }
  150. /// Returns the uncompressed data.
  151. /// - Returns: The decompressed data.
  152. /// - Throws: An error if decompression failed.
  153. func unzipped() throws -> Data {
  154. try NSData.gul_data(byInflatingGzippedData: self)
  155. }
  156. }