From 1ebc0927ad84d7a13c2c9d0b0a35765d0afcda56 Mon Sep 17 00:00:00 2001 From: li4nee Date: Sat, 11 Jul 2026 15:27:04 +0545 Subject: [PATCH] feat(analytics): implement time-series granularity selection and enhance time series fetching methods --- .../analytics/services/analytics.service.ts | 41 ++++++++- .../modules/processor/repos/apiHits.repo.ts | 86 +++++++++++++------ .../processor/repos/apiHitsBase.repo.ts | 11 +++ .../processor/repos/endpointMetrics.repo.ts | 42 +++++++++ .../repos/endpointMetricsBase.repo.ts | 5 ++ .../middleware/zodValidators.middleware.ts | 9 +- 6 files changed, 162 insertions(+), 32 deletions(-) diff --git a/server/src/modules/analytics/services/analytics.service.ts b/server/src/modules/analytics/services/analytics.service.ts index 147b0c8..b649181 100644 --- a/server/src/modules/analytics/services/analytics.service.ts +++ b/server/src/modules/analytics/services/analytics.service.ts @@ -136,11 +136,40 @@ export class AnalyticsService implements IAnalyticsService { } } + /** Picks time-series source/resolution by range. */ + private pickGranularity(startTime: Date, endTime: Date): { bucketMs: number; source: "mongo-fine" | "postgres-hourly" | "postgres-daily" } { + const HOUR_MS = 60 * 60 * 1000; + const DAY_MS = 24 * HOUR_MS; + const spanMs = Math.max(0, endTime.getTime() - startTime.getTime()); + + if (spanMs <= 3 * HOUR_MS) { + const MINUTE_MS = 60 * 1000; + // Aim for ~60 points across the range, snapped to a whole minute. + const bucketMs = Math.max(MINUTE_MS, Math.round(spanMs / 60 / MINUTE_MS) * MINUTE_MS); + return { bucketMs, source: "mongo-fine" }; + } + if (spanMs > 10 * DAY_MS) { + return { bucketMs: DAY_MS, source: "postgres-daily" }; + } + return { bucketMs: HOUR_MS, source: "postgres-hourly" }; + } + async getTimeSeries(user: UserInsideAuthorizedRequest, query: AnalyticsTimeSeriesQueryDTOType): Promise { try { AuthorizationUtils.canViewAnalytics(user, query.clientId); logger.info(`[AnalyticsService] Fetching time series for clientId: ${query.clientId}`); - return await this.endPointMetricsRepo.getTimeSeries(query.clientId, query.startTime, query.endTime, query.serviceName); + + const endTime = query.endTime ?? new Date(); + const startTime = query.startTime ?? new Date(endTime.getTime() - 24 * 60 * 60 * 1000); + const { bucketMs, source } = this.pickGranularity(startTime, endTime); + + if (source === "mongo-fine") { + return await this.apiHitsRepo.getFineTimeSeries(query.clientId, bucketMs, startTime, endTime, query.serviceName); + } + if (source === "postgres-daily") { + return await this.endPointMetricsRepo.getDailyTimeSeries(query.clientId, startTime, endTime, query.serviceName); + } + return await this.endPointMetricsRepo.getTimeSeries(query.clientId, startTime, endTime, query.serviceName); } catch (error) { logger.error("[AnalyticsService] Error fetching time series", { error, query }); throw error; @@ -167,13 +196,19 @@ export class AnalyticsService implements IAnalyticsService { logger.info( `[AnalyticsService] Fetching endpoint drilldown for clientId: ${query.clientId} endpoint: ${query.endpoint}`, ); + + const endTime = query.endTime ?? new Date(); + const startTime = query.startTime ?? new Date(endTime.getTime() - 24 * 60 * 60 * 1000); + const { bucketMs } = this.pickGranularity(startTime, endTime); + return await this.apiHitsRepo.getEndpointTimeSeries( query.clientId, query.serviceName, query.endpoint, query.method, - query.startTime, - query.endTime, + startTime, + endTime, + bucketMs, ); } catch (error) { logger.error("[AnalyticsService] Error fetching endpoint drilldown", { error, query }); diff --git a/server/src/modules/processor/repos/apiHits.repo.ts b/server/src/modules/processor/repos/apiHits.repo.ts index 1500ff2..a19bfaf 100644 --- a/server/src/modules/processor/repos/apiHits.repo.ts +++ b/server/src/modules/processor/repos/apiHits.repo.ts @@ -129,13 +129,45 @@ export class MongoApiHitsRepo extends ApiHitsBaseRepo { } } + /** + * Groups matched apiHits into fixed-width buckets aligned to epoch time + * (not calendar boundaries), so any bucketMs works — 1 minute, 5 minutes, + * 1 hour, 1 day — without needing MongoDB 5's $dateTrunc. + */ + private async aggregateBucketedTimeSeries(matchStage: Record, bucketMs: number): Promise { + const results = await this.model.aggregate([ + { $match: matchStage }, + { + $group: { + _id: { + $toDate: { + $subtract: [{ $toLong: "$timestamp" }, { $mod: [{ $toLong: "$timestamp" }, bucketMs] }], + }, + }, + total_hits: { $sum: 1 }, + error_hits: { $sum: { $cond: [{ $gte: ["$statusCode", 400] }, 1, 0] } }, + total_latency: { $sum: "$latencyInMs" }, + }, + }, + { $sort: { _id: 1 } }, + ]); + + return results.map((r) => ({ + time_bucket: r._id, + total_hits: r.total_hits, + error_hits: r.error_hits, + avg_latency: r.total_hits > 0 ? parseFloat((r.total_latency / r.total_hits).toFixed(2)) : 0, + })); + } + async getEndpointTimeSeries( clientId: string, serviceName: string, endpoint: string, method: string, - startTime?: Date, - endTime?: Date, + startTime: Date | undefined, + endTime: Date | undefined, + bucketMs: number, ): Promise { try { const matchStage: Record = { @@ -150,36 +182,38 @@ export class MongoApiHitsRepo extends ApiHitsBaseRepo { if (endTime) timeFilter.$lte = endTime; if (Object.keys(timeFilter).length > 0) matchStage.timestamp = timeFilter; - const results = await this.model.aggregate([ - { $match: matchStage }, - { - $group: { - _id: { - $dateToString: { - format: "%Y-%m-%dT%H:00:00.000Z", - date: "$timestamp", - }, - }, - total_hits: { $sum: 1 }, - error_hits: { $sum: { $cond: [{ $gte: ["$statusCode", 400] }, 1, 0] } }, - total_latency: { $sum: "$latencyInMs" }, - }, - }, - { $sort: { _id: 1 } }, - ]); - - return results.map((r) => ({ - time_bucket: new Date(r._id), - total_hits: r.total_hits, - error_hits: r.error_hits, - avg_latency: r.total_hits > 0 ? parseFloat((r.total_latency / r.total_hits).toFixed(2)) : 0, - })); + return await this.aggregateBucketedTimeSeries(matchStage, bucketMs); } catch (error) { logger.error(`Failed to get endpoint time series: ${error instanceof Error ? error.message : "Unknown error"}`); throw error; } } + async getFineTimeSeries( + clientId: string, + bucketMs: number, + startTime?: Date, + endTime?: Date, + serviceName?: string, + ): Promise { + try { + const matchStage: Record = { + clientId: new Types.ObjectId(clientId), + }; + if (serviceName) matchStage.serviceName = serviceName; + + const timeFilter: Record = {}; + if (startTime) timeFilter.$gte = startTime; + if (endTime) timeFilter.$lte = endTime; + if (Object.keys(timeFilter).length > 0) matchStage.timestamp = timeFilter; + + return await this.aggregateBucketedTimeSeries(matchStage, bucketMs); + } catch (error) { + logger.error(`Failed to get fine time series: ${error instanceof Error ? error.message : "Unknown error"}`); + throw error; + } + } + async getDistinctServices(clientId: string): Promise { try { const services = await this.model.distinct("serviceName", { diff --git a/server/src/modules/processor/repos/apiHitsBase.repo.ts b/server/src/modules/processor/repos/apiHitsBase.repo.ts index 3b32555..ad8de1f 100644 --- a/server/src/modules/processor/repos/apiHitsBase.repo.ts +++ b/server/src/modules/processor/repos/apiHitsBase.repo.ts @@ -23,8 +23,19 @@ export abstract class ApiHitsBaseRepo { serviceName: string, endpoint: string, method: string, + startTime: Date | undefined, + endTime: Date | undefined, + bucketMs: number, + ): Promise; + /** Buckets raw apiHits directly (not the hourly Postgres rollup) at an + * arbitrary bucketMs — used for short time ranges where the rollup's fixed + * hourly grain would produce only one or two flat points. */ + abstract getFineTimeSeries( + clientId: string, + bucketMs: number, startTime?: Date, endTime?: Date, + serviceName?: string, ): Promise; abstract getDistinctServices(clientId: string): Promise; abstract streamRawLogsAsCsv(query: ExportQueryDTOType, onRow: (csvRow: string) => void): Promise; diff --git a/server/src/modules/processor/repos/endpointMetrics.repo.ts b/server/src/modules/processor/repos/endpointMetrics.repo.ts index 8f241b7..072afe9 100644 --- a/server/src/modules/processor/repos/endpointMetrics.repo.ts +++ b/server/src/modules/processor/repos/endpointMetrics.repo.ts @@ -345,4 +345,46 @@ export class PgEndPointMetricsRepo extends EndPointMetricsBaseRepo { + try { + if (!startTime) { + startTime = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); + } + + const dayBucket = sql`date_trunc('day', time_bucket)`; + + let query = PostgresDB.selectFrom("endpoint_metrics") + .select([ + dayBucket.as("time_bucket"), + sql`SUM(total_hits)`.as("total_hits"), + sql`SUM(error_hits)`.as("error_hits"), + sql`COALESCE(SUM(total_latency)::float / NULLIF(SUM(total_hits), 0), 0)`.as("avg_latency"), + ]) + .where("client_id", "=", clientId) + .where("time_bucket", ">=", startTime) + .groupBy(dayBucket) + .orderBy(dayBucket, "asc"); + + if (endTime) { + query = query.where("time_bucket", "<=", endTime); + } + + if (serviceName) { + query = query.where("service_name", "=", serviceName); + } + + const rows = await query.execute(); + + return rows.map((row) => ({ + time_bucket: row.time_bucket, + total_hits: Number(row.total_hits), + error_hits: Number(row.error_hits), + avg_latency: parseFloat(Number(row.avg_latency).toFixed(2)), + })); + } catch (error) { + logger.error("Error getting daily time series", { error, clientId }); + throw error; + } + } } diff --git a/server/src/modules/processor/repos/endpointMetricsBase.repo.ts b/server/src/modules/processor/repos/endpointMetricsBase.repo.ts index 6f9e878..9933531 100644 --- a/server/src/modules/processor/repos/endpointMetricsBase.repo.ts +++ b/server/src/modules/processor/repos/endpointMetricsBase.repo.ts @@ -22,4 +22,9 @@ export abstract class EndPointMetricsBaseRepo { abstract getOverviewStats(clientId: string, startTime?: Date, endTime?: Date): Promise; abstract getTimeSeries(clientId: string, startTime?: Date, endTime?: Date, serviceName?: string): Promise; + + /** Same rollup table as getTimeSeries, but grouped by day instead of the + * stored hourly bucket — used for long ranges where hundreds of hourly + * points would just be noise rather than a readable trend. */ + abstract getDailyTimeSeries(clientId: string, startTime?: Date, endTime?: Date, serviceName?: string): Promise; } diff --git a/server/src/shared/middleware/zodValidators.middleware.ts b/server/src/shared/middleware/zodValidators.middleware.ts index 4a078b4..6a4fc09 100644 --- a/server/src/shared/middleware/zodValidators.middleware.ts +++ b/server/src/shared/middleware/zodValidators.middleware.ts @@ -25,9 +25,12 @@ export const validateBody = (schema: z.ZodType) => async (req: Request, res export const validateQuery = (schema: z.ZodType) => async (req: Request, res: Response, next: NextFunction) => { try { const parsed = await schema.parseAsync(req.query); - // Express 5 exposes req.query as a getter-only accessor, so it can't be - // reassigned outright — mutate the existing object in place instead. - Object.assign(req.query, parsed); + Object.defineProperty(req, "query", { + value: parsed, + writable: true, + configurable: true, + enumerable: true, + }); next(); } catch (error: any) { const formattedErrors =