OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import 'dart:async'; |
| 6 import 'dart:io'; |
| 7 import 'logger.dart'; |
| 8 import 'try.dart'; |
| 9 |
| 10 typedef Future<String> FetchDataFunction(); |
| 11 typedef Future<String> WithCacheFunction(FetchDataFunction fetchData, |
| 12 [String key]); |
| 13 typedef WithCacheFunction CreateCacheFunction( |
| 14 {String overrideKey, Duration duration}); |
| 15 |
| 16 CreateCacheFunction initCache(Uri baseUri, [Logger logger]) { |
| 17 final cache = new Cache(baseUri, logger); |
| 18 logger ??= new StdOutLogger(Level.warning); |
| 19 |
| 20 return ({String overrideKey, Duration duration}) { |
| 21 if (duration == null) { |
| 22 duration = new Duration(hours: 24); |
| 23 } |
| 24 |
| 25 return (FetchDataFunction call, [String key]) async { |
| 26 if (overrideKey != null) { |
| 27 key = overrideKey; |
| 28 } |
| 29 |
| 30 if (key == null || key.isEmpty) { |
| 31 logger.warning("Key is null or empty - cannot cache result"); |
| 32 } else { |
| 33 // format key |
| 34 key = key.replaceAll("/", "_").replaceAll(".", "_"); |
| 35 |
| 36 Try<CacheResult> readResult = await cache.read(key, duration); |
| 37 if (!readResult.isError && readResult.value.hasResult) { |
| 38 logger.debug("Found key $key in cache"); |
| 39 return readResult.value.result; |
| 40 } |
| 41 if (readResult.isError) { |
| 42 logger.error("Error when reading from cache", readResult.error, |
| 43 readResult.stackTrace); |
| 44 } |
| 45 } |
| 46 |
| 47 logger.debug("Could not find key $key in cache"); |
| 48 |
| 49 // we have to make a call |
| 50 String result = await call(); |
| 51 |
| 52 // insert/update the cache |
| 53 if (key != null && !key.isEmpty) { |
| 54 await cache.write(key, result); |
| 55 } |
| 56 |
| 57 return result; |
| 58 }; |
| 59 }; |
| 60 } |
| 61 |
| 62 CreateCacheFunction noCache() { |
| 63 return ({String overrideKey, Duration duration}) { |
| 64 return (FetchDataFunction fetchData, [String key]) { |
| 65 return fetchData(); |
| 66 }; |
| 67 }; |
| 68 } |
| 69 |
| 70 /// Simple cache for caching data. |
| 71 class Cache { |
| 72 // TODO(mkroghj) use this instead of cache.dart |
| 73 Uri base; |
| 74 Logger logger; |
| 75 |
| 76 Cache(this.base, this.logger); |
| 77 |
| 78 Map<String, String> memoryCache = <String, String>{}; |
| 79 |
| 80 /// Checks if key [path] is in cache |
| 81 Future<bool> containsKey(String path, [Duration duration]) async { |
| 82 if (memoryCache.containsKey(path)) return true; |
| 83 |
| 84 File file = new File.fromUri(base.resolve(path)); |
| 85 if (await file.exists()) { |
| 86 return duration == null |
| 87 ? true |
| 88 : new DateTime.now().difference(await file.lastModified()) <= |
| 89 duration; |
| 90 } |
| 91 |
| 92 return false; |
| 93 } |
| 94 |
| 95 /// Try reading [path] from cache |
| 96 Future<Try<CacheResult>> read(String path, [Duration duration]) async { |
| 97 if (memoryCache.containsKey(path)) { |
| 98 logger.debug('Found $path in memory cache'); |
| 99 return new Try.from(new CacheResult(memoryCache[path])); |
| 100 } |
| 101 |
| 102 File file = new File.fromUri(base.resolve(path)); |
| 103 |
| 104 if (!(await file.exists())) { |
| 105 logger.debug('Could not find file $path in file cache'); |
| 106 return new Try.from(new CacheResult.noResult()); |
| 107 } |
| 108 |
| 109 if (duration != null && |
| 110 new DateTime.now().difference(await file.lastModified()) > duration) { |
| 111 logger.debug('File $path was found but the information is too stale,' |
| 112 'for the duration: $duration'); |
| 113 return new Try.from(new CacheResult.noResult()); |
| 114 } |
| 115 |
| 116 return tryStartAsync(() async { |
| 117 logger.debug('Found $path in file cache'); |
| 118 var text = await file.readAsString(); |
| 119 memoryCache[path] = text; |
| 120 return new CacheResult(text); |
| 121 }); |
| 122 } |
| 123 |
| 124 /// Store [text] as the cache data for [path]. |
| 125 Future write(String path, String text) async { |
| 126 logger.debug('Creating $path in file cache'); |
| 127 File file = new File.fromUri(base.resolve(path)); |
| 128 if (!await file.exists()) { |
| 129 await file.create(recursive: true); |
| 130 } |
| 131 await file.writeAsString(text); |
| 132 memoryCache[path] = text; |
| 133 } |
| 134 |
| 135 /// Clears the cache at [baseUri] |
| 136 Future clearCache(Uri baseUri) async { |
| 137 await new Directory(baseUri.toFilePath()).delete(recursive: true); |
| 138 } |
| 139 } |
| 140 |
| 141 class CacheResult { |
| 142 final bool hasResult; |
| 143 final String result; |
| 144 |
| 145 CacheResult.noResult() |
| 146 : hasResult = false, |
| 147 result = null {} |
| 148 |
| 149 CacheResult(this.result) : hasResult = true {} |
| 150 } |
OLD | NEW |