-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
156 lines (134 loc) · 4.67 KB
/
background.js
File metadata and controls
156 lines (134 loc) · 4.67 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
// Background service worker — cache manager, rate limiter, account tracker
// API calls stay in content scripts (same-origin cookies); background coordinates.
(() => {
const LOG_PREFIX = '[FMC-BG]';
const MAX_CACHE_ENTRIES = 50;
const DEFAULT_BASELINE_TTL = 60000;
const DEFAULT_PROJECTED_TTL = 30000;
const MIN_API_INTERVAL = 2000;
// --- In-memory cache (lost on service worker termination — by design) ---
const cache = new Map(); // key -> { data, expires, lastAccess }
const apiCallLog = new Map(); // accountNum -> lastCallTimestamp
const tabAccounts = new Map(); // tabId -> accountNum
function log(...args) {
console.log(LOG_PREFIX, ...args);
}
// --- LRU eviction ---
function evictIfNeeded() {
if (cache.size <= MAX_CACHE_ENTRIES) return;
// Find least recently accessed
let oldestKey = null;
let oldestAccess = Infinity;
for (const [key, entry] of cache) {
if (entry.lastAccess < oldestAccess) {
oldestAccess = entry.lastAccess;
oldestKey = key;
}
}
if (oldestKey) cache.delete(oldestKey);
}
// --- Cache operations ---
function cacheGet(key) {
const entry = cache.get(key);
if (!entry) return { hit: false, data: null, age: 0 };
if (Date.now() > entry.expires) {
cache.delete(key);
return { hit: false, data: null, age: 0 };
}
entry.lastAccess = Date.now();
return { hit: true, data: entry.data, age: Date.now() - (entry.expires - entry.ttl) };
}
function cacheSet(key, data, ttl) {
const now = Date.now();
cache.set(key, { data, expires: now + ttl, ttl, lastAccess: now });
evictIfNeeded();
return { ok: true };
}
function cacheInvalidate(key, pattern) {
let cleared = 0;
if (key) {
if (cache.delete(key)) cleared++;
}
if (pattern) {
for (const k of cache.keys()) {
if (k.startsWith(pattern)) {
cache.delete(k);
cleared++;
}
}
}
return { ok: true, cleared };
}
// --- Rate limiting ---
function checkRateLimit(accountNum) {
const last = apiCallLog.get(accountNum) || 0;
const elapsed = Date.now() - last;
if (elapsed < MIN_API_INTERVAL) {
return { rateLimited: true, retryAfter: MIN_API_INTERVAL - elapsed };
}
apiCallLog.set(accountNum, Date.now());
return { rateLimited: false };
}
// --- Account tracking ---
function handleAccountChanged(tabId, accountNum, previousAccountNum) {
tabAccounts.set(tabId, accountNum);
if (previousAccountNum && previousAccountNum !== accountNum) {
// Invalidate cache for old account
cacheInvalidate(null, `baseline:${previousAccountNum}`);
cacheInvalidate(null, `projected:${previousAccountNum}`);
log('Account switched', previousAccountNum, '->', accountNum, '- cache cleared');
}
return { ok: true };
}
// --- Message router ---
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (!msg || !msg._fmc) return false;
const tabId = sender.tab ? sender.tab.id : -1;
switch (msg.type) {
case 'CACHE_GET':
sendResponse(cacheGet(msg.payload.key));
return false;
case 'CACHE_SET':
sendResponse(cacheSet(msg.payload.key, msg.payload.data, msg.payload.ttl || DEFAULT_BASELINE_TTL));
return false;
case 'CACHE_INVALIDATE':
sendResponse(cacheInvalidate(msg.payload.key, msg.payload.pattern));
return false;
case 'ACCOUNT_CHANGED':
sendResponse(handleAccountChanged(tabId, msg.payload.accountNum, msg.payload.previousAccountNum));
return false;
case 'LOG_API_CALL':
sendResponse(checkRateLimit(msg.payload.accountNum));
return false;
case 'GET_STATE':
sendResponse({
activeAccount: tabAccounts.get(tabId) || null,
cacheSize: cache.size,
lastApiCall: apiCallLog.get(msg.payload.accountNum) || 0
});
return false;
case 'SET_BADGE':
if (msg.payload.text) {
chrome.action.setBadgeText({ text: msg.payload.text, tabId });
chrome.action.setBadgeBackgroundColor({ color: msg.payload.color || '#c41200', tabId });
} else {
chrome.action.setBadgeText({ text: '', tabId });
}
sendResponse({ ok: true });
return false;
case 'HEARTBEAT':
sendResponse({ ok: true });
return false;
default:
sendResponse({ error: 'unknown message type' });
return false;
}
});
// Clean up tab tracking when tabs close
chrome.tabs.onRemoved.addListener((tabId) => {
tabAccounts.delete(tabId);
});
chrome.runtime.onInstalled.addListener(() => {
log('Extension installed/updated');
});
})();