-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathHoldingQueue.swift
250 lines (225 loc) · 8.51 KB
/
HoldingQueue.swift
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//
// HoldingQueue.swift
// background_downloader
//
// Created by Bram on 3/16/24.
//
import Foundation
import os.log
/**
* Queue that holds [EnqueueItem] items before they are actually enqueued as a URLSessionTask
*
* Configure [maxConcurrent], [maxConcurrentByHost] and [maxConcurrentByGroup] to limit which items
* can be enqueued simultaneously.
*
* Call:
* [add] to add an [EnqueueItem]
* [taskFinished] for all tasks that finish, so we may start a new one
* [cancelAllTasks] to empty the queue (sends status updates)
* [cancelTasksWithIds] to remove specific tasks (sends status updates)
* [allTasks] for a list of [Task] matching a group
* [taskForId] to get the task for a specific taskId
*/
class HoldingQueue {
var maxConcurrent: Int = 1000000
var maxConcurrentByHost: Int = 1000000
var maxConcurrentByGroup: Int = 1000000
var enqueuedTaskIds = [String]()
private var concurrent = 0
private var concurrentByHost = [String: Int]()
private var concurrentByGroup = [String: Int]()
private var queue = [EnqueueItem]() // Using an array as a substitute for a priority queue
let stateLock = AsyncLock()
private var job: DispatchWorkItem? = nil // for advanceQueue in future
/**
* Add [EnqueueItem] [item] to the queue and advance the queue if possible
*/
func add(item: EnqueueItem) async {
await stateLock.lock()
queue.append(item)
queue.sort()
enqueuedTaskIds.append(item.task.taskId)
advanceQueue()
await stateLock.unlock()
}
/**
* Signals to the holdingQueue that a [task] has finished
*
* Adjusts the state variables and advances the queue
*/
func taskFinished(_ task: Task) async {
await stateLock.lock()
let host = getHost(task)
concurrent -= 1
concurrentByHost[host]? -= 1
concurrentByGroup[task.group]? -= 1
if let index = enqueuedTaskIds.firstIndex(of: task.taskId) {
enqueuedTaskIds.remove(at: index)
}
advanceQueue()
await stateLock.unlock()
}
/**
* Removes all [EnqueueItem] where their taskId is in [taskIds], sends a
* [TaskStatus.canceled] update and returns a list of
* taskIds that were cancelled this way.
*
* Because this is used in combination with the UrlSessions tasks, use of this method
* requires the caller to acquire the [stateLock]
*/
func cancelTasksWithIds(_ taskIds: [String]) -> [String] {
let toRemove = queue.filter( { taskIds.contains($0.task.taskId) } )
toRemove.forEach { item in
processStatusUpdate(task: item.task, status: .canceled)
os_log("Canceled task with id %@", log: log, type: .info, item.task.taskId)
}
queue.removeAll(where: { taskIds.contains($0.task.taskId)})
return toRemove.map { $0.task.taskId }
}
/**
* Cancel (delete) all [EnqueueItem] matching [group], send a
* [TaskStatus.canceled] for each and return the number of items cancelled
*
* Because this is used in combination with the UrlSessions tasks, use of this method
* requires the caller to acquire the [stateLock]
*/
func cancelAllTasks(group: String) -> Int {
let taskIds = queue.filter({ $0.task.group == group }).map { $0.task.taskId }
return cancelTasksWithIds(taskIds).count
}
/**
* Return task matching [taskId], or null
*
* Because this is used in combination with the UrlSessions tasks, use of this method
* requires the caller to acquire the [stateLock]
*/
func taskForId(_ taskId: String) -> Task? {
let tasks = queue.filter( { $0.task.taskId == taskId } ).map { $0.task }
if !tasks.isEmpty {
return tasks.first
}
return nil
}
/**
* Return list of [Task] for this [group]
*
* Because this is used in combination with the UrlSessions tasks, use of this method
* requires the caller to acquire the [stateLock]
*/
func allTasks(group: String) -> [Task] {
return queue.filter( { $0.task.group == group } ).map { $0.task }
}
/**
* Advance the queue by signalling the queue processing coroutine
*
* Also restarts a timer that will advance the queue in 10 seconds, in case
* it dries up
*/
private func advanceQueue() {
DispatchQueue.global().async {
_Concurrency.Task {
await self.processQueue()
}
}
advanceQueueInFuture()
}
private func advanceQueueInFuture() {
job?.cancel()
job = DispatchWorkItem {
_Concurrency.Task {
await self.calculateState()
self.advanceQueue()
}
}
guard let job = job else { return }
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10, execute: job)
}
/// Processes one item in the queue, if possible
private func processQueue() async {
await stateLock.lock()
if concurrent < maxConcurrent {
var mustWait = [EnqueueItem]()
while !queue.isEmpty {
let item = queue.removeFirst()
let host = getHost(item.task)
if concurrentByHost[host] ?? 0 < maxConcurrentByHost &&
concurrentByGroup[item.task.group] ?? 0 < maxConcurrentByGroup {
concurrent += 1
concurrentByHost[host, default: 0] += 1
concurrentByGroup[item.task.group, default: 0] += 1
await item.enqueue()
break
} else {
mustWait.append(item)
}
}
queue.append(contentsOf: mustWait)
queue.sort()
}
await stateLock.unlock()
}
/**
* Calculates the [concurrent], [concurrentByHost] and [concurrentByGroup] values
*
* This is expensive, so is only done initially and when the [advanceQueueInFuture] timer
* fires
*/
private func calculateState() async {
await stateLock.lock()
UrlSessionDelegate.createUrlSession()
guard let urlSessionTasks = await UrlSessionDelegate.urlSession?.allTasks else {
await stateLock.unlock()
return
}
let tasks: [Task] = urlSessionTasks.filter({ $0.state != .completed }).map({ getTaskFrom(urlSessionTask: $0)}).filter({ $0 != nil}).map({ $0!})
concurrent = tasks.count
concurrentByHost.removeAll()
concurrentByGroup.removeAll()
for task in tasks {
let host = getHost(task)
concurrentByHost[host, default: 0] += 1
concurrentByGroup[task.group, default: 0] += 1
}
await stateLock.unlock()
}
}
/**
* Holds data related to enqueueing a task
*
* Used in the context of changing the RequireWiFi setting (where tasks need to be re-enqueued)
* and in the context of the [HoldingQueue]
*/
struct EnqueueItem : Comparable {
let task: Task
let notificationConfigJsonString: String?
let resumeDataAsBase64String: String
let created = Date()
// Comparable implementation to sort based on task priority and creation time
static func < (lhs: EnqueueItem, rhs: EnqueueItem) -> Bool {
return lhs.task.priority == rhs.task.priority ? lhs.task.creationTime < rhs.task.creationTime : lhs.task.priority < rhs.task.priority
}
static func == (lhs: EnqueueItem, rhs: EnqueueItem) -> Bool {
return lhs.task.priority == rhs.task.priority && lhs.task.creationTime == rhs.task.creationTime
}
func enqueue() async {
let success = await BDPlugin.instance.doEnqueue(taskJsonString: jsonStringFor(task: task) ?? "", notificationConfigJsonString: notificationConfigJsonString, resumeDataAsBase64String: resumeDataAsBase64String)
if !success {
os_log("Delayed or retried enqueue failed for taskId %@", log: log, type: .info, task.taskId)
processStatusUpdate(task: task, status: .failed, taskException: TaskException(type: .general, description: "Delayed or retried enqueue failed"))
await BDPlugin.holdingQueue?.taskFinished(task)
}
}
}
/// Traditional lock for asyn/await environment
actor AsyncLock {
private var isLocked = false
func lock() async {
while isLocked {
await _Concurrency.Task.yield()
}
isLocked = true
}
func unlock() async {
isLocked = false
}
}