blob: c9746c03b23c3a124a51334d74a1dd38cdef82d0 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
//
// DeviceDataThrottling.swift
// MullvadVPN
//
// Created by pronebird on 13/12/2022.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadTypes
/// Struct used for throttling UI calls to update device data via tunnel manager.
struct DeviceDataThrottling {
/// Default cooldown interval between requests.
private static let defaultWaitInterval: Duration = .minutes(1)
let tunnelManager: TunnelManager
private(set) var lastUpdate: Date?
init(tunnelManager: TunnelManager) {
self.tunnelManager = tunnelManager
}
mutating func requestUpdate(forceUpdate: Bool) {
guard tunnelManager.deviceState.isLoggedIn else {
return
}
let now = Date()
guard !forceUpdate else {
startUpdate(now: now)
return
}
let nextUpdateAfter = lastUpdate?.addingTimeInterval(Self.defaultWaitInterval.timeInterval)
let comparisonResult = nextUpdateAfter?.compare(now) ?? .orderedAscending
switch comparisonResult {
case .orderedAscending, .orderedSame:
startUpdate(now: now)
case .orderedDescending:
break
}
}
mutating func reset() {
lastUpdate = nil
}
private mutating func startUpdate(now: Date) {
lastUpdate = now
tunnelManager.updateDeviceData()
}
}
|