Repository navigation
Expand file tree
/
Copy pathCacheService.js
More file actions
367 lines (321 loc) · 9.44 KB
/
Copy pathCacheService.js
File metadata and controls
367 lines (321 loc) · 9.44 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
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
/**
* Cache Management Module
* Consolidated caching logic for performance optimization
*
* Handles:
* - Sender stats caching
* - Message template caching
* - Label data caching
* - Sheet reference caching
*/
// ===== SENDER CACHE =====
/**
* Get cached sender statistics
* @param {string} email - Sender email
* @return {Object|null} Cached data or null
*/
function getCachedSenderStats(email) {
if (!isValidEmail(email)) return null;
var sheet = getCachedSheet(CONFIG.CACHE_SHEET_NAME);
if (!sheet) return null;
try {
var finder = sheet.createTextFinder(email).matchEntireCell(true);
var result = finder.findNext();
if (result) {
var row = result.getRow();
var data = sheet.getRange(row, 1, 1, 4).getValues()[0];
var lastUpdate = new Date(data[3]);
var now = new Date();
// Check if cache is still valid
if (now.getTime() - lastUpdate.getTime() < CONFIG.CACHE_DURATION_MS) {
var cached = {
totalCount: data[1],
labelMap: JSON.parse(data[2])
};
if (CONFIG.ENABLE_CACHE_LOGGING) {
logCacheOperation("HIT", email, { type: "sender", source: "sheet" });
}
return cached;
} else {
if (CONFIG.ENABLE_CACHE_LOGGING) {
logCacheOperation("EXPIRED", email, { type: "sender", age: now.getTime() - lastUpdate.getTime() });
}
}
}
} catch (e) {
logError("getCachedSenderStats", e);
}
if (CONFIG.ENABLE_CACHE_LOGGING) {
logCacheOperation("MISS", email, { type: "sender" });
}
return null;
}
/**
* Update cached sender statistics
* @param {string} email - Sender email
* @param {number} totalCount - Total thread count
* @param {Object} labelMap - Label frequency map
* @return {boolean} Success status
*/
function updateCachedSenderStats(email, totalCount, labelMap) {
if (!isValidEmail(email)) return false;
var sheet = getCachedSheet(CONFIG.CACHE_SHEET_NAME);
if (!sheet) return false;
try {
var finder = sheet.createTextFinder(email).matchEntireCell(true);
var result = finder.findNext();
var jsonMap = JSON.stringify(labelMap);
var now = new Date();
if (result) {
// Update existing row
var row = result.getRow();
sheet.getRange(row, 2, 1, 3).setValues([[totalCount, jsonMap, now]]);
} else {
// Add new row
sheet.appendRow([email, totalCount, jsonMap, now]);
}
if (CONFIG.ENABLE_CACHE_LOGGING) {
safeLog("Cache", `Cache UPDATED for ${email}: ${totalCount} threads`);
}
return true;
} catch (e) {
logError("updateCachedSenderStats", e);
return false;
}
}
/**
* Clear cache for specific sender
* @param {string} email - Sender email
* @return {boolean} Success status
*/
function clearSenderCache(email) {
if (!isValidEmail(email)) return false;
var sheet = getCachedSheet(CONFIG.CACHE_SHEET_NAME);
if (!sheet) return false;
try {
var finder = sheet.createTextFinder(email).matchEntireCell(true);
var result = finder.findNext();
if (result) {
var row = result.getRow();
sheet.deleteRow(row);
safeLog("Cache", `Cache CLEARED for ${email}`);
return true;
}
} catch (e) {
logError("clearSenderCache", e);
}
return false;
}
/**
* Clear all sender caches (use with caution)
* @return {boolean} Success status
*/
function clearAllSenderCaches() {
var sheet = getCachedSheet(CONFIG.CACHE_SHEET_NAME);
if (!sheet) return false;
try {
// Keep header row, delete all data rows
var lastRow = sheet.getLastRow();
if (lastRow > 1) {
sheet.deleteRows(2, lastRow - 1);
}
safeLog("Cache", "All sender caches CLEARED");
return true;
} catch (e) {
logError("clearAllSenderCaches", e);
return false;
}
}
// ===== MESSAGE CACHE =====
/** @type {Object} In-memory cache for messages */
var _messagesCache = null;
var _messagesCacheTime = 0;
/**
* Get cached messages from sheet
* @return {Object} Messages object
*/
function getCachedMessages() {
var now = new Date().getTime();
// Return in-memory cache if fresh
if (_messagesCache && (now - _messagesCacheTime) < CONFIG.MESSAGE_CACHE_DURATION_MS) {
if (CONFIG.ENABLE_CACHE_LOGGING) {
logCacheOperation("HIT", "MEMORY", { type: "messages" });
}
return _messagesCache;
}
var sheet = getCachedSheet(CONFIG.MESSAGES_SHEET_NAME);
if (!sheet) {
console.log("Messages sheet not found, using defaults");
return getDefaultMessages();
}
try {
var data = sheet.getDataRange().getValues();
var messages = {};
// Skip header row
for (var i = 1; i < data.length; i++) {
var row = data[i];
if (row[0] && row[1]) {
var key = row[0].toString().trim();
var value = row[1].toString().trim();
// Try to parse JSON values
try {
if (value.startsWith('[') || value.startsWith('{')) {
messages[key] = JSON.parse(value);
} else {
messages[key] = value;
}
} catch (e) {
messages[key] = value; // Keep as string if not valid JSON
}
}
}
_messagesCache = messages;
_messagesCacheTime = now;
if (CONFIG.ENABLE_CACHE_LOGGING) {
logCacheOperation("HIT", "SHEET", { type: "messages", count: Object.keys(messages).length });
}
return messages;
} catch (error) {
logError("getCachedMessages", error);
return getDefaultMessages();
}
}
/**
* Clear message cache (forces refresh on next call)
*/
function clearMessageCache() {
_messagesCache = null;
_messagesCacheTime = 0;
safeLog("Cache", "Message cache CLEARED");
}
// ===== LABEL CACHE =====
/**
* Cache label data in chunks for later use
* @param {Array} labels - Array of label objects
* @return {boolean} Success status
*/
function cacheLabelChunks(labels) {
try {
var cache = CacheService.getUserCache();
var labelDataKeyPrefix = 'labelChunk_';
var labelMetaKey = 'labelMeta';
var chunkSize = CONFIG.MAX_LABELS_DISPLAY || 1000;
// Store label NAMES, not the GmailLabel objects: JSON.stringify()
// of an Apps Script object does not round-trip to usable labels.
var labelNames = labels.map(function(l) {
return (l && typeof l.getName === "function") ? l.getName() : String(l);
});
var chunkCount = Math.ceil(labelNames.length / chunkSize);
for (var i = 0; i < chunkCount; i++) {
var chunk = labelNames.slice(i * chunkSize, (i + 1) * chunkSize);
cache.put(labelDataKeyPrefix + i, JSON.stringify(chunk), 1800); // 30 min
}
cache.put(labelMetaKey, chunkCount.toString(), 1800);
if (CONFIG.ENABLE_CACHE_LOGGING) {
safeLog("Cache", `Cached ${chunkCount} label chunks (${labels.length} labels)`);
}
return true;
} catch (e) {
logError("cacheLabelChunks", e);
return false;
}
}
/**
* Get cached label chunks
* @return {Array|null} Combined labels or null
*/
function getCachedLabelChunks() {
try {
var cache = CacheService.getUserCache();
var labelMetaKey = 'labelMeta';
var labelDataKeyPrefix = 'labelChunk_';
var chunkCountStr = cache.get(labelMetaKey);
if (!chunkCountStr) return null;
var chunkCount = parseInt(chunkCountStr, 10);
var allLabels = [];
for (var i = 0; i < chunkCount; i++) {
var chunk = cache.get(labelDataKeyPrefix + i);
if (chunk) {
allLabels = allLabels.concat(JSON.parse(chunk));
}
}
if (CONFIG.ENABLE_CACHE_LOGGING) {
safeLog("Cache", `Retrieved ${allLabels.length} labels from cache chunks`);
}
return allLabels.length > 0 ? allLabels : null;
} catch (e) {
logError("getCachedLabelChunks", e);
return null;
}
}
/**
* Clear label cache
*/
function clearLabelCache() {
try {
var cache = CacheService.getUserCache();
var labelMetaKey = 'labelMeta';
var labelDataKeyPrefix = 'labelChunk_';
var chunkCountStr = cache.get(labelMetaKey);
if (chunkCountStr) {
var chunkCount = parseInt(chunkCountStr, 10);
cache.remove(labelMetaKey);
for (var i = 0; i < chunkCount; i++) {
cache.remove(labelDataKeyPrefix + i);
}
}
safeLog("Cache", "Label cache CLEARED");
return true;
} catch (e) {
logError("clearLabelCache", e);
return false;
}
}
// ===== UTILITY CACHE FUNCTIONS =====
/**
* Get total cached label count
* @return {number|null} Label count or null
*/
function getCachedLabelCount() {
try {
var cache = CacheService.getUserCache();
var labelCountKey = 'totalLabelCount';
var count = cache.get(labelCountKey);
return count ? parseInt(count, 10) : null;
} catch (e) {
logError("getCachedLabelCount", e);
return null;
}
}
/**
* Update cached label count
* @param {number} count - New count
* @return {boolean} Success status
*/
function updateCachedLabelCount(count) {
try {
var cache = CacheService.getUserCache();
var labelCountKey = 'totalLabelCount';
cache.put(labelCountKey, count.toString(), 600); // 10 min
return true;
} catch (e) {
logError("updateCachedLabelCount", e);
return false;
}
}
/**
* Clear all user caches (comprehensive reset)
* @return {boolean} Success status
*/
function clearAllCaches() {
try {
var cache = CacheService.getUserCache();
cache.removeAll(cache.getKeys());
clearMessageCache();
safeLog("Cache", "ALL CACHES CLEARED");
return true;
} catch (e) {
logError("clearAllCaches", e);
return false;
}
}