File: AsyncThrottleSequence.swift

package info (click to toggle)
swiftlang 6.1.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 2,791,644 kB
  • sloc: cpp: 9,901,738; ansic: 2,201,433; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (116 lines) | stat: -rw-r--r-- 4,871 bytes parent folder | download | duplicates (2)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

extension AsyncSequence {
  /// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
  @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  public func _throttle<C: Clock, Reduced>(for interval: C.Instant.Duration, clock: C, reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced) -> _AsyncThrottleSequence<Self, C, Reduced> {
      _AsyncThrottleSequence(self, interval: interval, clock: clock, reducing: reducing)
  }
  
  /// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
  @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  public func _throttle<Reduced>(for interval: Duration, reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced) -> _AsyncThrottleSequence<Self, ContinuousClock, Reduced> {
      _throttle(for: interval, clock: .continuous, reducing: reducing)
  }
  
  /// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
  @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  public func _throttle<C: Clock>(for interval: C.Instant.Duration, clock: C, latest: Bool = true) -> _AsyncThrottleSequence<Self, C, Element> {
      _throttle(for: interval, clock: clock) { previous, element in
      if latest {
        return element
      } else {
        return previous ?? element
      }
    }
  }
  
  /// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
  @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  public func _throttle(for interval: Duration, latest: Bool = true) -> _AsyncThrottleSequence<Self, ContinuousClock, Element> {
      _throttle(for: interval, clock: .continuous, latest: latest)
  }
}

/// A rate-limited `AsyncSequence` by emitting values at most every specified interval.
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public struct _AsyncThrottleSequence<Base: AsyncSequence, C: Clock, Reduced> {
  let base: Base
  let interval: C.Instant.Duration
  let clock: C
  let reducing: @Sendable (Reduced?, Base.Element) async -> Reduced
  
  init(_ base: Base, interval: C.Instant.Duration, clock: C, reducing: @Sendable @escaping (Reduced?, Base.Element) async -> Reduced) {
    self.base = base
    self.interval = interval
    self.clock = clock
    self.reducing = reducing
  }
}

@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension _AsyncThrottleSequence: AsyncSequence {
  public typealias Element = Reduced
  
  /// The iterator for an `AsyncThrottleSequence` instance.
  public struct Iterator: AsyncIteratorProtocol {
    var base: Base.AsyncIterator
    var last: C.Instant?
    let interval: C.Instant.Duration
    let clock: C
    let reducing: @Sendable (Reduced?, Base.Element) async -> Reduced
    
    init(_ base: Base.AsyncIterator, interval: C.Instant.Duration, clock: C, reducing: @Sendable @escaping (Reduced?, Base.Element) async -> Reduced) {
      self.base = base
      self.interval = interval
      self.clock = clock
      self.reducing = reducing
    }
    
    public mutating func next() async rethrows -> Reduced? {
      var reduced: Reduced?
      let start = last ?? clock.now
      repeat {
        guard let element = try await base.next() else {
          if reduced != nil, let last {
            // ensure the rate of elements never exceeds the given interval
            let amount = interval - last.duration(to: clock.now)
            if amount > .zero {
              try? await clock.sleep(until: clock.now.advanced(by: amount), tolerance: nil)
            }
          }
          // the last value is unable to have any subsequent
          // values so always return the last reduction
          return reduced
        }
        let reduction = await reducing(reduced, element)
        let now = clock.now
        if start.duration(to: now) >= interval || last == nil {
          last = now
          return reduction
        } else {
          reduced = reduction
        }
      } while true
    }
  }
  
  public func makeAsyncIterator() -> Iterator {
    Iterator(base.makeAsyncIterator(), interval: interval, clock: clock, reducing: reducing)
  }
}

@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension _AsyncThrottleSequence: Sendable where Base: Sendable, Element: Sendable { }

@available(*, unavailable)
extension _AsyncThrottleSequence.Iterator: Sendable { }