Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions Sources/Mapnik/WorkQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,22 +43,51 @@ public actor WorkQueue<Work: Sendable, Result: Sendable> {
private let processWork: @Sendable (Work) async throws -> Result?
private let onResult: @Sendable (Work, Result?) async throws -> Void

/// The range ``maxConcurrency`` is clamped to.
///
/// Values outside this range are clamped rather than rejected, so callers
/// that need to validate their own input can check against it first.
public static var concurrencyRange: ClosedRange<Int> {
1 ... 256
}

private var _maxConcurrency: Int
private var inFlight = 0

/// The maximum number of concurrently processed work items (1...256).
/// The maximum number of concurrently processed work items.
///
/// The value is clamped to ``concurrencyRange``: assigning `1000` stores
/// `256`, assigning `0` stores `1`. Check against ``concurrencyRange``
/// before assigning if the exact value matters.
///
/// Changing this while ``start()`` is running is supported. The queue
/// re-reads it each time it refills, so a raised limit takes effect as
/// soon as an in-flight item finishes. Lowering it does not interrupt
/// running `processWork` calls, so the number of concurrent items can
/// briefly exceed the new limit until they complete.
public var maxConcurrency: Int {
get { _maxConcurrency }
set { _maxConcurrency = max(1, min(256, newValue)) }
set { _maxConcurrency = Self.clamp(newValue) }
}

/// Clamps `value` into ``concurrencyRange``.
private static func clamp(_ value: Int) -> Int {
min(max(value, concurrencyRange.lowerBound), concurrencyRange.upperBound)
}

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

/// - Parameters:
/// - maxConcurrency: Upper bound for parallel `processWork` calls.
/// - maxConcurrency: Upper bound for parallel `processWork` calls,
/// clamped to ``concurrencyRange``.
/// - fetchWork: Produces the next work item, or `nil` when the queue
/// should drain and finish. Called on the actor.
/// - processWork: Transforms a work item into a result. Runs detached
Expand All @@ -72,7 +101,7 @@ public actor WorkQueue<Work: Sendable, Result: Sendable> {
processWork: @escaping @Sendable (Work) async throws -> Result?,
onResult: @escaping @Sendable (Work, Result?) async throws -> Void,
) {
self._maxConcurrency = max(1, min(256, maxConcurrency))
self._maxConcurrency = Self.clamp(maxConcurrency)
self.fetchWork = fetchWork
self.processWork = processWork
self.onResult = onResult
Expand Down
57 changes: 54 additions & 3 deletions Tests/MapnikTests/WorkQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ struct WorkQueueTests {
#expect(processed.value == 30)
}

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

#expect(await queue.maxConcurrency == 256)
#expect(await queue.maxConcurrency == WorkQueue<Int, Int>.concurrencyRange.upperBound)

// setMaxConcurrency is the only way to change it from outside the
// actor, and it clamps like the property setter.
await queue.setMaxConcurrency(0)
#expect(await queue.maxConcurrency == 1)
#expect(await queue.maxConcurrency == WorkQueue<Int, Int>.concurrencyRange.lowerBound)

await queue.setMaxConcurrency(8)
#expect(await queue.maxConcurrency == 8)
}

/// Raising the limit mid-run takes effect without interrupting work.
@Test
func raisingMaxConcurrencyMidRunIsHonoured() async throws {
let source = WorkSource(Array(1 ... 200))
let peak = ThreadSafeCounter()
let current = ThreadSafeCounter()

let queue = WorkQueue<Int, Int>(
maxConcurrency: 1,
fetchWork: { source.next() },
processWork: { work in
current.increment()
peak.recordMaximum(current.value)

try? await Task.sleep(for: .milliseconds(2))
current.decrement()
return work
},
onResult: { _, _ in },
)

let task = Task { try await queue.start() }

// Let the queue start with a single worker, then raise the limit.
try await Task.sleep(for: .milliseconds(50))
await queue.setMaxConcurrency(8)
try await task.value

#expect(peak.value > 1, "raising maxConcurrency mid-run had no effect")
#expect(source.remaining == 0)
}

/// Errors from process work propagate.
Expand Down Expand Up @@ -287,4 +325,17 @@ final class ThreadSafeCounter: @unchecked Sendable {
lock.unlock()
}

func decrement() {
lock.lock()
_value -= 1
lock.unlock()
}

/// Sets the value only when it is greater than the current one.
func recordMaximum(_ candidate: Int) {
lock.lock()
_value = max(_value, candidate)
lock.unlock()
}

}
Loading