forked from mapbox/mapbox-gl-native-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMGLNetworkConfiguration.m
229 lines (180 loc) · 7.78 KB
/
MGLNetworkConfiguration.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
#import "MGLNetworkConfiguration_Private.h"
#import "MGLLoggingConfiguration_Private.h"
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
#import "MGLAccountManager_Private.h"
#endif
#import "MGLReachability.h"
static NSString * const MGLStartTime = @"start_time";
static NSString * const MGLResourceType = @"resource_type";
NSString * const kMGLDownloadPerformanceEvent = @"mobile.performance_trace";
@interface MGLNetworkConfiguration () <MGLNativeNetworkDelegate>
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSDictionary*> *events;
@property (nonatomic, weak) id<MGLNetworkConfigurationMetricsDelegate> metricsDelegate;
@property (nonatomic) dispatch_queue_t eventsQueue;
@end
@implementation MGLNetworkConfiguration
{
NSURLSessionConfiguration *_sessionConfig;
}
- (instancetype)init {
if (self = [super init]) {
self.sessionConfiguration = nil;
_events = [NSMutableDictionary dictionary];
_eventsQueue = dispatch_queue_create("com.mapbox.network-configuration", DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
+ (instancetype)sharedManager {
static dispatch_once_t onceToken;
static MGLNetworkConfiguration *_sharedManager;
dispatch_once(&onceToken, ^{
_sharedManager = [[self alloc] init];
});
// Notice, this is reset for each call. This is primarily for testing purposes.
// TODO: Consider only calling this for testing?
[_sharedManager resetNativeNetworkManagerDelegate];
return _sharedManager;
}
- (void)resetNativeNetworkManagerDelegate {
// Tell core about our network integration. `delegate` here is not (yet)
// intended to be set to nil, except for testing.
[MGLNativeNetworkManager sharedManager].delegate = self;
}
+ (NSURLSessionConfiguration *)defaultSessionConfiguration {
NSURLSessionConfiguration* sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.timeoutIntervalForResource = 30;
sessionConfiguration.HTTPMaximumConnectionsPerHost = 8;
sessionConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
sessionConfiguration.URLCache = nil;
return sessionConfiguration;
}
#pragma mark - MGLNativeNetworkDelegate
- (NSURLSession *)sessionForNetworkManager:(MGLNativeNetworkManager *)networkManager {
// Note: this method is NOT called on the main thread.
NSURLSession *session;
if ([self.delegate respondsToSelector:@selector(sessionForNetworkConfiguration:)]) {
session = [self.delegate sessionForNetworkConfiguration:self];
}
// Check for a background session; string checking is fragile, but this is not
// a deal breaker as we're only doing this to provide more clarity to the
// developer
NSAssert(![session isKindOfClass:NSClassFromString(@"__NSURLBackgroundSession")],
@"Background NSURLSessions are not yet supported");
if (session.delegate) {
NSAssert(![session.delegate conformsToProtocol:@protocol(NSURLSessionDataDelegate)],
@"Session delegates conforming to NSURLSessionDataDelegate are not yet supported");
}
return session;
}
- (NSURLSessionConfiguration *)sessionConfiguration {
NSURLSessionConfiguration *sessionConfig = nil;
@synchronized (self) {
sessionConfig = _sessionConfig;
}
return sessionConfig;
}
- (void)setSessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration {
@synchronized (self) {
if (sessionConfiguration == nil) {
_sessionConfig = [MGLNetworkConfiguration defaultSessionConfiguration];
} else {
_sessionConfig = sessionConfiguration;
}
}
}
#if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
- (NSString *)skuToken {
return MGLAccountManager.skuToken;
}
#endif
- (void)startDownloadEvent:(NSString *)urlString type:(NSString *)resourceType {
if (urlString && resourceType && ![self eventDictionaryForKey:urlString]) {
NSDate *startDate = [NSDate date];
[self setEventDictionary:@{ MGLStartTime: startDate, MGLResourceType: resourceType }
forKey:urlString];
}
}
- (void)stopDownloadEventForResponse:(NSURLResponse *)response {
[self sendEventForURLResponse:response withAction:nil];
}
- (void)cancelDownloadEventForResponse:(NSURLResponse *)response {
[self sendEventForURLResponse:response withAction:@"cancel"];
}
- (void)debugLog:(NSString *)format, ... {
MGLLogDebug(format);
}
- (void)errorLog:(NSString *)format, ... {
MGLLogError(format);
}
#pragma mark - Event management
- (void)sendEventForURLResponse:(NSURLResponse *)response withAction:(NSString *)action
{
if ([response isKindOfClass:[NSURLResponse class]]) {
NSString *urlString = response.URL.relativePath;
if (urlString && [self eventDictionaryForKey:urlString]) {
NSDictionary *eventAttributes = [self eventAttributesForURL:response withAction:action];
[self removeEventDictionaryForKey:urlString];
dispatch_async(dispatch_get_main_queue(), ^{
[self.metricsDelegate networkConfiguration:self didGenerateMetricEvent:eventAttributes];
});
}
}
}
- (NSDictionary *)eventAttributesForURL:(NSURLResponse *)response withAction:(NSString *)action
{
NSString *urlString = response.URL.relativePath;
NSDictionary *parameters = [self eventDictionaryForKey:urlString];
NSDate *startDate = [parameters objectForKey:MGLStartTime];
NSDate *endDate = [NSDate date];
NSTimeInterval elapsedTime = [endDate timeIntervalSinceDate:startDate];
NSDateFormatter* iso8601Formatter = [[NSDateFormatter alloc] init];
iso8601Formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
NSString *createdDate = [iso8601Formatter stringFromDate:[NSDate date]];
NSMutableArray *attributes = [NSMutableArray array];
[attributes addObject:@{ @"name" : @"requestUrl" , @"value" : urlString }];
[attributes addObject:@{ @"name" : MGLResourceType , @"value" : [parameters objectForKey:MGLResourceType] }];
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
[attributes addObject:@{ @"name" : @"responseCode", @"value" : @(responseCode)}];
}
BOOL isWIFIOn = [[MGLReachability reachabilityWithHostName:response.URL.host] isReachableViaWiFi];
[attributes addObject:@{ @"name" : @"wifiOn", @"value" : @(isWIFIOn)}];
if (action) {
[attributes addObject:@{ @"name" : @"action" , @"value" : action }];
}
double elapsedTimeInMS = elapsedTime * 1000.0;
return @{
@"event" : kMGLDownloadPerformanceEvent,
@"created" : createdDate,
@"sessionId" : [NSUUID UUID].UUIDString,
@"counters" : @[ @{ @"name" : @"elapsedMS" , @"value" : @(elapsedTimeInMS) } ],
@"attributes" : attributes
};
}
#pragma mark - Events dictionary access
- (nullable NSDictionary*)eventDictionaryForKey:(nonnull NSString*)key {
__block NSDictionary *dictionary;
dispatch_sync(self.eventsQueue, ^{
dictionary = [self.events objectForKey:key];
});
return dictionary;
}
- (void)setEventDictionary:(nonnull NSDictionary*)dictionary forKey:(nonnull NSString*)key {
dispatch_barrier_async(self.eventsQueue, ^{
[self.events setObject:dictionary forKey:key];
});
}
- (void)removeEventDictionaryForKey:(nonnull NSString*)key {
dispatch_barrier_async(self.eventsQueue, ^{
[self.events removeObjectForKey:key];
});
}
@end
@implementation MGLNetworkConfiguration (ForTesting)
+ (void)testing_clearNativeNetworkManagerDelegate {
[MGLNativeNetworkManager sharedManager].delegate = nil;
}
+ (id)testing_nativeNetworkManagerDelegate {
return [MGLNativeNetworkManager sharedManager].delegate;
}
@end