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
|
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
//using System.Runtime.Serialization.Formatters.Binary;
namespace FlickrNet
{
/// <summary>
/// A threadsafe cache that is backed by disk storage.
///
/// All public methods that read or write state must be
/// protected by the lockFile. Private methods should
/// not acquire the lockFile as it is not reentrant.
/// </summary>
internal sealed class PersistentCache
{
// The in-memory representation of the cache.
// Use SortedList instead of Hashtable only to maintain backward
// compatibility with previous serialization scheme. If we
// abandon backward compatibility, we should switch to Hashtable.
private Hashtable dataTable = new Hashtable();
private readonly CacheItemPersister persister;
// true if dataTable contains changes vs. on-disk representation
private bool dirty;
// The persistent file representation of the cache.
private readonly FileInfo dataFile;
private DateTime timestamp; // last-modified time of dataFile when cache data was last known to be in sync
private long length; // length of dataFile when cache data was last known to be in sync
private long maxSize;
// The file-based mutex. Named (dataFile.FullName + ".lock")
private readonly LockFile lockFile;
public PersistentCache(string filename, CacheItemPersister persister, long maxSize)
{
this.maxSize = maxSize;
this.persister = persister;
this.dataFile = new FileInfo(filename);
this.lockFile = new LockFile(filename + ".lock");
}
/// <summary>
/// Return all items in the cache. Works similarly to
/// ArrayList.ToArray(Type).
/// </summary>
public ICacheItem[] ToArray(Type valueType)
{
using (lockFile.Acquire())
{
Refresh();
string[] keys;
Array values;
InternalGetAll(valueType, out keys, out values);
return (ICacheItem[]) values;
}
}
public int Count
{
get
{
using (lockFile.Acquire())
{
Refresh();
return dataTable.Count;
}
}
}
/// <summary>
/// Gets the maximum size for the persistent cache.
/// </summary>
public long MaxSize
{
get { return maxSize; }
}
/// <summary>
/// Gets or sets cache values.
/// </summary>
public ICacheItem this[string key]
{
get
{
if (key == null)
throw new ArgumentNullException("key");
using (lockFile.Acquire())
{
Refresh();
return InternalGet(key);
}
}
set
{
if (key == null)
throw new ArgumentNullException("key");
ICacheItem oldItem;
using (lockFile.Acquire())
{
Refresh();
oldItem = InternalSet(key, value);
Persist();
}
if (oldItem != null)
oldItem.OnItemFlushed();
}
}
public ICacheItem Get(string key, TimeSpan maxAge, bool removeIfExpired)
{
Debug.Assert(maxAge > TimeSpan.Zero || maxAge == TimeSpan.MinValue, "maxAge should be positive, not negative");
ICacheItem item;
bool expired;
using (lockFile.Acquire())
{
Refresh();
item = InternalGet(key);
expired = item != null && Expired(item.CreationTime, maxAge);
if (expired)
{
if (removeIfExpired)
{
item = RemoveKey(key);
Persist();
}
else
item = null;
}
}
if (expired && removeIfExpired)
item.OnItemFlushed();
return expired ? null : item;
}
public void Flush()
{
Shrink(0);
}
public void Shrink(long size)
{
if (size < 0)
throw new ArgumentException("Cannot shrink to a negative size", "size");
ArrayList flushed = new ArrayList();
using (lockFile.Acquire())
{
Refresh();
string[] keys;
Array values;
InternalGetAll(typeof(ICacheItem), out keys, out values);
long totalSize = 0;
foreach (ICacheItem cacheItem in values)
totalSize += cacheItem.FileSize;
for (int i = 0; i < keys.Length; i++)
{
if (totalSize <= size)
break;
ICacheItem cacheItem = (ICacheItem) values.GetValue(i);
totalSize -= cacheItem.FileSize;
flushed.Add(RemoveKey(keys[i]));
}
Persist();
}
foreach (ICacheItem flushedItem in flushed)
{
Debug.Assert(flushedItem != null, "Flushed item was null--programmer error");
if (flushedItem != null)
flushedItem.OnItemFlushed();
}
}
private bool Expired(DateTime test, TimeSpan age)
{
if (age == TimeSpan.MinValue)
return true;
else if (age == TimeSpan.MaxValue)
return false;
else
return test < DateTime.UtcNow - age;
}
private void InternalGetAll(Type valueType, out string[] keys, out Array values)
{
if (!typeof(ICacheItem).IsAssignableFrom(valueType))
throw new ArgumentException("Type " + valueType.FullName + " does not implement ICacheItem", "valueType");
keys = (string[]) new ArrayList(dataTable.Keys).ToArray(typeof(string));
values = Array.CreateInstance(valueType, keys.Length);
for (int i = 0; i < keys.Length; i++)
values.SetValue(dataTable[keys[i]], i);
Array.Sort(values, keys, new CreationTimeComparer());
}
private ICacheItem InternalGet(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return (ICacheItem) dataTable[key];
}
/// <returns>The old value associated with <c>key</c>, if any.</returns>
private ICacheItem InternalSet(string key, ICacheItem value)
{
if (key == null)
throw new ArgumentNullException("key");
ICacheItem flushedItem;
flushedItem = RemoveKey(key);
if (value != null) // don't ever let nulls get in
dataTable[key] = value;
dirty = dirty || !object.ReferenceEquals(flushedItem, value);
return flushedItem;
}
private ICacheItem RemoveKey(string key)
{
ICacheItem cacheItem = (ICacheItem) dataTable[key];
if (cacheItem != null)
{
dataTable.Remove(key);
dirty = true;
}
return cacheItem;
}
private void Refresh()
{
Debug.Assert(!dirty, "Refreshing even though cache is dirty");
DateTime newTimestamp = DateTime.MinValue;
long newLength = -1;
if (dataFile.Exists)
{
dataFile.Refresh();
newTimestamp = dataFile.LastWriteTime;
newLength = dataFile.Length;
}
if (timestamp != newTimestamp || length != newLength)
{
// file changed
if (!dataFile.Exists)
dataTable.Clear();
else
{
Debug.WriteLine("Loading cache from disk");
using (FileStream inStream = dataFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
dataTable = Load(inStream);
}
}
}
timestamp = newTimestamp;
length = newLength;
dirty = false;
}
private void Persist()
{
if (!dirty)
return;
Debug.WriteLine("Saving cache to disk");
using (FileStream outStream = dataFile.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
Store(outStream, dataTable);
}
dataFile.Refresh();
timestamp = dataFile.LastWriteTime;
length = dataFile.Length;
dirty = false;
}
private Hashtable Load(Stream s)
{
Hashtable table = new Hashtable();
int itemCount = Utils.ReadInt32(s);
for (int i = 0; i < itemCount; i++)
{
try
{
string key = Utils.ReadString(s);
ICacheItem val = persister.Read(s);
if( val == null ) // corrupt cache file
return table;
table[key] = val;
}
catch(IOException)
{
return table;
}
}
return table;
}
private void Store(Stream s, Hashtable table)
{
Utils.WriteInt32(s, table.Count);
foreach (DictionaryEntry entry in table)
{
Utils.WriteString(s, (string) entry.Key);
persister.Write(s, (ICacheItem) entry.Value);
}
}
private class CreationTimeComparer : IComparer
{
public int Compare(object x, object y)
{
return ((ICacheItem)x).CreationTime.CompareTo(((ICacheItem)y).CreationTime);
}
}
}
}
|