File size: 9,256 Bytes
46eb81c f7d65f7 6d9f36a 1dbfa1e 6d9f36a f7d65f7 6d9f36a 1dbfa1e 46eb81c f7d65f7 46eb81c 6d9f36a 46eb81c 6d9f36a f7d65f7 6d9f36a 1dbfa1e 46eb81c f6d3526 1dbfa1e 6d9f36a f7d65f7 46eb81c f7d65f7 46eb81c 499175b f7d65f7 46eb81c f7d65f7 46eb81c f7d65f7 46eb81c f7d65f7 46eb81c 499175b 46eb81c f7d65f7 46eb81c 499175b 46eb81c f7d65f7 46eb81c f7d65f7 499175b f7d65f7 1dbfa1e f6d3526 1dbfa1e 499175b 6d9f36a f7d65f7 6d9f36a f7d65f7 6d9f36a 499175b 6d9f36a 499175b 6d9f36a 499175b 6d9f36a 499175b f7d65f7 1dbfa1e 6d9f36a 46eb81c 6d9f36a f7d65f7 6d9f36a f7d65f7 6d9f36a f7d65f7 6d9f36a f7d65f7 6d9f36a 1dbfa1e f7d65f7 46eb81c 6d9f36a 46eb81c f7d65f7 6d9f36a |
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 |
import { Redis } from '@upstash/redis';
interface EndpointStats {
totalRequests: number;
successRequests: number;
failedRequests: number;
lastAccessed: number;
}
interface VisitorData {
timestamp: number;
count: number;
}
interface IPFailureTracking {
count: number;
resetTime: number;
}
interface GlobalStats {
totalRequests: number;
totalSuccess: number;
totalFailed: number;
uniqueVisitors: Set<string>;
endpoints: Map<string, EndpointStats>;
startTime: number;
visitorsByDay: Map<string, Set<string>>;
}
interface SerializedStats {
totalRequests: number;
totalSuccess: number;
totalFailed: number;
uniqueVisitors: string[];
endpoints: Record<string, EndpointStats>;
startTime: number;
visitorsByDay: Record<string, string[]>;
}
class StatsTracker {
private stats: GlobalStats;
private ipFailures: Map<string, IPFailureTracking>;
private readonly MAX_FAILS_PER_IP = 1;
private readonly FAIL_WINDOW_MS = 12 * 60 * 60 * 1000;
private redis: Redis | null = null;
private saveTimeout: NodeJS.Timeout | null = null;
private readonly REDIS_KEY = 'api-stats:global';
constructor() {
this.stats = {
totalRequests: 0,
totalSuccess: 0,
totalFailed: 0,
uniqueVisitors: new Set(),
endpoints: new Map(),
startTime: Date.now(),
visitorsByDay: new Map(),
};
this.ipFailures = new Map();
if (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) {
this.redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
console.log('Redis initialized for persistent stats');
} else {
console.warn('Redis not configured - stats will be in-memory only');
}
setInterval(() => {
const now = Date.now();
this.ipFailures.forEach((tracking, ip) => {
if (now > tracking.resetTime) {
this.ipFailures.delete(ip);
}
});
}, 5 * 60 * 1000);
}
async loadStats(): Promise<void> {
if (!this.redis) {
console.log('No Redis configured, starting with fresh stats');
return;
}
try {
const data = await this.redis.get<SerializedStats>(this.REDIS_KEY);
if (!data) {
console.log('No existing stats found in Redis, starting fresh');
return;
}
this.stats.totalRequests = data.totalRequests || 0;
this.stats.totalSuccess = data.totalSuccess || 0;
this.stats.totalFailed = data.totalFailed || 0;
this.stats.uniqueVisitors = new Set(data.uniqueVisitors || []);
this.stats.startTime = data.startTime || Date.now();
this.stats.endpoints = new Map();
if (data.endpoints) {
Object.entries(data.endpoints).forEach(([endpoint, stats]) => {
this.stats.endpoints.set(endpoint, stats);
});
}
this.stats.visitorsByDay = new Map();
if (data.visitorsByDay) {
Object.entries(data.visitorsByDay).forEach(([date, ips]) => {
this.stats.visitorsByDay.set(date, new Set(ips));
});
}
console.log(`Stats loaded from Redis: ${this.stats.totalRequests} total requests`);
} catch (error) {
console.error('Error loading stats from Redis:', error);
}
}
private async saveStats(): Promise<void> {
if (!this.redis) {
return;
}
try {
const serialized: SerializedStats = {
totalRequests: this.stats.totalRequests,
totalSuccess: this.stats.totalSuccess,
totalFailed: this.stats.totalFailed,
uniqueVisitors: Array.from(this.stats.uniqueVisitors),
startTime: this.stats.startTime,
endpoints: {},
visitorsByDay: {},
};
this.stats.endpoints.forEach((stats, endpoint) => {
serialized.endpoints[endpoint] = stats;
});
this.stats.visitorsByDay.forEach((ips, date) => {
serialized.visitorsByDay[date] = Array.from(ips);
});
await this.redis.set(this.REDIS_KEY, serialized);
// use this if we need auto cleanup
// await this.redis.expire(this.REDIS_KEY, 90 * 24 * 60 * 60);
} catch (error) {
console.error('Error saving stats to Redis:', error);
}
}
private scheduleSave(): void {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(() => {
this.saveStats();
}, 5000);
}
trackRequest(endpoint: string, statusCode: number, clientIp: string): boolean {
const now = Date.now();
const isFailed = statusCode >= 500;
if (isFailed) {
const ipTracking = this.ipFailures.get(clientIp);
if (!ipTracking) {
this.ipFailures.set(clientIp, {
count: 1,
resetTime: now + this.FAIL_WINDOW_MS,
});
} else {
if (now > ipTracking.resetTime) {
ipTracking.count = 1;
ipTracking.resetTime = now + this.FAIL_WINDOW_MS;
} else {
if (ipTracking.count >= this.MAX_FAILS_PER_IP) {
return false;
}
ipTracking.count++;
}
}
} else {
const ipTracking = this.ipFailures.get(clientIp);
if (ipTracking && ipTracking.count > 0) {
ipTracking.count--;
}
}
const isSuccess = statusCode >= 200 && statusCode < 400;
const isServerError = statusCode >= 500;
if (isSuccess || isServerError) {
this.stats.totalRequests++;
if (isSuccess) {
this.stats.totalSuccess++;
} else if (isServerError) {
this.stats.totalFailed++;
}
}
this.stats.uniqueVisitors.add(clientIp);
const dateKey = new Date(now).toISOString().split('T')[0];
if (!this.stats.visitorsByDay.has(dateKey)) {
this.stats.visitorsByDay.set(dateKey, new Set());
}
this.stats.visitorsByDay.get(dateKey)!.add(clientIp);
if (isSuccess || isServerError) {
if (!this.stats.endpoints.has(endpoint)) {
this.stats.endpoints.set(endpoint, {
totalRequests: 0,
successRequests: 0,
failedRequests: 0,
lastAccessed: now,
});
}
const endpointStats = this.stats.endpoints.get(endpoint)!;
endpointStats.totalRequests++;
endpointStats.lastAccessed = now;
if (isSuccess) {
endpointStats.successRequests++;
} else if (isServerError) {
endpointStats.failedRequests++;
}
}
this.scheduleSave();
return true;
}
getGlobalStats() {
const uptime = Date.now() - this.stats.startTime;
const uptimeHours = Math.floor(uptime / (1000 * 60 * 60));
const uptimeDays = Math.floor(uptimeHours / 24);
return {
totalRequests: this.stats.totalRequests,
totalSuccess: this.stats.totalSuccess,
totalFailed: this.stats.totalFailed,
uniqueVisitors: this.stats.uniqueVisitors.size,
successRate: this.stats.totalRequests > 0
? ((this.stats.totalSuccess / this.stats.totalRequests) * 100).toFixed(2)
: "0.00",
uptime: {
ms: uptime,
hours: uptimeHours,
days: uptimeDays,
formatted: uptimeDays > 0
? `${uptimeDays}d ${uptimeHours % 24}h`
: `${uptimeHours}h`,
},
persistenceEnabled: this.redis !== null,
};
}
getVisitorChartData(days: number = 30): VisitorData[] {
const now = new Date();
const data: VisitorData[] = [];
for (let i = days - 1; i >= 0; i--) {
const date = new Date(now);
date.setDate(date.getDate() - i);
const dateKey = date.toISOString().split('T')[0];
const visitors = this.stats.visitorsByDay.get(dateKey);
const timestamp = date.getTime();
data.push({
timestamp,
count: visitors ? visitors.size : 0,
});
}
return data;
}
getEndpointStats(endpoint: string) {
return this.stats.endpoints.get(endpoint) || null;
}
getAllEndpointStats() {
const result: Record<string, EndpointStats> = {};
this.stats.endpoints.forEach((stats, endpoint) => {
result[endpoint] = stats;
});
return result;
}
getTopEndpoints(limit: number = 10) {
return Array.from(this.stats.endpoints.entries())
.map(([endpoint, stats]) => ({ endpoint, ...stats }))
.sort((a, b) => b.totalRequests - a.totalRequests)
.slice(0, limit);
}
async reset() {
this.stats = {
totalRequests: 0,
totalSuccess: 0,
totalFailed: 0,
uniqueVisitors: new Set(),
endpoints: new Map(),
startTime: Date.now(),
visitorsByDay: new Map(),
};
this.ipFailures.clear();
await this.saveStats();
}
async shutdown(): Promise<void> {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
await this.saveStats();
console.log('Stats saved on shutdown');
}
}
let statsTracker: StatsTracker;
export async function initStatsTracker() {
statsTracker = new StatsTracker();
await statsTracker.loadStats();
return statsTracker;
}
export function getStatsTracker() {
if (!statsTracker) {
throw new Error("StatsTracker not initialized. Call initStatsTracker() first.");
}
return statsTracker;
} |