DBSize.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // LoopFollow
  2. // DBSize.swift
  3. import Foundation
  4. /// Response shape of `/api/v2/properties/dbsize`.
  5. ///
  6. /// Nightscout's `dbsize` plugin reports the Mongo `dataSize + indexSize` sum
  7. /// against `DBSIZE_MAX` (defaults to 496 MiB when the site admin has not set it).
  8. /// The key is absent when the plugin has not produced a property yet.
  9. struct DBSizeProperties: Codable {
  10. let dbsize: DBSizeData?
  11. }
  12. struct DBSizeData: Codable {
  13. /// Used size, in MiB.
  14. let totalDataSize: Double?
  15. /// Used size as a percentage of `details.maxSize`, floored by the server.
  16. let dataPercentage: Int?
  17. let details: Details?
  18. struct Details: Codable {
  19. /// The configured limit in MiB (`DBSIZE_MAX`).
  20. let maxSize: Double?
  21. let dataSize: Double?
  22. }
  23. }
  24. extension MainViewController {
  25. // NS Database Size Web Call
  26. func webLoadNSDBSize() {
  27. NightscoutUtils.executeRequest(eventType: .dbSize, parameters: [:]) { (result: Result<DBSizeProperties, Error>) in
  28. switch result {
  29. case let .success(properties):
  30. self.updateDBSize(data: properties.dbsize)
  31. case let .failure(error):
  32. LogManager.shared.log(category: .nightscout, message: "webLoadNSDBSize, error: \(error.localizedDescription)")
  33. }
  34. }
  35. }
  36. // NS Database Size Response Processor
  37. func updateDBSize(data: DBSizeData?) {
  38. // Nightscout still reports the property when `db.stats()` failed, but with a zero
  39. // size. Its own pill hides on that, so treat it as "no reading" rather than 0%.
  40. guard let data = data, let usedMiB = data.totalDataSize, usedMiB > 0 else {
  41. infoManager.clearInfoData(type: .dbSize)
  42. Observable.shared.dbSizePercentage.set(nil)
  43. return
  44. }
  45. Observable.shared.dbSizePercentage.set(data.dataPercentage.map(Double.init))
  46. let used = Localizer.formatToLocalizedString(usedMiB, maxFractionDigits: 0, minFractionDigits: 0)
  47. if let percentage = data.dataPercentage {
  48. infoManager.updateInfoData(type: .dbSize, value: "\(used) MiB (\(percentage)%)")
  49. } else {
  50. infoManager.updateInfoData(type: .dbSize, value: "\(used) MiB")
  51. }
  52. }
  53. }