-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathGTMSessionFetcherService.m
1381 lines (1138 loc) · 46.2 KB
/
GTMSessionFetcherService.m
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
#import "GTMSessionFetcherService.h"
NSString *const kGTMSessionFetcherServiceSessionBecameInvalidNotification
= @"kGTMSessionFetcherServiceSessionBecameInvalidNotification";
NSString *const kGTMSessionFetcherServiceSessionKey
= @"kGTMSessionFetcherServiceSessionKey";
#if !GTMSESSION_BUILD_COMBINED_SOURCES
@interface GTMSessionFetcher (ServiceMethods)
- (BOOL)beginFetchMayDelay:(BOOL)mayDelay
mayAuthorize:(BOOL)mayAuthorize;
@end
#endif // !GTMSESSION_BUILD_COMBINED_SOURCES
@interface GTMSessionFetcherService ()
@property(atomic, strong, readwrite) NSDictionary *delayedFetchersByHost;
@property(atomic, strong, readwrite) NSDictionary *runningFetchersByHost;
@end
// Since NSURLSession doesn't support a separate delegate per task (!), instances of this
// class serve as a session delegate trampoline.
//
// This class maps a session's tasks to fetchers, and resends delegate messages to the task's
// fetcher.
@interface GTMSessionFetcherSessionDelegateDispatcher : NSObject<NSURLSessionDelegate>
// The session for the tasks in this dispatcher's task-to-fetcher map.
@property(atomic) NSURLSession *session;
// The timer interval for invalidating a session that has no active tasks.
@property(atomic) NSTimeInterval discardInterval;
// The current discard timer.
@property(atomic, readonly) NSTimer *discardTimer;
- (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService
sessionDiscardInterval:(NSTimeInterval)discardInterval;
- (void)setFetcher:(GTMSessionFetcher *)fetcher
forTask:(NSURLSessionTask *)task;
- (void)removeFetcher:(GTMSessionFetcher *)fetcher;
// Before using a session, tells the delegate dispatcher to stop the discard timer.
- (void)startSessionUsage;
// When abandoning a delegate dispatcher, we want to avoid the session retaining
// the delegate after tasks complete.
- (void)abandon;
@end
@implementation GTMSessionFetcherService {
NSMutableDictionary *_delayedFetchersByHost;
NSMutableDictionary *_runningFetchersByHost;
NSUInteger _maxRunningFetchersPerHost;
// When this ivar is nil, the service will not reuse sessions.
GTMSessionFetcherSessionDelegateDispatcher *_delegateDispatcher;
// Fetchers will wait on this if another fetcher is creating the shared NSURLSession.
dispatch_semaphore_t _sessionCreationSemaphore;
dispatch_queue_t _callbackQueue;
NSOperationQueue *_delegateQueue;
NSHTTPCookieStorage *_cookieStorage;
NSString *_userAgent;
NSTimeInterval _timeout;
NSURLCredential *_credential; // Username & password.
NSURLCredential *_proxyCredential; // Credential supplied to proxy servers.
NSInteger _cookieStorageMethod;
id<GTMFetcherAuthorizationProtocol> _authorizer;
// For waitForCompletionOfAllFetchersWithTimeout: we need to wait on stopped fetchers since
// they've not yet finished invoking their queued callbacks. This array is nil except when
// waiting on fetchers.
NSMutableArray *_stoppedFetchersToWaitFor;
// For fetchers that enqueued their callbacks before stopAllFetchers was called on the service,
// set a barrier so the callbacks know to bail out.
NSDate *_stoppedAllFetchersDate;
}
@synthesize maxRunningFetchersPerHost = _maxRunningFetchersPerHost,
configuration = _configuration,
configurationBlock = _configurationBlock,
cookieStorage = _cookieStorage,
userAgent = _userAgent,
challengeBlock = _challengeBlock,
credential = _credential,
proxyCredential = _proxyCredential,
allowedInsecureSchemes = _allowedInsecureSchemes,
allowLocalhostRequest = _allowLocalhostRequest,
allowInvalidServerCertificates = _allowInvalidServerCertificates,
retryEnabled = _retryEnabled,
retryBlock = _retryBlock,
maxRetryInterval = _maxRetryInterval,
minRetryInterval = _minRetryInterval,
metricsCollectionBlock = _metricsCollectionBlock,
properties = _properties,
unusedSessionTimeout = _unusedSessionTimeout,
testBlock = _testBlock;
#if GTM_BACKGROUND_TASK_FETCHING
@synthesize skipBackgroundTask = _skipBackgroundTask;
#endif
- (instancetype)init {
self = [super init];
if (self) {
_delayedFetchersByHost = [[NSMutableDictionary alloc] init];
_runningFetchersByHost = [[NSMutableDictionary alloc] init];
_maxRunningFetchersPerHost = 10;
_cookieStorageMethod = -1;
_unusedSessionTimeout = 60.0;
_delegateDispatcher =
[[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self
sessionDiscardInterval:_unusedSessionTimeout];
_callbackQueue = dispatch_get_main_queue();
_delegateQueue = [[NSOperationQueue alloc] init];
_delegateQueue.maxConcurrentOperationCount = 1;
_delegateQueue.name = @"com.google.GTMSessionFetcher.NSURLSessionDelegateQueue";
_sessionCreationSemaphore = dispatch_semaphore_create(1);
// Starting with the SDKs for OS X 10.11/iOS 9, the service has a default useragent.
// Apps can remove this and get the default system "CFNetwork" useragent by setting the
// fetcher service's userAgent property to nil.
#if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \
|| (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0)
_userAgent = GTMFetcherStandardUserAgentString(nil);
#endif
}
return self;
}
- (void)dealloc {
[self detachAuthorizer];
[_delegateDispatcher abandon];
}
#pragma mark Generate a new fetcher
// Clients may override this method. Clients should not override any other library methods.
- (id)fetcherWithRequest:(NSURLRequest *)request
fetcherClass:(Class)fetcherClass {
GTMSessionFetcher *fetcher = [[fetcherClass alloc] initWithRequest:request
configuration:self.configuration];
fetcher.callbackQueue = self.callbackQueue;
fetcher.sessionDelegateQueue = self.sessionDelegateQueue;
fetcher.challengeBlock = self.challengeBlock;
fetcher.credential = self.credential;
fetcher.proxyCredential = self.proxyCredential;
fetcher.authorizer = self.authorizer;
fetcher.cookieStorage = self.cookieStorage;
fetcher.allowedInsecureSchemes = self.allowedInsecureSchemes;
fetcher.allowLocalhostRequest = self.allowLocalhostRequest;
fetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates;
fetcher.configurationBlock = self.configurationBlock;
fetcher.retryEnabled = self.retryEnabled;
fetcher.retryBlock = self.retryBlock;
fetcher.maxRetryInterval = self.maxRetryInterval;
fetcher.minRetryInterval = self.minRetryInterval;
if (@available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *)) {
fetcher.metricsCollectionBlock = self.metricsCollectionBlock;
}
fetcher.properties = self.properties;
fetcher.service = self;
if (self.cookieStorageMethod >= 0) {
[fetcher setCookieStorageMethod:self.cookieStorageMethod];
}
#if GTM_BACKGROUND_TASK_FETCHING
fetcher.skipBackgroundTask = self.skipBackgroundTask;
#endif
NSString *userAgent = self.userAgent;
if (userAgent.length > 0
&& [request valueForHTTPHeaderField:@"User-Agent"] == nil) {
[fetcher setRequestValue:userAgent
forHTTPHeaderField:@"User-Agent"];
}
fetcher.testBlock = self.testBlock;
return fetcher;
}
- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request {
return [self fetcherWithRequest:request
fetcherClass:[GTMSessionFetcher class]];
}
- (GTMSessionFetcher *)fetcherWithURL:(NSURL *)requestURL {
return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]];
}
- (GTMSessionFetcher *)fetcherWithURLString:(NSString *)requestURLString {
NSURL *url = [NSURL URLWithString:requestURLString];
return [self fetcherWithURL:url];
}
// Returns a session for the fetcher's host, or nil.
- (NSURLSession *)session {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
NSURLSession *session = _delegateDispatcher.session;
return session;
}
}
// Returns a session for the fetcher's host, or nil. For shared sessions, this
// waits on a semaphore, blocking other fetchers while the caller creates the
// session if needed.
- (NSURLSession *)sessionForFetcherCreation {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
if (!_delegateDispatcher) {
// This fetcher is creating a non-shared session, so skip the semaphore usage.
return nil;
}
}
// Wait if another fetcher is currently creating a session; avoid waiting
// inside the @synchronized block, as that can deadlock.
dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER);
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
// Before getting the NSURLSession for task creation, it is
// important to invalidate and nil out the session discard timer; otherwise
// the session can be invalidated between when it is returned to the
// fetcher, and when the fetcher attempts to create its NSURLSessionTask.
[_delegateDispatcher startSessionUsage];
NSURLSession *session = _delegateDispatcher.session;
if (session) {
// The calling fetcher will receive a preexisting session, so
// we can allow other fetchers to create a session.
dispatch_semaphore_signal(_sessionCreationSemaphore);
} else {
// No existing session was obtained, so the calling fetcher will create the session;
// it *must* invoke fetcherDidCreateSession: to signal the dispatcher's semaphore after
// the session has been created (or fails to be created) to avoid a hang.
}
return session;
}
}
- (id<NSURLSessionDelegate>)sessionDelegate {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _delegateDispatcher;
}
}
#pragma mark Queue Management
- (void)addRunningFetcher:(GTMSessionFetcher *)fetcher
forHost:(NSString *)host {
// Add to the array of running fetchers for this host, creating the array if needed.
NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host];
if (runningForHost == nil) {
runningForHost = [NSMutableArray arrayWithObject:fetcher];
[_runningFetchersByHost setObject:runningForHost forKey:host];
} else {
[runningForHost addObject:fetcher];
}
}
- (void)addDelayedFetcher:(GTMSessionFetcher *)fetcher
forHost:(NSString *)host {
// Add to the array of delayed fetchers for this host, creating the array if needed.
NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host];
if (delayedForHost == nil) {
delayedForHost = [NSMutableArray arrayWithObject:fetcher];
[_delayedFetchersByHost setObject:delayedForHost forKey:host];
} else {
[delayedForHost addObject:fetcher];
}
}
- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
NSString *host = fetcher.request.URL.host;
if (host == nil) {
return NO;
}
NSArray *delayedForHost = [_delayedFetchersByHost objectForKey:host];
NSUInteger idx = [delayedForHost indexOfObjectIdenticalTo:fetcher];
BOOL isDelayed = (delayedForHost != nil) && (idx != NSNotFound);
return isDelayed;
}
}
- (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher {
// Entry point from the fetcher
NSURL *requestURL = fetcher.request.URL;
NSString *host = requestURL.host;
// Addresses "file:///path" case where localhost is the implicit host.
if (host.length == 0 && [requestURL isFileURL]) {
host = @"localhost";
}
if (host.length == 0) {
// Data URIs legitimately have no host, reject other hostless URLs.
GTMSESSION_ASSERT_DEBUG([[requestURL scheme] isEqual:@"data"], @"%@ lacks host", fetcher);
return YES;
}
BOOL shouldBeginResult;
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host];
if (runningForHost != nil
&& [runningForHost indexOfObjectIdenticalTo:fetcher] != NSNotFound) {
GTMSESSION_ASSERT_DEBUG(NO, @"%@ was already running", fetcher);
return YES;
}
BOOL shouldRunNow = (fetcher.usingBackgroundSession
|| _maxRunningFetchersPerHost == 0
|| _maxRunningFetchersPerHost >
[[self class] numberOfNonBackgroundSessionFetchers:runningForHost]);
if (shouldRunNow) {
[self addRunningFetcher:fetcher forHost:host];
shouldBeginResult = YES;
} else {
[self addDelayedFetcher:fetcher forHost:host];
shouldBeginResult = NO;
}
} // @synchronized(self)
// We'll save the host that serves as the key for this fetcher's array
// to avoid any chance of the underlying request changing, stranding
// the fetcher in the wrong array
fetcher.serviceHost = host;
return shouldBeginResult;
}
- (void)startFetcher:(GTMSessionFetcher *)fetcher {
[fetcher beginFetchMayDelay:NO
mayAuthorize:YES];
}
// Internal utility. Returns a fetcher's delegate if it's a dispatcher, or nil if the fetcher
// is its own delegate (possibly via proxy) and has no dispatcher.
- (GTMSessionFetcherSessionDelegateDispatcher *)delegateDispatcherForFetcher:(GTMSessionFetcher *)fetcher {
GTMSessionCheckNotSynchronized(self);
NSURLSession *fetcherSession = fetcher.session;
if (fetcherSession) {
id<NSURLSessionDelegate> fetcherDelegate = fetcherSession.delegate;
// If the delegate is non-nil and claims to be a GTMSessionFetcher, there is no dispatcher;
// assume the fetcher is the delegate or has been proxied (some third-party frameworks
// are known to swizzle NSURLSession to proxy its delegate).
BOOL hasDispatcher = (fetcherDelegate != nil &&
![fetcherDelegate isKindOfClass:[GTMSessionFetcher class]]);
if (hasDispatcher) {
GTMSESSION_ASSERT_DEBUG([fetcherDelegate isKindOfClass:[GTMSessionFetcherSessionDelegateDispatcher class]],
@"Fetcher delegate class: %@", [fetcherDelegate class]);
return (GTMSessionFetcherSessionDelegateDispatcher *)fetcherDelegate;
}
}
return nil;
}
- (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher {
if (fetcher.canShareSession) {
NSURLSession *fetcherSession = fetcher.session;
GTMSESSION_ASSERT_DEBUG(fetcherSession != nil, @"Fetcher missing its session: %@", fetcher);
GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher =
[self delegateDispatcherForFetcher:fetcher];
if (delegateDispatcher) {
GTMSESSION_ASSERT_DEBUG(delegateDispatcher.session == nil,
@"Fetcher made an extra session: %@", fetcher);
// Save this fetcher's session.
delegateDispatcher.session = fetcherSession;
// Allow other fetchers to request this session now.
dispatch_semaphore_signal(_sessionCreationSemaphore);
}
}
}
- (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher {
// If this fetcher has a separate delegate with a shared session, then
// this fetcher should be added to the delegate's map of tasks to fetchers.
GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher =
[self delegateDispatcherForFetcher:fetcher];
if (delegateDispatcher) {
GTMSESSION_ASSERT_DEBUG(fetcher.canShareSession,
@"Inappropriate shared session: %@", fetcher);
// There should already be a session, from this or a previous fetcher.
//
// Sanity check that the fetcher's session is the delegate's shared session.
NSURLSession *sharedSession = delegateDispatcher.session;
NSURLSession *fetcherSession = fetcher.session;
GTMSESSION_ASSERT_DEBUG(sharedSession != nil, @"Missing delegate session: %@", fetcher);
GTMSESSION_ASSERT_DEBUG(fetcherSession == sharedSession,
@"Inconsistent session: %@ %@ (shared: %@)",
fetcher, fetcherSession, sharedSession);
if (sharedSession != nil && fetcherSession == sharedSession) {
NSURLSessionTask *task = fetcher.sessionTask;
GTMSESSION_ASSERT_DEBUG(task != nil, @"Missing session task: %@", fetcher);
if (task) {
[delegateDispatcher setFetcher:fetcher
forTask:task];
}
}
}
}
- (void)stopFetcher:(GTMSessionFetcher *)fetcher {
[fetcher stopFetching];
}
- (void)fetcherDidStop:(GTMSessionFetcher *)fetcher {
// Entry point from the fetcher
NSString *host = fetcher.serviceHost;
if (!host) {
// fetcher has been stopped previously
return;
}
// This removeFetcher: invocation is a fallback; typically, fetchers are removed from the task
// map when the task completes.
GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher =
[self delegateDispatcherForFetcher:fetcher];
[delegateDispatcher removeFetcher:fetcher];
NSMutableArray *fetchersToStart;
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
// If a test is waiting for all fetchers to stop, it needs to wait for this one
// to invoke its callbacks on the callback queue.
[_stoppedFetchersToWaitFor addObject:fetcher];
NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host];
[runningForHost removeObject:fetcher];
NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host];
[delayedForHost removeObject:fetcher];
while (delayedForHost.count > 0
&& [[self class] numberOfNonBackgroundSessionFetchers:runningForHost]
< _maxRunningFetchersPerHost) {
// Start another delayed fetcher running, scanning for the minimum
// priority value, defaulting to FIFO for equal priorities
GTMSessionFetcher *nextFetcher = nil;
for (GTMSessionFetcher *delayedFetcher in delayedForHost) {
if (nextFetcher == nil
|| delayedFetcher.servicePriority < nextFetcher.servicePriority) {
nextFetcher = delayedFetcher;
}
}
if (nextFetcher) {
[self addRunningFetcher:nextFetcher forHost:host];
runningForHost = [_runningFetchersByHost objectForKey:host];
[delayedForHost removeObjectIdenticalTo:nextFetcher];
if (!fetchersToStart) {
fetchersToStart = [NSMutableArray array];
}
[fetchersToStart addObject:nextFetcher];
}
}
if (runningForHost.count == 0) {
// None left; remove the empty array
[_runningFetchersByHost removeObjectForKey:host];
}
if (delayedForHost.count == 0) {
[_delayedFetchersByHost removeObjectForKey:host];
}
} // @synchronized(self)
// Start fetchers outside of the synchronized block to avoid a deadlock.
for (GTMSessionFetcher *nextFetcher in fetchersToStart) {
[self startFetcher:nextFetcher];
}
// The fetcher is no longer in the running or the delayed array,
// so remove its host and thread properties
fetcher.serviceHost = nil;
}
- (NSUInteger)numberOfFetchers {
NSUInteger running = [self numberOfRunningFetchers];
NSUInteger delayed = [self numberOfDelayedFetchers];
return running + delayed;
}
- (NSUInteger)numberOfRunningFetchers {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
NSUInteger sum = 0;
for (NSString *host in _runningFetchersByHost) {
NSArray *fetchers = [_runningFetchersByHost objectForKey:host];
sum += fetchers.count;
}
return sum;
}
}
- (NSUInteger)numberOfDelayedFetchers {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
NSUInteger sum = 0;
for (NSString *host in _delayedFetchersByHost) {
NSArray *fetchers = [_delayedFetchersByHost objectForKey:host];
sum += fetchers.count;
}
return sum;
}
}
- (NSArray *)issuedFetchers {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
NSMutableArray *allFetchers = [NSMutableArray array];
void (^accumulateFetchers)(id, id, BOOL *) = ^(NSString *host,
NSArray *fetchersForHost,
BOOL *stop) {
[allFetchers addObjectsFromArray:fetchersForHost];
};
[_runningFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers];
[_delayedFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers];
GTMSESSION_ASSERT_DEBUG(allFetchers.count == [NSSet setWithArray:allFetchers].count,
@"Fetcher appears multiple times\n running: %@\n delayed: %@",
_runningFetchersByHost, _delayedFetchersByHost);
return allFetchers.count > 0 ? allFetchers : nil;
}
}
- (NSArray *)issuedFetchersWithRequestURL:(NSURL *)requestURL {
NSString *host = requestURL.host;
if (host.length == 0) return nil;
NSURL *targetURL = [requestURL absoluteURL];
NSArray *allFetchers = [self issuedFetchers];
NSIndexSet *indexes = [allFetchers indexesOfObjectsPassingTest:^BOOL(GTMSessionFetcher *fetcher,
NSUInteger idx,
BOOL *stop) {
NSURL *fetcherURL = [fetcher.request.URL absoluteURL];
return [fetcherURL isEqual:targetURL];
}];
NSArray *result = nil;
if (indexes.count > 0) {
result = [allFetchers objectsAtIndexes:indexes];
}
return result;
}
- (void)stopAllFetchers {
NSArray *delayedFetchersByHost;
NSArray *runningFetchersByHost;
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
// Set the time barrier so fetchers know not to call back even if
// the stop calls below occur after the fetchers naturally
// stopped and so were removed from _runningFetchersByHost,
// but while the callbacks were already enqueued before stopAllFetchers
// was invoked.
_stoppedAllFetchersDate = [[NSDate alloc] init];
// Remove fetchers from the delayed list to avoid fetcherDidStop: from
// starting more fetchers running as a side effect of stopping one
delayedFetchersByHost = _delayedFetchersByHost.allValues;
[_delayedFetchersByHost removeAllObjects];
runningFetchersByHost = _runningFetchersByHost.allValues;
[_runningFetchersByHost removeAllObjects];
}
for (NSArray *delayedForHost in delayedFetchersByHost) {
for (GTMSessionFetcher *fetcher in delayedForHost) {
[self stopFetcher:fetcher];
}
}
for (NSArray *runningForHost in runningFetchersByHost) {
for (GTMSessionFetcher *fetcher in runningForHost) {
[self stopFetcher:fetcher];
}
}
}
- (NSDate *)stoppedAllFetchersDate {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _stoppedAllFetchersDate;
}
}
#pragma mark Accessors
- (BOOL)reuseSession {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _delegateDispatcher != nil;
}
}
- (void)setReuseSession:(BOOL)shouldReuse {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
BOOL wasReusing = (_delegateDispatcher != nil);
if (shouldReuse != wasReusing) {
[self abandonDispatcher];
if (shouldReuse) {
_delegateDispatcher =
[[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self
sessionDiscardInterval:_unusedSessionTimeout];
} else {
_delegateDispatcher = nil;
}
}
}
}
- (void)resetSession {
GTMSessionCheckNotSynchronized(self);
dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER);
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
[self resetSessionInternal];
}
dispatch_semaphore_signal(_sessionCreationSemaphore);
}
- (void)resetSessionInternal {
GTMSessionCheckSynchronized(self);
// The old dispatchers may be retained as delegates of any ongoing sessions by those sessions.
if (_delegateDispatcher) {
[self abandonDispatcher];
_delegateDispatcher =
[[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self
sessionDiscardInterval:_unusedSessionTimeout];
}
}
- (void)resetSessionForDispatcherDiscardTimer:(NSTimer *)timer {
GTMSessionCheckNotSynchronized(self);
dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER);
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
if (_delegateDispatcher.discardTimer == timer) {
// If the delegate dispatcher's current discardTimer is the same object as the timer
// that fired, no fetcher has recently attempted to start using the session by calling
// startSessionUsage, which invalidates and nils out the timer.
[self resetSessionInternal];
} else {
// A fetcher has invalidated the timer between its triggering and now, potentially
// meaning a fetcher has requested access to the NSURLSession, and may be in the process
// of starting a new task. The dispatcher should not be abandoned, as this can lead
// to a race condition between calling -finishTasksAndInvalidate on the NSURLSession
// and the fetcher attempting to create a new task.
}
}
dispatch_semaphore_signal(_sessionCreationSemaphore);
}
- (NSTimeInterval)unusedSessionTimeout {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _unusedSessionTimeout;
}
}
- (void)setUnusedSessionTimeout:(NSTimeInterval)timeout {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
_unusedSessionTimeout = timeout;
_delegateDispatcher.discardInterval = timeout;
}
}
// This method should be called inside of @synchronized(self)
- (void)abandonDispatcher {
GTMSessionCheckSynchronized(self);
[_delegateDispatcher abandon];
}
- (NSDictionary *)runningFetchersByHost {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return [_runningFetchersByHost copy];
}
}
- (void)setRunningFetchersByHost:(NSDictionary *)dict {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
_runningFetchersByHost = [dict mutableCopy];
}
}
- (NSDictionary *)delayedFetchersByHost {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return [_delayedFetchersByHost copy];
}
}
- (void)setDelayedFetchersByHost:(NSDictionary *)dict {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
_delayedFetchersByHost = [dict mutableCopy];
}
}
- (id<GTMFetcherAuthorizationProtocol>)authorizer {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _authorizer;
}
}
- (void)setAuthorizer:(id<GTMFetcherAuthorizationProtocol>)obj {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
if (obj != _authorizer) {
[self detachAuthorizer];
}
_authorizer = obj;
}
// Use the fetcher service for the authorization fetches if the auth
// object supports fetcher services
if ([obj respondsToSelector:@selector(setFetcherService:)]) {
#if GTM_USE_SESSION_FETCHER
[obj setFetcherService:self];
#else
[obj setFetcherService:(id)self];
#endif
}
}
// This should be called inside a @synchronized(self) block except during dealloc.
- (void)detachAuthorizer {
// This method is called by the fetcher service's dealloc and setAuthorizer:
// methods; do not override.
//
// The fetcher service retains the authorizer, and the authorizer has a
// weak pointer to the fetcher service (a non-zeroing pointer for
// compatibility with iOS 4 and Mac OS X 10.5/10.6.)
//
// When this fetcher service no longer uses the authorizer, we want to remove
// the authorizer's dependence on the fetcher service. Authorizers can still
// function without a fetcher service.
if ([_authorizer respondsToSelector:@selector(fetcherService)]) {
id authFetcherService = [_authorizer fetcherService];
if (authFetcherService == self) {
[_authorizer setFetcherService:nil];
}
}
}
- (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _callbackQueue;
} // @synchronized(self)
}
- (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
_callbackQueue = queue ?: dispatch_get_main_queue();
} // @synchronized(self)
}
- (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _delegateQueue;
} // @synchronized(self)
}
- (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
_delegateQueue = queue ?: [NSOperationQueue mainQueue];
} // @synchronized(self)
}
- (NSOperationQueue *)delegateQueue {
// Provided for compatibility with the old fetcher service. The gtm-oauth2 code respects
// any custom delegate queue for calling the app.
return nil;
}
+ (NSUInteger)numberOfNonBackgroundSessionFetchers:(NSArray *)fetchers {
NSUInteger sum = 0;
for (GTMSessionFetcher *fetcher in fetchers) {
if (!fetcher.usingBackgroundSession) {
++sum;
}
}
return sum;
}
@end
@implementation GTMSessionFetcherService (TestingSupport)
+ (instancetype)mockFetcherServiceWithFakedData:(NSData *)fakedDataOrNil
fakedError:(NSError *)fakedErrorOrNil {
#if !GTM_DISABLE_FETCHER_TEST_BLOCK
NSURL *url = [NSURL URLWithString:@"http://example.invalid"];
NSHTTPURLResponse *fakedResponse =
[[NSHTTPURLResponse alloc] initWithURL:url
statusCode:(fakedErrorOrNil ? 500 : 200)
HTTPVersion:@"HTTP/1.1"
headerFields:nil];
return [self mockFetcherServiceWithFakedData:fakedDataOrNil
fakedResponse:fakedResponse
fakedError:fakedErrorOrNil];
#else
GTMSESSION_ASSERT_DEBUG(0, @"Test blocks disabled");
return nil;
#endif // GTM_DISABLE_FETCHER_TEST_BLOCK
}
+ (instancetype)mockFetcherServiceWithFakedData:(NSData *)fakedDataOrNil
fakedResponse:(NSHTTPURLResponse *)fakedResponse
fakedError:(NSError *)fakedErrorOrNil {
#if !GTM_DISABLE_FETCHER_TEST_BLOCK
GTMSessionFetcherService *service = [[self alloc] init];
service.allowedInsecureSchemes = @[ @"http" ];
service.testBlock = ^(GTMSessionFetcher *fetcherToTest,
GTMSessionFetcherTestResponse testResponse) {
testResponse(fakedResponse, fakedDataOrNil, fakedErrorOrNil);
};
return service;
#else
GTMSESSION_ASSERT_DEBUG(0, @"Test blocks disabled");
return nil;
#endif // GTM_DISABLE_FETCHER_TEST_BLOCK
}
#pragma mark Synchronous Wait for Unit Testing
- (BOOL)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds {
NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds];
_stoppedFetchersToWaitFor = [NSMutableArray array];
BOOL shouldSpinRunLoop = [NSThread isMainThread];
const NSTimeInterval kSpinInterval = 0.001;
BOOL didTimeOut = NO;
while (([self numberOfFetchers] > 0 || _stoppedFetchersToWaitFor.count > 0)) {
didTimeOut = [giveUpDate timeIntervalSinceNow] < 0;
if (didTimeOut) break;
GTMSessionFetcher *stoppedFetcher = _stoppedFetchersToWaitFor.firstObject;
if (stoppedFetcher) {
[_stoppedFetchersToWaitFor removeObject:stoppedFetcher];
[stoppedFetcher waitForCompletionWithTimeout:10.0 * kSpinInterval];
}
if (shouldSpinRunLoop) {
NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval];
[[NSRunLoop currentRunLoop] runUntilDate:stopDate];
} else {
[NSThread sleepForTimeInterval:kSpinInterval];
}
}
_stoppedFetchersToWaitFor = nil;
return !didTimeOut;
}
@end
@implementation GTMSessionFetcherService (BackwardsCompatibilityOnly)
- (NSInteger)cookieStorageMethod {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
return _cookieStorageMethod;
}
}
- (void)setCookieStorageMethod:(NSInteger)cookieStorageMethod {
@synchronized(self) {
GTMSessionMonitorSynchronized(self);
_cookieStorageMethod = cookieStorageMethod;
}
}
@end
@implementation GTMSessionFetcherSessionDelegateDispatcher {
__weak GTMSessionFetcherService *_parentService;
NSURLSession *_session;
// The task map maps NSURLSessionTasks to GTMSessionFetchers
NSMutableDictionary *_taskToFetcherMap;
// The discard timer will invalidate sessions after the session's last task completes.
NSTimer *_discardTimer;
NSTimeInterval _discardInterval;
}
@synthesize discardInterval = _discardInterval,
session = _session;
- (instancetype)init {
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService
sessionDiscardInterval:(NSTimeInterval)discardInterval {
self = [super init];
if (self) {
_discardInterval = discardInterval;
_parentService = parentService;
}
return self;
}
- (NSString *)description {