Repository navigation
Expand file tree
/
Copy pathDataCache.cs
More file actions
256 lines (220 loc) · 7.94 KB
/
Copy pathDataCache.cs
File metadata and controls
256 lines (220 loc) · 7.94 KB
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
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using IBM.Watson.DeveloperCloud.Logging;
namespace IBM.Watson.DeveloperCloud.Utilities
{
/// <summary>
/// This class manages a cache of binary data by ID.
/// </summary>
public class DataCache
{
#region Private Data
private string m_CachePath = null;
private long m_MaxCacheSize = -1;
private double m_MaxCacheAge = 0;
private long m_CurrentCacheSize = 0;
private class CacheItem
{
public string Path { get; set; }
public string Id { get; set; }
public DateTime Time { get; set; }
public byte[] Data { get; set; }
};
private Dictionary<string, CacheItem> m_Cache = new Dictionary<string, CacheItem>();
#endregion
/// <summary>
/// DataCache constructor.
/// </summary>
/// <param name="cacheName">The name of the cache.</param>
/// <param name="maxCacheSize">Maximum cache size in bytes.</param>
/// <param name="maxCacheAge">Maximum age of a cache item in hours.</param>
public DataCache(string cacheName, long maxCacheSize = 1024 * 1024 * 50, double maxCacheAge = 24 * 7)
{
Initialize(cacheName, maxCacheSize, maxCacheAge);
}
/// <summary>
/// Initializes this DataCache object.
/// </summary>
/// <param name="cacheName">The name of the cache.</param>
/// <param name="maxCacheSize">Maximum cache size in bytes.</param>
/// <param name="maxCacheAge">Maximum age of a cache item in hours.</param>
public void Initialize(string cacheName, long maxCacheSize, double maxCacheAge)
{
if (string.IsNullOrEmpty(cacheName))
throw new ArgumentNullException("cacheName");
cacheName = cacheName.Replace('/', '_');
m_MaxCacheSize = maxCacheSize;
m_MaxCacheAge = maxCacheAge;
m_CachePath = Application.persistentDataPath + Constants.Path.CACHE_FOLDER + "/" + cacheName + "/";
if (!Directory.Exists(m_CachePath))
Directory.CreateDirectory(m_CachePath);
foreach (var f in Directory.GetFiles(m_CachePath))
{
DateTime lastWrite = File.GetLastAccessTime(f);
double age = (DateTime.Now - lastWrite).TotalHours;
if (age < m_MaxCacheAge)
{
CacheItem item = new CacheItem();
item.Path = f;
item.Id = Path.GetFileNameWithoutExtension(f);
item.Time = lastWrite;
item.Data = null;
m_Cache[item.Id] = item;
m_CurrentCacheSize += (new FileInfo(f)).Length;
}
else
{
Log.Debug("DataCache", "Removing aged cache item {0}", f);
File.Delete(f);
}
}
}
/// <summary>
/// Find a data object by ID.
/// </summary>
/// <param name="id">The ID to find.</param>
/// <returns>The cached data, or null if not found.</returns>
public byte[] Find(string id)
{
if (!string.IsNullOrEmpty(id))
{
id = id.Replace('/', '_');
CacheItem item = null;
if (m_Cache.TryGetValue(id, out item))
{
item.Time = DateTime.Now;
File.SetLastWriteTime(item.Path, item.Time);
if (item.Data == null)
{
item.Data = File.ReadAllBytes(item.Path);
}
return item.Data;
}
}
return null;
}
public bool IsCached(string id)
{
bool isCached = false;
if (!string.IsNullOrEmpty(id))
{
id = id.Replace('/', '_');
CacheItem item = null;
if (m_Cache.TryGetValue(id, out item))
{
isCached = File.Exists(item.Path);
}
}
return isCached;
}
/// <summary>
/// Save data into the cache by ID.
/// </summary>
/// <param name="id">The ID to save.</param>
/// <param name="data">The data of the object to save.</param>
public void Save(string id, byte[] data)
{
if (data != null && data.Length > 0)
{
id = id.Replace('/', '_');
if (m_Cache.ContainsKey(id))
{
Log.Debug("DataCache", "Has same key in the cache. Flushing old one: {0}", id);
Flush(id);
}
CacheItem item = new CacheItem();
item.Path = m_CachePath + id + ".bytes";
item.Id = id;
item.Time = DateTime.Now;
item.Data = data;
File.WriteAllBytes(item.Path, data);
m_CurrentCacheSize += item.Data.Length;
m_Cache[id] = item;
while (m_CurrentCacheSize > m_MaxCacheSize)
FlushOldest();
}
else
{
Log.Error("DataCache", "Empty data came to the cache, couldn't cache any null data");
}
}
/// <summary>
/// Flush a specific item from the cache.
/// </summary>
/// <param name="id">The ID of the object to flush.</param>
public void Flush(string id)
{
id = id.Replace('/', '_');
CacheItem item = null;
if (m_Cache.TryGetValue(id, out item))
{
Log.Debug("DataCache", "Flushing {0} from cache.", item.Path);
if (item.Data != null)
m_CurrentCacheSize -= item.Data.Length;
else
m_CurrentCacheSize -= (new FileInfo(item.Path)).Length;
File.Delete(item.Path);
m_Cache.Remove(id);
}
}
/// <summary>
/// Flush any aged out data from the cache.
/// </summary>
public void FlushAged()
{
List<CacheItem> flush = new List<CacheItem>();
foreach (var kp in m_Cache)
{
double age = (DateTime.Now - kp.Value.Time).TotalHours;
if (age > m_MaxCacheAge)
flush.Add(kp.Value);
}
foreach (var item in flush)
Flush(item.Id);
}
/// <summary>
/// Flush the oldest item from the cache.
/// </summary>
public void FlushOldest()
{
CacheItem oldest = null;
foreach (var kp in m_Cache)
{
if (oldest == null || kp.Value.Time < oldest.Time)
oldest = kp.Value;
}
if (oldest != null)
{
Flush(oldest.Id);
}
}
/// <summary>
/// Flush all data from the cache.
/// </summary>
public void Flush()
{
foreach (var kp in m_Cache)
File.Delete(kp.Value.Path);
m_Cache.Clear();
}
}
}