57 lines
1.8 KiB
TypeScript
57 lines
1.8 KiB
TypeScript
/** Refreshes analytics materialized views on a schedule. */
|
|
|
|
import { query } from '../db/connection';
|
|
import { invalidateDashboardAnalyticsCache, invalidateSecurityKpisCache } from './analyticsCache';
|
|
import { invalidateChartMaterializedViewsCache } from '../repositories/analyticsMaterializedQueries';
|
|
|
|
const REFRESH_INTERVAL_MS = Math.max(
|
|
60_000,
|
|
parseInt(process.env.ANALYTICS_MV_REFRESH_MS ?? '900000', 10)
|
|
);
|
|
|
|
const MV_REFRESH_ORDER = [
|
|
'analytics_daily_transactions',
|
|
'analytics_daily_tx_by_user',
|
|
'analytics_daily_tx_by_country',
|
|
'analytics_daily_bets',
|
|
'analytics_daily_bets_by_user',
|
|
'analytics_hourly_bets',
|
|
'analytics_daily_adjustments',
|
|
'analytics_daily_adjustments_by_user',
|
|
'analytics_daily_referrals_by_user',
|
|
'analytics_daily_country_user_logins',
|
|
'analytics_daily_active_users',
|
|
] as const;
|
|
|
|
let refreshTimer: ReturnType<typeof setInterval> | null = null;
|
|
|
|
export async function refreshAnalyticsMaterializedViews(): Promise<void> {
|
|
try {
|
|
for (const name of MV_REFRESH_ORDER) {
|
|
await query(`REFRESH MATERIALIZED VIEW CONCURRENTLY ${name}`);
|
|
}
|
|
invalidateChartMaterializedViewsCache();
|
|
invalidateDashboardAnalyticsCache();
|
|
invalidateSecurityKpisCache();
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
console.log('[analytics-mv] Dashboard rollups refreshed');
|
|
}
|
|
} catch (e) {
|
|
console.warn('[analytics-mv] Refresh failed (views may not exist yet):', e);
|
|
}
|
|
}
|
|
|
|
export function scheduleAnalyticsMaterializedViewRefresh(): void {
|
|
if (refreshTimer) return;
|
|
setImmediate(() => {
|
|
void refreshAnalyticsMaterializedViews();
|
|
});
|
|
setTimeout(() => {
|
|
void refreshAnalyticsMaterializedViews();
|
|
}, 60_000);
|
|
refreshTimer = setInterval(() => {
|
|
void refreshAnalyticsMaterializedViews();
|
|
}, REFRESH_INTERVAL_MS);
|
|
refreshTimer.unref();
|
|
}
|