Oolite
Loading...
Searching...
No Matches
OOCacheManager.m
Go to the documentation of this file.
1/*
2
3OOCacheManager.m
4
5Oolite
6Copyright (C) 2004-2013 Giles C Williams and contributors
7
8This program is free software; you can redistribute it and/or
9modify it under the terms of the GNU General Public License
10as published by the Free Software Foundation; either version 2
11of the License, or (at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program; if not, write to the Free Software
20Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21MA 02110-1301, USA.
22
23*/
24
25#import "OOCacheManager.h"
28#import "OODeepCopy.h"
29#import "OOJavaScriptEngine.h"
30#import "OOPListParsing.h"
31
32#define WRITE_ASYNC 1
33#define PROFILE_WRITES 0
34
35// Use the (presumed) most efficient plist format for each platform.
36#if OOLITE_MAC_OS_X
37#define CACHE_PLIST_FORMAT NSPropertyListBinaryFormat_v1_0
38#else
39#define CACHE_PLIST_FORMAT NSPropertyListGNUstepBinaryFormat
40#endif
41
42#if WRITE_ASYNC
44#endif
45#if PROFILE_WRITES
47#endif
48
49static NSString* const kOOLogDataCacheFound = @"dataCache.found";
50static NSString* const kOOLogDataCacheNotFound = @"dataCache.notFound";
51static NSString* const kOOLogDataCacheRebuild = @"dataCache.rebuild";
52static NSString* const kOOLogDataCacheWriteSuccess = @"dataCache.write.success";
53static NSString* const kOOLogDataCacheWriteFailed = @"dataCache.write.failed";
54static NSString* const kOOLogDataCacheRetrieveSuccess = @"dataCache.retrieve.success";
55static NSString* const kOOLogDataCacheRetrieveFailed = @"dataCache.retrieve.failed";
56static NSString* const kOOLogDataCacheSetSuccess = @"dataCache.set.success";
57static NSString* const kOOLogDataCacheSetFailed = @"dataCache.set.failed";
58static NSString* const kOOLogDataCacheRemoveSuccess = @"dataCache.remove.success";
59static NSString* const kOOLogDataCacheClearSuccess = @"dataCache.clear.success";
60static NSString* const kOOLogDataCacheBuildPathError = @"dataCache.write.buildPath.failed";
61static NSString* const kOOLogDataCacheSerializationError = @"dataCache.write.serialize.failed";
62
63static NSString* const kCacheKeyVersion = @"version";
64static NSString* const kCacheKeyEndianTag = @"endian tag";
65static NSString* const kCacheKeyFormatVersion = @"format version";
66static NSString* const kCacheKeyCaches = @"caches";
67
68enum {
69 kEndianTagValue = 0x0123456789ABCDEFULL,
71};
72
74
75@interface OOCacheManager (Private)
76
77- (void)loadCache;
78- (void)write;
79- (void)clear;
80- (BOOL)dirty;
81- (void)markClean;
82
83- (NSDictionary*)loadDict;
84- (BOOL)writeDict:(NSDictionary*)inDict;
85
86- (void)buildCachesFromDictionary:(NSDictionary*)inDict;
87- (NSDictionary*)dictionaryOfCaches;
88
89- (BOOL)directoryExists:(NSString*)inPath create:(BOOL)inCreate;
90
91@end
92
93@interface OOCacheManager (PlatformSpecific)
94
95- (NSString*)cachePathCreatingIfNecessary:(BOOL)inCreate;
96
97@end
98
99#if WRITE_ASYNC
100@interface OOAsyncCacheWriter : NSObject <OOAsyncWorkTask> {
101@private
102 NSDictionary* _cacheContents;
103}
104
105- (id)initWithCacheContents:(NSDictionary*)cacheContents;
106
107@end
108#endif
109
110@implementation OOCacheManager
111
112- (id)init
113{
114 self = [super init];
115 if (self != nil) {
116 _permitWrites = YES;
117 [self loadCache];
118 }
119 return self;
120}
121
122- (void)dealloc
123{
124 [self clear];
125
126 [super dealloc];
127}
128
129- (NSString*)description
130{
131 return [NSString stringWithFormat:@"<%@ %p>{dirty=%s}", [self class], self, [self dirty] ? "yes" : "no"];
132}
133
135{
136 // NOTE: assumes single-threaded access.
137 if (sSingleton == nil) {
138 sSingleton = [[self alloc] init];
139 }
140
141 return sSingleton;
142}
143
144- (id)objectForKey:(NSString*)inKey inCache:(NSString*)inCacheKey
145{
146 NSMutableDictionary* cache = nil;
147 id result = nil;
148
149 NSParameterAssert(inKey != nil && inCacheKey != nil);
150
151 cache = [_caches objectForKey:inCacheKey];
152 if (cache != nil) {
153 result = [cache objectForKey:inKey];
154 if (result != nil) {
155 OODebugLog(kOOLogDataCacheRetrieveSuccess, @"Retrieved \"%@\" cache object %@.", inCacheKey, inKey);
156 } else {
157 OODebugLog(kOOLogDataCacheRetrieveFailed, @"Failed to retrieve \"%@\" cache object %@ -- no such entry.", inCacheKey, inKey);
158 }
159 } else {
160 OODebugLog(kOOLogDataCacheRetrieveFailed, @"Failed to retrieve \"%@\" cache object %@ -- no such cache.", inCacheKey, inKey);
161 }
162
163 return result;
164}
165
166- (void)setObject:(id)inObject forKey:(NSString*)inKey inCache:(NSString*)inCacheKey
167{
168 NSMutableDictionary* cache = nil;
169
170 NSParameterAssert(inObject != nil && inKey != nil && inCacheKey != nil);
171
172 if (EXPECT_NOT(_caches == nil))
173 return;
174
175 cache = [_caches objectForKey:inCacheKey];
176 if (cache == nil) {
177 cache = [NSMutableDictionary dictionary];
178 if (cache == nil) {
179 OODebugLog(kOOLogDataCacheSetFailed, @"Failed to create cache for key \"%@\".", inCacheKey);
180 return;
181 }
182 [_caches setObject:cache forKey:inCacheKey];
183 }
184
185 [cache setObject:inObject forKey:inKey];
186 _dirty = YES;
187 OODebugLog(kOOLogDataCacheSetSuccess, @"Updated entry %@ in cache \"%@\".", inKey, inCacheKey);
188}
189
190- (void)removeObjectForKey:(NSString*)inKey inCache:(NSString*)inCacheKey
191{
192 NSMutableDictionary* cache = nil;
193
194 NSParameterAssert(inKey != nil && inCacheKey != nil);
195
196 cache = [_caches objectForKey:inCacheKey];
197 if (cache != nil) {
198 if (nil != [cache objectForKey:inKey]) {
199 [cache removeObjectForKey:inKey];
200 _dirty = YES;
201 OODebugLog(kOOLogDataCacheRemoveSuccess, @"Removed entry keyed %@ from cache \"%@\".", inKey, inCacheKey);
202 } else {
203 OODebugLog(kOOLogDataCacheRemoveSuccess, @"No need to remove non-existent entry keyed %@ from cache \"%@\".", inKey, inCacheKey);
204 }
205 } else {
206 OODebugLog(kOOLogDataCacheRemoveSuccess, @"No need to remove entry keyed %@ from non-existent cache \"%@\".", inKey, inCacheKey);
207 }
208}
209
210- (void)clearCache:(NSString*)inCacheKey
211{
212 NSParameterAssert(inCacheKey != nil);
213
214 if (nil != [_caches objectForKey:inCacheKey]) {
215 [_caches removeObjectForKey:inCacheKey];
216 _dirty = YES;
217 OODebugLog(kOOLogDataCacheClearSuccess, @"Cleared cache \"%@\".", inCacheKey);
218 } else {
219 OODebugLog(kOOLogDataCacheClearSuccess, @"No need to clear non-existent cache \"%@\".", inCacheKey);
220 }
221}
222
224{
225 [self clear];
226 _caches = [[NSMutableDictionary alloc] init];
227 _dirty = YES;
228}
229
231{
232 [self clear];
233 [self loadCache];
234}
235
236- (void)flush
237{
238 if (_permitWrites && [self dirty] && _scheduledWrite == nil) {
239 [self write];
240 [self markClean];
241 }
242}
243
245{
246#if WRITE_ASYNC
248#endif
249}
250
251- (void)setAllowCacheWrites:(BOOL)flag
252{
253 _permitWrites = (flag != NO);
254}
255
256- (NSString*)cacheDirectoryPathCreatingIfNecessary:(BOOL)create
257{
258 /* Construct the path to the directory for cache files, which is:
259 ~/Library/Caches/org.aegidian.oolite/
260 or
261 ~/GNUStep/Library/Caches/org.aegidian.oolite/
262 In addition to generally being the right place to put caches,
263 ~/Library/Caches has the particular advantage of not being indexed by
264 Spotlight or backed up by Time Machine.
265 */
266 NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
267 if (![self directoryExists:cachePath create:create])
268 return nil;
269
270#if !OOLITE_MAC_OS_X
271 // the old cache file on GNUstep was one level up, so remove it if it exists
272 [[NSFileManager defaultManager] removeFileAtPath:[cachePath stringByAppendingPathComponent:@"Oolite-cache.plist"] handler:nil];
273#endif
274
275 cachePath = [cachePath stringByAppendingPathComponent:@"org.aegidian.oolite"];
276 if (![self directoryExists:cachePath create:create])
277 return nil;
278 return cachePath;
279}
280
281@end
282
283@implementation OOCacheManager (Private)
284
286{
287 NSDictionary* cache = nil;
288 NSString* cacheVersion = nil;
289 NSString* ooliteVersion = nil;
290 NSData* endianTag = nil;
291 NSNumber* formatVersion = nil;
292 BOOL accept = YES;
293 uint64_t endianTagValue = 0;
294
295 ooliteVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
296
297 [self clear];
298
299 cache = [self loadDict];
300 if (cache != nil) {
301 // We have a cache
302 OOLog(kOOLogDataCacheFound, @"%@", @"Found data cache.");
304
305 cacheVersion = [cache objectForKey:kCacheKeyVersion];
306 if (![cacheVersion isEqual:ooliteVersion]) {
307 OOLog(kOOLogDataCacheRebuild, @"Data cache version (%@) does not match Oolite version (%@), rebuilding cache.", cacheVersion, ooliteVersion);
308 accept = NO;
309 }
310
311 formatVersion = [cache objectForKey:kCacheKeyFormatVersion];
312 if (accept && [formatVersion unsignedIntValue] != kFormatVersionValue) {
313 OOLog(kOOLogDataCacheRebuild, @"Data cache format (%@) is not supported format (%zu), rebuilding cache.", formatVersion, kFormatVersionValue);
314 accept = NO;
315 }
316
317 if (accept) {
318 endianTag = [cache objectForKey:kCacheKeyEndianTag];
319 if (![endianTag isKindOfClass:[NSData class]] || [endianTag length] != sizeof endianTagValue) {
320 OOLog(kOOLogDataCacheRebuild, @"%@", @"Data cache endian tag is invalid, rebuilding cache.");
321 accept = NO;
322 } else {
323 endianTagValue = *(const uint64_t*)[endianTag bytes];
324 if (endianTagValue != kEndianTagValue) {
325 OOLog(kOOLogDataCacheRebuild, @"%@", @"Data cache endianness is inappropriate for this system, rebuilding cache.");
326 accept = NO;
327 }
328 }
329 }
330
331 if (accept) {
332 // We have a cache, and it's the right format.
333 [self buildCachesFromDictionary:[cache objectForKey:kCacheKeyCaches]];
334 }
335
337 } else {
338 // No cache
339 OOLog(kOOLogDataCacheNotFound, @"%@", @"No data cache found, starting from scratch.");
340 }
341
342 // If loading failed, or there was a version or endianness conflict
343 if (_caches == nil)
344 _caches = [[NSMutableDictionary alloc] init];
345 [self markClean];
346}
347
348- (void)write
349{
350 NSMutableDictionary* newCache = nil;
351 NSString* ooliteVersion = nil;
352 NSData* endianTag = nil;
353 NSNumber* formatVersion = nil;
354 NSDictionary* pListRep = nil;
355 uint64_t endianTagValue = kEndianTagValue;
356
357 if (_caches == nil)
358 return;
359 if (_scheduledWrite != nil)
360 return;
361
362#if PROFILE_WRITES
364#endif
365
366#if WRITE_ASYNC
367 OOLog(@"dataCache.willWrite", @"%@", @"Scheduling data cache write.");
368#else
369 OOLog(@"dataCache.willWrite", @"%@", @"About to write cache.");
370#endif
371
372 ooliteVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
373 endianTag = [NSData dataWithBytes:&endianTagValue length:sizeof endianTagValue];
374 formatVersion = [NSNumber numberWithUnsignedInt:kFormatVersionValue];
375
376 pListRep = [self dictionaryOfCaches];
377 if (ooliteVersion == nil || endianTag == nil || formatVersion == nil || pListRep == nil) {
378 OOLog(@"dataCache.cantWrite", @"%@", @"Failed to write data cache -- prerequisites not fulfilled. This is an internal error, please report it.");
379 return;
380 }
381
382 newCache = [NSMutableDictionary dictionaryWithCapacity:4];
383 [newCache setObject:ooliteVersion forKey:kCacheKeyVersion];
384 [newCache setObject:formatVersion forKey:kCacheKeyFormatVersion];
385 [newCache setObject:endianTag forKey:kCacheKeyEndianTag];
386 [newCache setObject:pListRep forKey:kCacheKeyCaches];
387
388#if PROFILE_WRITES && !WRITE_ASYNC
389 OOTimeDelta prepareT = [stopwatch reset];
390#endif
391
392#if WRITE_ASYNC
393 NSDictionary* cacheData = newCache;
394 _scheduledWrite = [[OOAsyncCacheWriter alloc] initWithCacheContents:cacheData];
395
396#if PROFILE_WRITES
397 OOTimeDelta endT = [stopwatch reset];
398 OOLog(@"dataCache.profile", @"Time to prepare cache data: %g seconds.", endT);
399#endif
400
402 priority:kOOAsyncPriorityLow];
403#else
404#if PROFILE_WRITES
405 OOLog(@"dataCache.profile", @"Time to prepare cache data: %g seconds.", prepareT);
406#endif
407
408 if ([self writeDict:newCache]) {
409 [self markClean];
410 OOLog(kOOLogDataCacheWriteSuccess, @"%@", @"Wrote data cache.");
411 } else {
412 OOLog(kOOLogDataCacheWriteFailed, @"%@", @"Failed to write data cache.");
413 }
414#endif
415}
416
417- (void)clear
418{
419 [_caches release];
420 _caches = nil;
421}
422
423- (BOOL)dirty
424{
425 return _dirty;
426}
427
429{
430 _dirty = NO;
431}
432
433- (NSDictionary*)loadDict
434{
435 NSString* path = nil;
436 NSData* data = nil;
437 NSString* errorString = nil;
438 id contents = nil;
439
440 path = [self cachePathCreatingIfNecessary:NO];
441 if (path == nil)
442 return nil;
443
444 @try {
445 data = [NSData dataWithContentsOfFile:path];
446 if (data == nil)
447 return nil;
448
449 contents = [NSPropertyListSerialization propertyListFromData:data
450 mutabilityOption:NSPropertyListImmutable
451 format:NULL
452 errorDescription:&errorString];
453 }
454 @catch (NSException* exception) {
455 errorString = [exception reason];
456 contents = nil;
457 }
458
459 if (errorString != nil) {
460 OOLog(@"dataCache.badData", @"Could not read data cache: %@", errorString);
461#if OOLITE_RELEASE_PLIST_ERROR_STRINGS
462 [errorString release];
463#endif
464 return nil;
465 }
466 if (![contents isKindOfClass:[NSDictionary class]])
467 return nil;
468
469 return contents;
470}
471
472- (BOOL)writeDict:(NSDictionary*)inDict
473{
474 NSString* path = nil;
475 NSData* plist = nil;
476 NSString* errorDesc = nil;
477
478 path = [self cachePathCreatingIfNecessary:YES];
479 if (path == nil)
480 return NO;
481
482#if PROFILE_WRITES
484#endif
485
486 plist = [NSPropertyListSerialization dataFromPropertyList:inDict format:CACHE_PLIST_FORMAT errorDescription:&errorDesc];
487 if (plist == nil) {
488#if OOLITE_RELEASE_PLIST_ERROR_STRINGS
489 [errorDesc autorelease];
490#endif
491 OOLog(kOOLogDataCacheSerializationError, @"Could not convert data cache to property list data: %@", errorDesc);
492 return NO;
493 }
494
495#if PROFILE_WRITES
496 OOTimeDelta serializeT = [stopwatch reset];
497#endif
498
499 BOOL result = [plist writeToFile:path atomically:NO];
500
501#if PROFILE_WRITES
502 OOTimeDelta writeT = [stopwatch reset];
503
504 OOLog(@"dataCache.profile", @"Time to serialize cache: %g seconds. Time to write data: %g seconds.", serializeT, writeT);
505#endif
506
507#if WRITE_ASYNC
508 DESTROY(_scheduledWrite);
509#endif
510 return result;
511}
512
513- (void)buildCachesFromDictionary:(NSDictionary*)inDict
514{
515 id key = nil;
516 id value = nil;
517 NSMutableDictionary* cache = nil;
518
519 if (inDict == nil)
520 return;
521
522 [_caches release];
523 _caches = [[NSMutableDictionary alloc] initWithCapacity:[inDict count]];
524
525 foreachkey(key, inDict)
526 {
527 value = [inDict oo_dictionaryForKey:key];
528 if (value != nil) {
529 cache = [NSMutableDictionary dictionaryWithDictionary:value];
530 if (cache != nil) {
531 [_caches setObject:cache forKey:key];
532 }
533 }
534 }
535}
536
537- (NSDictionary*)dictionaryOfCaches
538{
539 return [OODeepCopy(_caches) autorelease];
540}
541
542- (BOOL)directoryExists:(NSString*)inPath create:(BOOL)inCreate
543{
544 BOOL exists, directory;
545 NSFileManager* fmgr = [NSFileManager defaultManager];
546
547 exists = [fmgr fileExistsAtPath:inPath isDirectory:&directory];
548
549 if (exists && !directory) {
550 OOLog(kOOLogDataCacheBuildPathError, @"Expected %@ to be a folder, but it is a file.", inPath);
551 return NO;
552 }
553 if (!exists) {
554 if (!inCreate)
555 return NO;
556 if (![fmgr oo_createDirectoryAtPath:inPath attributes:nil]) {
557 OOLog(kOOLogDataCacheBuildPathError, @"Could not create folder %@.", inPath);
558 return NO;
559 }
560 }
561
562 return YES;
563}
564
565#if OOLITE_MAC_OS_X
566
567- (NSString*)cachePathCreatingIfNecessary:(BOOL)create
568{
569 NSString* cachePath = [self cacheDirectoryPathCreatingIfNecessary:create];
570 return [cachePath stringByAppendingPathComponent:@"Data Cache.plist"];
571}
572
573#else
574
575- (NSString*)cachePathCreatingIfNecessary:(BOOL)create
576{
577 NSString* cachePath = [self cacheDirectoryPathCreatingIfNecessary:create];
578 return [cachePath stringByAppendingPathComponent:@"Oolite-cache.plist"];
579}
580
581#endif
582
583@end
584
585@implementation OOCacheManager (Singleton)
586
587/* Canonical singleton boilerplate.
588 See Cocoa Fundamentals Guide: Creating a Singleton Instance.
589 See also +sharedCache above.
590
591 NOTE: assumes single-threaded access.
592*/
593
594+ (id)allocWithZone:(NSZone*)inZone
595{
596 if (sSingleton == nil) {
597 sSingleton = [super allocWithZone:inZone];
598 return sSingleton;
599 }
600 return nil;
601}
602
603- (id)copyWithZone:(NSZone*)inZone
604{
605 return self;
606}
607
609{
610 return self;
611}
612
613- (NSUInteger)retainCount
614{
615 return UINT_MAX;
616}
617
618- (void)release
619{
620}
621
623{
624 return self;
625}
626
627@end
628
629#if WRITE_ASYNC
630@implementation OOAsyncCacheWriter
631
632- (id)initWithCacheContents:(NSDictionary*)cacheContents
633{
634 if ((self = [super init])) {
636 if (_cacheContents == nil) {
637 [self release];
638 self = nil;
639 }
640 }
641
642 return self;
643}
644
645- (void)dealloc
646{
648
649 [super dealloc];
650}
651
653{
654 if ([[OOCacheManager sharedCache] writeDict:_cacheContents]) {
655 OOLog(kOOLogDataCacheWriteSuccess, @"%@", @"Wrote data cache.");
656 } else {
657 OOLog(kOOLogDataCacheWriteFailed, @"%@", @"Failed to write data cache.");
658 }
660}
661
663{
664 // Don't need to do anything, but this needs to be here so we can wait on it.
665}
666
667@end
668#endif // WRITE_ASYNC
static NSString *const kCacheKeyEndianTag
static NSString *const kOOLogDataCacheWriteSuccess
static NSString *const kOOLogDataCacheBuildPathError
static NSString *const kOOLogDataCacheRetrieveSuccess
static NSString *const kOOLogDataCacheClearSuccess
static NSString *const kOOLogDataCacheWriteFailed
static NSString *const kOOLogDataCacheRetrieveFailed
static NSString *const kOOLogDataCacheSetFailed
@ kFormatVersionValue
@ kEndianTagValue
static NSString *const kCacheKeyCaches
static NSString *const kOOLogDataCacheRebuild
static NSString *const kOOLogDataCacheSerializationError
static NSString *const kCacheKeyVersion
static NSString *const kOOLogDataCacheRemoveSuccess
static NSString *const kOOLogDataCacheNotFound
static NSString *const kCacheKeyFormatVersion
static NSString *const kOOLogDataCacheSetSuccess
static NSString *const kOOLogDataCacheFound
#define DESTROY(x)
#define foreachkey(VAR, DICT)
#define EXPECT_NOT(x)
#define OODebugLog(class, format,...)
Definition OOLogging.h:156
#define OOLogOutdentIf(class)
Definition OOLogging.h:112
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define OOLogIndentIf(class)
Definition OOLogging.h:107
static OONullTexture * sSingleton
return nil
double OOTimeDelta
Definition OOTypes.h:193
NSDictionary * dictionaryOfCaches()
NSDictionary * _cacheContents
BOOL addTask:priority:(id< OOAsyncWorkTask > task,[priority] OOAsyncWorkPriority priority)
void waitForTaskToComplete:(id< OOAsyncWorkTask > task)
OOAsyncWorkManager * sharedAsyncWorkManager()
NSMutableDictionary * _caches
void buildCachesFromDictionary:(NSDictionary *inDict)
NSString * cacheDirectoryPathCreatingIfNecessary:(BOOL create)
NSString * cachePathCreatingIfNecessary:(BOOL inCreate)
OOCacheManager * sharedCache()
NSDictionary * loadDict()
NSString * description()
NSDictionary * dictionaryOfCaches()