-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathSGCache.m
473 lines (395 loc) · 16 KB
/
SGCache.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
//
// Created by matt on 7/05/15.
//
#import <MGEvents/MGEvents.h>
#import "SGCache.h"
#import "SGCacheTask.h"
#import "SGCachePrivate.h"
#import "SGCachePromise.h"
#import "NSString+SGImageCacheHash.h"
#define FOLDER_NAME @"SGCache"
#define MAX_RETRIES 5
SGImageCacheLogging gSGImageCacheLogging = SGImageCacheLogNothing;
void backgroundDo(void(^block)(void)) {
if (NSThread.isMainThread) { // we're on the main thread. ew
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
block();
});
} else { // we're already off the main thread. chillax
block();
}
}
@implementation SGCache
+ (SGCache *)cache {
static SGCache *singleton;
static dispatch_once_t token = 0;
dispatch_once(&token, ^{
singleton = [[self alloc] init];
});
return singleton;
}
- (id)init {
self = [super init];
self.folderName = FOLDER_NAME;
self.cachePath = self.makeCachePath;
[self slowQueue];
[self fastQueue];
return self;
}
#pragma mark - Public API
+ (BOOL)haveFileForURL:(NSString *)url {
return [self haveFileForCacheKey:[self.cache cacheKeyFor:url requestHeaders:nil]];
}
+ (BOOL)haveFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers {
return [self haveFileForCacheKey:[self.cache cacheKeyFor:url requestHeaders:headers]];
}
+ (BOOL)haveFileForCacheKey:(NSString *)cacheKey {
if (![cacheKey isKindOfClass:NSString.class]) {
return NO;
}
return [NSFileManager.defaultManager fileExistsAtPath:[self.cache pathForCacheKey:cacheKey]];
}
+ (NSData *)fileForURL:(NSString *)url {
return [NSData dataWithContentsOfFile:[self.cache pathForURL:url requestHeaders:nil]];
}
+ (NSData *)fileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers {
return [NSData dataWithContentsOfFile:[self.cache pathForURL:url requestHeaders:headers]];
}
+ (NSData *)fileForCacheKey:(NSString *)cacheKey {
return [NSData dataWithContentsOfFile:[self.cache pathForCacheKey:cacheKey]];
}
+ (SGCachePromise *)getFileForURL:(NSString *)url {
return [self getFileForURL:url requestHeaders:nil];
}
+ (SGCachePromise *)getFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers {
id cacheKey = [self.cache cacheKeyFor:url requestHeaders:headers];
return [self getFileForURL:url requestHeaders:headers cacheKey:cacheKey];
}
+ (SGCachePromise *)getFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers
cacheKey:(NSString *)cacheKey {
__block SGCachePromise *promise = [SGCachePromise new:^(PMKPromiseFulfiller fulfill, PMKPromiseRejecter reject) {
dispatch_async(dispatch_get_main_queue(), ^{
[self getFileForURL:url requestHeaders:headers cacheKey:cacheKey remoteFetchOnly:NO
thenDo:^(NSData *data) {
fulfill(data);
} onFail:^(NSError *error, BOOL wasFatal) {
if (wasFatal) {
reject(error);
}
} promise:promise];
});
}];
return promise;
}
+ (SGCachePromise *)getRemoteFileForURL:(NSString *)url {
return [self getRemoteFileForURL:url requestHeaders:nil];
}
+ (SGCachePromise *)getRemoteFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers {
id cacheKey = [self.cache cacheKeyFor:url requestHeaders:headers];
return [self getRemoteFileForURL:url requestHeaders:headers cacheKey:cacheKey];
}
+ (SGCachePromise *)getRemoteFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers
cacheKey:(NSString *)cacheKey {
__block SGCachePromise *promise = [SGCachePromise new:^(PMKPromiseFulfiller fulfill, PMKPromiseRejecter reject) {
dispatch_async(dispatch_get_main_queue(), ^{
[self getFileForURL:url requestHeaders:headers cacheKey:cacheKey remoteFetchOnly:YES
thenDo:^(NSData *data) {
fulfill(data);
} onFail:^(NSError *error, BOOL wasFatal) {
if (wasFatal) {
reject(error);
}
} promise:promise];
});
}];
return promise;
}
+ (SGCachePromise *)slowGetFileForURL:(NSString *)url {
return [self slowGetFileForURL:url requestHeaders:nil];
}
+ (SGCachePromise *)slowGetFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers {
id cacheKey = [self.cache cacheKeyFor:url requestHeaders:headers];
return [self slowGetFileForURL:url requestHeaders:headers cacheKey:cacheKey];
}
+ (SGCachePromise *)slowGetFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers
cacheKey:(NSString *)cacheKey {
__block SGCachePromise *promise = [SGCachePromise new:^(PMKPromiseFulfiller fulfill, PMKPromiseRejecter reject) {
dispatch_async(dispatch_get_main_queue(), ^{
[self slowGetFileForURL:url requestHeaders:headers cacheKey:cacheKey
thenDo:^(NSData *data) {
fulfill(data);
} onFail:^(NSError *error, BOOL wasFatal) {
if (wasFatal) {
reject(error);
}
} promise:promise];
});
}];
return promise;
}
+ (void)getFileForURL:(NSString *)url requestHeaders:(NSDictionary *)headers
cacheKey:(NSString *)cacheKey remoteFetchOnly:(BOOL)remoteOnly
thenDo:(SGCacheFetchCompletion)completion
onFail:(SGCacheFetchFail)failBlock
promise:(SGCachePromise *)promise {
if (![url isKindOfClass:NSString.class] || !url.length) {
return;
}
backgroundDo(^{
SGCacheTask *slowTask = [self existingSlowQueueTaskFor:cacheKey];
SGCacheTask *fastTask = [self existingFastQueueTaskFor:cacheKey];
if (slowTask.isExecuting) { // reuse an executing slow task
[slowTask addCompletion:completion];
[slowTask addCompletions:fastTask.completions];
[slowTask addFailBlock:failBlock];
[slowTask addFailBlocks:fastTask.onFailBlocks];
slowTask.promise = promise;
[fastTask cancel];
} else if (fastTask) { // reuse a fast task
[fastTask addCompletion:completion];
[fastTask addCompletions:slowTask.completions];
[fastTask addFailBlock:failBlock];
[fastTask addFailBlocks:slowTask.onFailBlocks];
fastTask.promise = promise;
[slowTask cancel];
} else { // add a fresh task to fast queue
SGCacheTask *task = [self taskForURL:url requestHeaders:headers cacheKey:cacheKey
attempt:1];
task.remoteFetchOnly = remoteOnly;
[task addCompletion:completion];
[task addFailBlock:failBlock];
task.promise = promise;
[self.cache.fastQueue addOperation:task];
}
});
}
+ (void)slowGetFileForURL:(NSString *)url requestHeaders:(NSDictionary *)requestHeaders
cacheKey:(NSString *)cacheKey thenDo:(SGCacheFetchCompletion)completion
onFail:(SGCacheFetchFail)failBlock
promise:(SGCachePromise *)promise {
if (![url isKindOfClass:NSString.class] || !url.length) {
return;
}
backgroundDo(^{
SGCacheTask *slowTask = [self existingSlowQueueTaskFor:cacheKey];
SGCacheTask *fastTask = [self existingFastQueueTaskFor:cacheKey];
if (fastTask && !slowTask.isExecuting) { // reuse existing fast task
[fastTask addCompletion:completion];
[fastTask addCompletions:slowTask.completions];
[fastTask addFailBlock:failBlock];
[fastTask addFailBlocks:slowTask.onFailBlocks];
fastTask.promise = promise;
[slowTask cancel];
} else if (slowTask) { // reuse existing slow task
[slowTask addCompletion:completion];
[slowTask addCompletions:fastTask.completions];
[slowTask addFailBlock:failBlock];
[slowTask addFailBlocks:fastTask.onFailBlocks];
slowTask.promise = promise;
[fastTask cancel];
} else { // add a fresh task to slow queue
SGCacheTask *task = [self taskForURL:url requestHeaders:requestHeaders cacheKey:cacheKey
attempt:1];
[task addCompletion:completion];
[task addFailBlock:failBlock];
task.promise = promise;
[self.cache.slowQueue addOperation:task];
}
});
}
+ (void)moveTaskToSlowQueueForURL:(NSString *)url {
[self moveTaskToSlowQueueForURL:url requestHeaders:nil];
}
+ (void)moveTaskToSlowQueueForURL:(NSString *)url requestHeaders:(NSDictionary *)headers {
[self moveTaskToSlowQueueForCacheKey:[self.cache cacheKeyFor:url requestHeaders:headers]];
}
+ (void)moveTaskToSlowQueueForCacheKey:(NSString *)cacheKey {
if (![cacheKey isKindOfClass:NSString.class] || !cacheKey.length) {
return;
}
backgroundDo(^{
SGCacheTask *fastTask = [self existingFastQueueTaskFor:cacheKey];
if (fastTask) {
SGCacheTask *slowTask = [self existingSlowQueueTaskFor:cacheKey];
if (slowTask) { // reuse an executing slow task
[slowTask addCompletions:fastTask.completions];
} else { // add a fresh task to slow queue
SGCacheTask *task = [self taskForURL:fastTask.url
requestHeaders:fastTask.requestHeaders cacheKey:cacheKey attempt:1];
[task addCompletions:fastTask.completions];
[self.cache.slowQueue addOperation:task];
}
[fastTask cancel];
}
});
}
+ (void)flushFilesOlderThan:(NSTimeInterval)age {
// let the queues finish, then suspend them
[self.cache.slowQueue waitUntilAllOperationsAreFinished];
self.cache.slowQueue.suspended = YES;
[self.cache.fastQueue waitUntilAllOperationsAreFinished];
self.cache.fastQueue.suspended = YES;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSArray *files = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.cache
.cachePath error:nil];
for (NSString *file in files) {
if ([file isEqualToString:@"."] || [file isEqualToString:@".."]) {
continue;
}
NSString *path = [self.cache.cachePath stringByAppendingPathComponent:file];
NSDate *created = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil].fileCreationDate;
// too old. delete it
if (-created.timeIntervalSinceNow > age) {
[NSFileManager.defaultManager removeItemAtPath:path error:nil];
}
}
// let the queues run wild again
dispatch_async(dispatch_get_main_queue(), ^{
self.cache.fastQueue.suspended = NO;
self.cache.slowQueue.suspended = NO;
});
});
}
+ (void)addData:(NSData *)data forCacheKey:(NSString *)cacheKey {
[data writeToFile:[self.cache pathForCacheKey:cacheKey] atomically:YES];
}
+ (void)removeDataForCacheKey:(NSString *)cacheKey {
NSString *path = [self.cache pathForCacheKey:cacheKey];
if (path.length) {
[NSFileManager.defaultManager removeItemAtPath:path error:nil];
}
}
#pragma mark - Task Factory
+ (SGCacheTask *)taskForURL:(NSString *)url requestHeaders:(NSDictionary *)requestHeaders
cacheKey:(NSString *)cacheKey attempt:(int)attempt {
SGCacheTask *task = [SGCacheTask taskForURL:url requestHeaders:requestHeaders cacheKey:cacheKey
attempt:attempt];
__weak SGCacheTask *wTask = task;
task.completionBlock = ^{
if (!wTask.succeeded) {
[SGCache taskFailed:wTask];
}
};
return task;
}
#pragma mark - Task Finders
+ (SGCacheTask *)existingSlowQueueTaskFor:(NSString *)cacheKey {
for (SGCacheTask *task in self.cache.slowQueue.operations) {
if ([task matchesCacheKey:cacheKey]) {
return task;
}
}
return nil;
}
+ (SGCacheTask *)existingFastQueueTaskFor:(NSString *)cacheKey {
for (SGCacheTask *task in self.cache.fastQueue.operations) {
if ([task matchesCacheKey:cacheKey]) {
return task;
}
}
return nil;
}
+ (SGCacheTask *)taskForPromise:(SGCachePromise *)promise {
if (!promise) {
return nil;
}
for (SGCacheTask *task in self.cache.fastQueue.operations) {
if (promise == task.promise) {
return task;
}
}
for (SGCacheTask *task in self.cache.slowQueue.operations) {
if (promise == task.promise) {
return task;
}
}
return nil;
}
#pragma mark - Fail Handle
+ (void)taskFailed:(SGCacheTask *)task {
// too many retries?
if (task.attempt >= MAX_RETRIES) {
for (SGCacheFetchCompletion completion in task.completions) {
completion(nil);
}
return;
}
// make and add a retry task
SGCacheTask *retryTask = [self taskForURL:task.url requestHeaders:task.requestHeaders
cacheKey:nil attempt:task.attempt + 1];
[retryTask addCompletions:task.completions];
[self.cache.fastQueue addOperation:retryTask];
}
#pragma mark - File and Memory Cache Setup
- (NSString *)makeCachePath {
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,
YES)[0];
path = [path stringByAppendingFormat:@"/%@", self.folderName];
// make the cache directory if necessary
BOOL isDir;
if (![NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDir]) {
[NSFileManager.defaultManager createDirectoryAtPath:path withIntermediateDirectories:NO
attributes:nil error:nil];
}
return path;
}
#pragma mark - Getters
- (NSString *)hashForDictionary:(NSDictionary *)dict {
NSMutableString *hash = [NSMutableString stringWithFormat:@"%@", @(dict.hash)];
for (id key in dict) {
[hash appendFormat:@"%@", @([key hash])];
id value = dict[key];
if ([value respondsToSelector:@selector(sgCacheHash)]) {
[hash appendFormat:@"%@", [value sgCacheHash]];
} else if ([value conformsToProtocol:@protocol(NSObject)]) {
[hash appendFormat:@"%@", @([value hash])];
}
}
return hash;
}
- (NSString *)pathForCacheKey:(NSString *)cacheKey {
return [NSString stringWithFormat:@"%@/%@", self.cachePath, cacheKey.sgCacheHash];
}
- (NSString *)pathForURL:(NSString *)url requestHeaders:(NSDictionary *)headers {
return [self pathForCacheKey:[self cacheKeyFor:url requestHeaders:headers]];
}
- (NSString *)cacheKeyFor:(NSString *)url requestHeaders:(NSDictionary *)headers {
return [NSString stringWithFormat:@"%@%@", url.sgCacheHash, [self hashForDictionary:headers]];
}
- (NSOperationQueue *)fastQueue {
if (_fastQueue) {
return _fastQueue;
}
_fastQueue = NSOperationQueue.new;
// suspend slowQueue while fastQueue is active
__weakSelf me = self;
__weak NSOperationQueue *wQueue = _fastQueue;
[_fastQueue onChangeOf:@"operationCount" do:^{
me.slowQueue.suspended = !!wQueue.operationCount;
}];
return _fastQueue;
}
- (NSOperationQueue *)slowQueue {
if (!_slowQueue) {
_slowQueue = NSOperationQueue.new;
_slowQueue.maxConcurrentOperationCount = 1;
}
return _slowQueue;
}
#pragma mark - Retry handling
+ (void)addRetryForPromise:(SGCachePromise *)promise retryBlock:(SGCacheFetchOnRetry)retry {
SGCacheTask *task = [self taskForPromise:promise];
[task addRetryBlock:retry];
}
+ (void)addFailForPromise:(SGCachePromise *)promise failBlock:(SGCacheFetchFail)failBlock {
SGCacheTask *task = [self taskForPromise:promise];
[task addFailBlock:failBlock];
}
#pragma mark - Logging
+ (void)setLogging:(SGImageCacheLogging)logging {
gSGImageCacheLogging = logging;
}
+ (SGImageCacheLogging)logging {
return gSGImageCacheLogging;
}
@end