Spaces:
Sleeping

File size: 6,755 Bytes
4e83772
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { PLANS } from "@/constants/plan.js";
import { IAnalyticsRepository, QueryOptions } from "@/interfaces/repository/IAnalyticsRepository.js";
import { IProjectBandwidthRepository } from "@/interfaces/repository/IProjectBandwidthRepository.js";
import { BandWidthWithProjectType, IAnalyticsService, QueryOptionsString } from "@/interfaces/service/IAnalyticsService.js";
import { BufferAnalytics } from "@/models/Analytics.js";
import { fillEmptyQueries, getInterval, getRange, getUnit, validateFreeAnalyticsParams } from "@/utils/analyticsUnits.js";

class AnalyticsService implements IAnalyticsService {
	private analyticsRepo: IAnalyticsRepository;
	private projectBandwidthRepo: IProjectBandwidthRepository;

	private analyticsBuffer: BufferAnalytics[] = [];
	private readonly BATCH_SIZE = 6000;
	private readonly FLUSH_INTERVAL = 1000 * 10;
	private readonly MAX_BUFFER_SIZE = 40000;
	private flushTimer?: NodeJS.Timeout;
	private isFlushing = false;

	constructor(analyticsRepo: IAnalyticsRepository, projectBandwidthRepo: IProjectBandwidthRepository) {
		this.analyticsRepo = analyticsRepo;
		this.projectBandwidthRepo = projectBandwidthRepo;
		// this.startFlushTimer();
	}

	private startFlushTimer(): void {
		// not called ; Use interval Service in utils for intervals
		this.flushTimer = setInterval(() => {
			process.stdout.write(" -");
			if (this.analyticsBuffer.length > 0) {
				this.saveBatch().catch(console.error);
			}
		}, this.FLUSH_INTERVAL);
	}
	async saveBatch(): Promise<void> {
		if (this.isFlushing || this.analyticsBuffer.length === 0) {
			// process.stdout.write(` "`);
			return;
		}
		console.log("saving ....", this.analyticsBuffer.length, this.analyticsBuffer[0].project_id, this.analyticsBuffer[0].path);

		this.isFlushing = true;
		const batch = this.analyticsBuffer.splice(0, this.BATCH_SIZE * 3);
		try {
			await this.analyticsRepo.insertBatch(batch);
			console.log(`Saved ${batch.length} analytics `);
		} catch (error) {
			console.error("save analytics error:", error, "Discarding data");
		} finally {
			this.isFlushing = false;
			if (this.analyticsBuffer.length >= this.BATCH_SIZE) {
				setImmediate(() => this.saveBatch());
			}
		}
	}

	async addEvent(event: BufferAnalytics): Promise<void> {
		if (this.analyticsBuffer.length >= this.MAX_BUFFER_SIZE) {
			console.warn("Analytics buffer full, dropping oldest events");
			this.analyticsBuffer.splice(0, 1000);
		}
		this.analyticsBuffer.push(event);

		if (this.analyticsBuffer.length >= this.BATCH_SIZE) {
			this.saveBatch();
		}
	}
	async addEventBatch(event: BufferAnalytics[], bandwidthByProjectBatch: BandWidthWithProjectType): Promise<void> {
		if (this.analyticsBuffer.length >= this.MAX_BUFFER_SIZE) {
			console.warn("Analytics buffer full, dropping oldest events");
			this.analyticsBuffer.splice(0, 1000);
		}
		this.analyticsBuffer.push(...event);
		try {
			await this.projectBandwidthRepo.addBandwidth(bandwidthByProjectBatch);
		} catch (error) {
			console.log("Error on saving bws ,", error);
		}

		if (this.analyticsBuffer.length >= this.BATCH_SIZE) {
			this.saveBatch();
		}
	}

	async exitService(): Promise<void> {
		console.log("service cleaning analytics....");
		clearInterval(this.flushTimer);
		while (this.analyticsBuffer.length > 0) {
			if (this.isFlushing) {
				await new Promise((resolve) => setTimeout(resolve, 500));
				continue;
			}
			await this.saveBatch();
		}
	}

	async clearAnalytics(projectId: string): Promise<void> {
		return this.analyticsRepo.clearProjectAnalytics(projectId);
	}

	async getBandwidthData(projectId: string, userPlan: string, queryOptionsString?: QueryOptionsString): Promise<[unknown[], QueryOptions]> {
		const range = queryOptionsString?.range;
		const interval = queryOptionsString?.interval;
		const [filteredRange, fillteredInterval] = fillEmptyQueries(range, interval);

		const queryOptions = {
			interval: getInterval(fillteredInterval),
			intervalUnit: getUnit(fillteredInterval),
			range: getRange(filteredRange),
			rangeUnit: getUnit(filteredRange),
		};
		if (userPlan !== PLANS.PRO.name) {
			validateFreeAnalyticsParams(queryOptions, range, interval);
		}
		const data = await this.analyticsRepo.getBandwidth(projectId, queryOptions);
		return [data, queryOptions];
	}
	async getOverView(projectId: string, userPlan: string, queryOptionsString?: QueryOptionsString): Promise<[unknown[], QueryOptions]> {
		const range = queryOptionsString?.range;
		const interval = queryOptionsString?.interval;
		const [filteredRange, fillteredInterval] = fillEmptyQueries(range, interval);

		const queryOptions = {
			interval: getInterval(fillteredInterval),
			intervalUnit: getUnit(fillteredInterval),
			range: getRange(filteredRange),
			rangeUnit: getUnit(filteredRange),
		};
		if (userPlan !== PLANS.PRO.name) {
			validateFreeAnalyticsParams(queryOptions, range, interval);
		}
		const data = await this.analyticsRepo.getOverview(projectId, queryOptions);
		return [data, queryOptions];
	}
	async getRealtime(projectId: string, queryOptionsString?: QueryOptionsString): Promise<[unknown[], QueryOptions]> {
		const range = queryOptionsString?.range;
		const [filteredRange] = fillEmptyQueries(range);
		const queryOptions = {
			range: getRange(filteredRange),
			rangeUnit: getUnit(filteredRange),
		};
		const data = await this.analyticsRepo.getRealtime(projectId, queryOptions);
		return [data, queryOptions];
	}
	async getTopPages(projectId: string, userPlan: string, queryOptionsString?: QueryOptionsString): Promise<[unknown[], QueryOptions]> {
		const range = queryOptionsString?.range;
		const limit = queryOptionsString?.limit;
		const [filteredRange] = fillEmptyQueries(range);

		const queryOptions = {
			range: getRange(filteredRange),
			rangeUnit: getUnit(filteredRange),
			limit: 60,
		};
		if (userPlan !== PLANS.PRO.name) {
			validateFreeAnalyticsParams(queryOptions, range);
		}
		const data = await this.analyticsRepo.getTopPages(projectId, queryOptions);
		return [data, queryOptions];
	}
	async getPlatformStats(
		projectId: string,
		userPlan: string,
		queryOptionsString?: QueryOptionsString,
	): Promise<[{ osStats: unknown[]; browserStats: unknown[] }, QueryOptions]> {
		const range = queryOptionsString?.range;
		const [filteredRange] = fillEmptyQueries(range);
		const queryOptions = {
			range: getRange(filteredRange),
			rangeUnit: getUnit(filteredRange),
		};
		if (userPlan !== PLANS.PRO.name) {
			validateFreeAnalyticsParams(queryOptions, range);
		}
		const [osStats, browserStats] = await Promise.all([
			this.analyticsRepo.getOsStats(projectId, queryOptions),
			this.analyticsRepo.getBrowserStats(projectId, queryOptions),
		]);
		return [{ osStats, browserStats }, queryOptions];
	}
}

export default AnalyticsService;