-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathSTNetTaskQueue.m
More file actions
312 lines (251 loc) · 7.94 KB
/
STNetTaskQueue.m
File metadata and controls
312 lines (251 loc) · 7.94 KB
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//
// STNetTaskQueue.m
// STNetTaskQueue
//
// Created by Kevin Lin on 29/11/14.
// Copyright (c) 2014 Sth4Me. All rights reserved.
//
#import "STNetTaskQueue.h"
#import "STNetTaskQueueLog.h"
@interface STNetTask (STInternal)
@property (atomic, assign) BOOL pending;
@property (atomic, assign) BOOL cancelled;
@property (atomic, assign) BOOL finished;
@property (atomic, assign) NSUInteger retryCount;
- (void)notifyState:(STNetTaskState)state;
@end
@interface STNetTaskQueue()
@property (nonatomic, strong) NSThread *thread;
@property (nonatomic, strong) NSRecursiveLock *lock;
@property (nonatomic, strong) NSMutableDictionary *taskDelegates; // <NSString, NSHashTable<STNetTaskDelegate>>
@property (nonatomic, strong) NSMutableArray *tasks; // <STNetTask>
@property (nonatomic, strong) NSMutableArray *waitingTasks; // <STNetTask>
@end
@implementation STNetTaskQueue
+ (instancetype)sharedQueue
{
static STNetTaskQueue *sharedQueue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedQueue = [self new];
});
return sharedQueue;
}
- (id)init
{
if (self = [super init]) {
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadEntryPoint) object:nil];
self.thread.name = NSStringFromClass(self.class);
[self.thread start];
self.lock = [NSRecursiveLock new];
self.lock.name = [NSString stringWithFormat:@"%@Lock", NSStringFromClass(self.class)];
self.taskDelegates = [NSMutableDictionary new];
self.tasks = [NSMutableArray new];
self.waitingTasks = [NSMutableArray new];
}
return self;
}
- (void)dealloc
{
[self.handler netTaskQueueDidBecomeInactive:self];
}
- (void)threadEntryPoint
{
@autoreleasepool {
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
[runloop addPort:[NSPort port] forMode:NSDefaultRunLoopMode]; // Just for keeping the runloop
[runloop run];
}
}
- (void)performInThread:(NSThread *)thread usingBlock:(void(^)())block
{
[self performSelector:@selector(performUsingBlock:) onThread:thread withObject:block waitUntilDone:NO];
}
- (void)performUsingBlock:(void(^)())block
{
block();
}
- (void)addTask:(STNetTask *)task
{
NSAssert(self.handler, @"STNetTaskQueueHandler is not set.");
NSAssert(!task.finished && !task.cancelled, @"STNetTask is finished/cancelled, please recreate a net task.");
task.pending = YES;
[self performInThread:self.thread usingBlock:^{
[self _addTask:task];
}];
}
- (void)_addTask:(STNetTask *)task
{
if (self.maxConcurrentTasksCount > 0 && self.tasks.count >= self.maxConcurrentTasksCount) {
[self.waitingTasks addObject:task];
return;
}
[self.tasks addObject:task];
[self.handler netTaskQueue:self handleTask:task];
}
- (void)cancelTask:(STNetTask *)task
{
if (!task) {
return;
}
[self performInThread:self.thread usingBlock:^{
[self _cancelTask:task];
}];
}
- (void)_cancelTask:(STNetTask *)task
{
[self.tasks removeObject:task];
[self.waitingTasks removeObject:task];
task.pending = NO;
[self.handler netTaskQueue:self didCancelTask:task];
task.cancelled = YES;
[task notifyState:STNetTaskStateCancalled];
}
- (BOOL)_retryTask:(STNetTask *)task withError:(NSError *)error
{
if ([task shouldRetryForError:error] && task.retryCount < task.maxRetryCount) {
task.retryCount++;
[self performSelector:@selector(_retryTask:) withObject:task afterDelay:task.retryInterval];
return YES;
}
return NO;
}
- (void)_retryTask:(STNetTask *)task
{
if (!task.cancelled) {
[task didRetry];
[task notifyState:STNetTaskStateRetrying];
[self addTask:task];
}
}
- (void)_sendwaitingTasks
{
if (!self.waitingTasks.count) {
return;
}
STNetTask *task = self.waitingTasks.firstObject;
[self.waitingTasks removeObjectAtIndex:0];
[self addTask:task];
}
- (void)task:(STNetTask *)task didResponse:(id)response
{
[self performInThread:self.thread usingBlock:^{
[self _task:task didResponse:response];
}];
}
- (void)_task:(STNetTask *)task didResponse:(id)response
{
if (![self.tasks containsObject:task]) {
return;
}
[self.tasks removeObject:task];
@try {
[task didResponse:response];
}
@catch (NSException *exception) {
[STNetTaskQueueLog log:@"Exception in 'didResponse' - %@", exception.debugDescription];
NSError *error = [NSError errorWithDomain:STNetTaskUnknownError
code:-1
userInfo:@{ @"msg": exception.description ? : @"nil" }];
if ([self _retryTask:task withError:error]) {
return;
}
task.error = error;
[task didFail];
}
task.pending = NO;
task.finished = YES;
[task notifyState:STNetTaskStateFinished];
[self _netTaskDidEnd:task];
[self _sendwaitingTasks];
}
- (void)task:(STNetTask *)task didFailWithError:(NSError *)error
{
[self performInThread:self.thread usingBlock:^{
[self _task:task didFailWithError:error];
}];
}
- (void)_task:(STNetTask *)task didFailWithError:(NSError *)error
{
if (![self.tasks containsObject:task]) {
return;
}
[self.tasks removeObject:task];
[STNetTaskQueueLog log:error.debugDescription];
if ([self _retryTask:task withError:error]) {
return;
}
task.error = error;
[task didFail];
task.pending = NO;
task.finished = YES;
[task notifyState:STNetTaskStateFinished];
[self _netTaskDidEnd:task];
[self _sendwaitingTasks];
}
- (void)_netTaskDidEnd:(STNetTask *)task
{
[self.lock lock];
NSHashTable *delegatesForURI = self.taskDelegates[task.uri];
NSHashTable *delegatesForClass = self.taskDelegates[NSStringFromClass(task.class)];
NSMutableSet *set = [NSMutableSet new];
[set addObjectsFromArray:delegatesForURI.allObjects];
[set addObjectsFromArray:delegatesForClass.allObjects];
NSArray *delegates = set.allObjects;
[self.lock unlock];
if (delegates.count) {
dispatch_async(dispatch_get_main_queue(), ^ {
for (id<STNetTaskDelegate> delegate in delegates) {
[delegate netTaskDidEnd:task];
}
});
}
}
- (void)addTaskDelegate:(id<STNetTaskDelegate>)delegate uri:(NSString *)uri
{
[self.lock lock];
NSHashTable *delegates = self.taskDelegates[uri];
if (!delegates) {
delegates = [NSHashTable weakObjectsHashTable];
self.taskDelegates[uri] = delegates;
}
[delegates addObject:delegate];
[self.lock unlock];
}
- (void)addTaskDelegate:(id<STNetTaskDelegate>)delegate class:(Class)clazz
{
NSString *className = NSStringFromClass(clazz);
NSAssert([clazz isSubclassOfClass:[STNetTask class]], @"%@ should be a subclass of STNetTask", className);
[self.lock lock];
NSHashTable *delegates = self.taskDelegates[className];
if (!delegates) {
delegates = [NSHashTable weakObjectsHashTable];
self.taskDelegates[className] = delegates;
}
[delegates addObject:delegate];
[self.lock unlock];
}
- (void)removeTaskDelegate:(id<STNetTaskDelegate>)delegate
{
[self.lock lock];
for (NSString *key in self.taskDelegates) {
[self removeTaskDelegate:delegate key:key];
}
[self.lock unlock];
}
- (void)removeTaskDelegate:(id<STNetTaskDelegate>)delegate uri:(NSString *)uri
{
[self removeTaskDelegate:delegate key:uri];
}
- (void)removeTaskDelegate:(id<STNetTaskDelegate>)delegate class:(Class)clazz
{
[self removeTaskDelegate:delegate key:NSStringFromClass(clazz)];
}
- (void)removeTaskDelegate:(id<STNetTaskDelegate>)delegate key:(NSString *)key
{
[self.lock lock];
NSHashTable *delegates = self.taskDelegates[key];
[delegates removeObject:delegate];
[self.lock unlock];
}
@end