Skip to content

Commit edb2126

Browse files
authored
Document and constrain WorkQueue.maxConcurrency (#120)
1 parent d314c12 commit edb2126

2 files changed

Lines changed: 88 additions & 8 deletions

File tree

‎Sources/Mapnik/WorkQueue.swift‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,22 +43,51 @@ public actor WorkQueue<Work: Sendable, Result: Sendable> {
4343
private let processWork: @Sendable (Work) async throws -> Result?
4444
private let onResult: @Sendable (Work, Result?) async throws -> Void
4545

46+
/// The range ``maxConcurrency`` is clamped to.
47+
///
48+
/// Values outside this range are clamped rather than rejected, so callers
49+
/// that need to validate their own input can check against it first.
50+
public static var concurrencyRange: ClosedRange<Int> {
51+
1 ... 256
52+
}
53+
4654
private var _maxConcurrency: Int
4755
private var inFlight = 0
4856

49-
/// The maximum number of concurrently processed work items (1...256).
57+
/// The maximum number of concurrently processed work items.
58+
///
59+
/// The value is clamped to ``concurrencyRange``: assigning `1000` stores
60+
/// `256`, assigning `0` stores `1`. Check against ``concurrencyRange``
61+
/// before assigning if the exact value matters.
62+
///
63+
/// Changing this while ``start()`` is running is supported. The queue
64+
/// re-reads it each time it refills, so a raised limit takes effect as
65+
/// soon as an in-flight item finishes. Lowering it does not interrupt
66+
/// running `processWork` calls, so the number of concurrent items can
67+
/// briefly exceed the new limit until they complete.
5068
public var maxConcurrency: Int {
5169
get { _maxConcurrency }
52-
set { _maxConcurrency = max(1, min(256, newValue)) }
70+
set { _maxConcurrency = Self.clamp(newValue) }
71+
}
72+
73+
/// Clamps `value` into ``concurrencyRange``.
74+
private static func clamp(_ value: Int) -> Int {
75+
min(max(value, concurrencyRange.lowerBound), concurrencyRange.upperBound)
5376
}
5477

55-
/// Sets the maximum concurrency, clamped to 1...256.
78+
/// Sets ``maxConcurrency`` from outside the actor.
79+
///
80+
/// The property itself is readable from any context, but Swift only
81+
/// permits mutating actor state from inside the actor, so this method is
82+
/// the supported way to change the limit. It clamps to
83+
/// ``concurrencyRange`` exactly like the setter does.
5684
public func setMaxConcurrency(_ value: Int) {
5785
maxConcurrency = value
5886
}
5987

6088
/// - Parameters:
61-
/// - maxConcurrency: Upper bound for parallel `processWork` calls.
89+
/// - maxConcurrency: Upper bound for parallel `processWork` calls,
90+
/// clamped to ``concurrencyRange``.
6291
/// - fetchWork: Produces the next work item, or `nil` when the queue
6392
/// should drain and finish. Called on the actor.
6493
/// - processWork: Transforms a work item into a result. Runs detached
@@ -72,7 +101,7 @@ public actor WorkQueue<Work: Sendable, Result: Sendable> {
72101
processWork: @escaping @Sendable (Work) async throws -> Result?,
73102
onResult: @escaping @Sendable (Work, Result?) async throws -> Void,
74103
) {
75-
self._maxConcurrency = max(1, min(256, maxConcurrency))
104+
self._maxConcurrency = Self.clamp(maxConcurrency)
76105
self.fetchWork = fetchWork
77106
self.processWork = processWork
78107
self.onResult = onResult

‎Tests/MapnikTests/WorkQueueTests.swift‎

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ struct WorkQueueTests {
8787
#expect(processed.value == 30)
8888
}
8989

90-
/// Max concurrency clamped to sane range.
90+
/// Max concurrency is clamped to the documented range.
9191
@Test
9292
func maxConcurrencyClampedToSaneRange() async {
9393
let queue = WorkQueue<Int, Int>(
@@ -97,9 +97,47 @@ struct WorkQueueTests {
9797
onResult: { _, _ in },
9898
)
9999

100-
#expect(await queue.maxConcurrency == 256)
100+
#expect(await queue.maxConcurrency == WorkQueue<Int, Int>.concurrencyRange.upperBound)
101+
102+
// setMaxConcurrency is the only way to change it from outside the
103+
// actor, and it clamps like the property setter.
101104
await queue.setMaxConcurrency(0)
102-
#expect(await queue.maxConcurrency == 1)
105+
#expect(await queue.maxConcurrency == WorkQueue<Int, Int>.concurrencyRange.lowerBound)
106+
107+
await queue.setMaxConcurrency(8)
108+
#expect(await queue.maxConcurrency == 8)
109+
}
110+
111+
/// Raising the limit mid-run takes effect without interrupting work.
112+
@Test
113+
func raisingMaxConcurrencyMidRunIsHonoured() async throws {
114+
let source = WorkSource(Array(1 ... 200))
115+
let peak = ThreadSafeCounter()
116+
let current = ThreadSafeCounter()
117+
118+
let queue = WorkQueue<Int, Int>(
119+
maxConcurrency: 1,
120+
fetchWork: { source.next() },
121+
processWork: { work in
122+
current.increment()
123+
peak.recordMaximum(current.value)
124+
125+
try? await Task.sleep(for: .milliseconds(2))
126+
current.decrement()
127+
return work
128+
},
129+
onResult: { _, _ in },
130+
)
131+
132+
let task = Task { try await queue.start() }
133+
134+
// Let the queue start with a single worker, then raise the limit.
135+
try await Task.sleep(for: .milliseconds(50))
136+
await queue.setMaxConcurrency(8)
137+
try await task.value
138+
139+
#expect(peak.value > 1, "raising maxConcurrency mid-run had no effect")
140+
#expect(source.remaining == 0)
103141
}
104142

105143
/// Errors from process work propagate.
@@ -287,4 +325,17 @@ final class ThreadSafeCounter: @unchecked Sendable {
287325
lock.unlock()
288326
}
289327

328+
func decrement() {
329+
lock.lock()
330+
_value -= 1
331+
lock.unlock()
332+
}
333+
334+
/// Sets the value only when it is greater than the current one.
335+
func recordMaximum(_ candidate: Int) {
336+
lock.lock()
337+
_value = max(_value, candidate)
338+
lock.unlock()
339+
}
340+
290341
}

0 commit comments

Comments
 (0)