-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
350 lines (301 loc) · 9.69 KB
/
Copy pathmain.js
File metadata and controls
350 lines (301 loc) · 9.69 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
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
344
345
346
347
348
349
350
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
import dotenv from "dotenv";
dotenv.config();
// .env dosyasından bilgileri alıyoruz.
// Eğer ELASTICSEARCH_HOST tanımlı değilse, varsayılan olarak yerel sunucuyu kullan.
const ELASTICSEARCH_HOST =
process.env.ELASTICSEARCH_HOST || "http://localhost:9200/";
import { fetchCountryDataDynamic } from "./scraper/countryDataDynamic.js";
import { fetchWorldDataDynamic } from "./scraper/worldDataDynamic.js";
import { initIndex, client } from "./elastic/client.js";
import ProgressBar from "progress";
import { updateCurrentSnapshot } from "./elastic/client.js";
// Gelişmiş Loglama Sistemi
const logger = {
info: (message) =>
console.log(
`\x1b[36mℹ️ [${new Date().toLocaleTimeString()}] ${message}\x1b[0m`
),
success: (message) =>
console.log(
`\x1b[32m✅ [${new Date().toLocaleTimeString()}] ${message}\x1b[0m`
),
error: (message) =>
console.log(
`\x1b[31m❌ [${new Date().toLocaleTimeString()}] ${message}\x1b[0m`
),
warn: (message) =>
console.log(
`\x1b[33m⚠️ [${new Date().toLocaleTimeString()}] ${message}\x1b[0m`
),
};
// Geliştirilmiş Veri Doğrulama
const validateData = (worldData, countryData) => {
const warnings = [];
const errors = [];
const EXPECTED_COUNTRIES = 235;
// Dünya verisi kontrolleri
if (!worldData?.current_population) {
errors.push("Dünya nüfus verisi eksik");
}
// Ülke verisi kontrolleri
if (!countryData || countryData.length === 0) {
errors.push("Hiç ülke verisi alınamadı");
return { isValid: false, errors, warnings };
}
const totalCountries = countryData.length;
const validCountries = countryData.filter(
(c) =>
c.current_population > 0 && !isNaN(c.yearly_change) && !isNaN(c.med_age)
).length;
// Uyarılar
if (totalCountries < EXPECTED_COUNTRIES) {
warnings.push(`Eksik ülke: ${EXPECTED_COUNTRIES - totalCountries}`);
}
const criticalMissing = ["China", "India", "United States"].filter(
(c) => !countryData.some((d) => d.country === c)
);
if (criticalMissing.length > 0) {
warnings.push(`Eksik kritik ülkeler: ${criticalMissing.join(", ")}`);
}
if (totalCountries - validCountries > 0) {
warnings.push(
`Geçersiz veri içeren ülkeler: ${totalCountries - validCountries}`
);
}
// Hatalar
if (validCountries === 0) {
errors.push("Hiç geçerli ülke verisi yok");
}
return {
isValid: errors.length === 0,
errors,
warnings,
};
};
// Enerji Tüketimi Ölçüm Fonksiyonu
const measureEnergyConsumption = async (fn, label = "İşlem") => {
const startTime = process.hrtime();
const startCpuUsage = process.cpuUsage();
try {
const result = await fn();
const elapsedTime = process.hrtime(startTime);
const elapsedCpu = process.cpuUsage(startCpuUsage);
const cpuSeconds = (elapsedCpu.user + elapsedCpu.system) / 1e6;
const wallSeconds = elapsedTime[0] + elapsedTime[1] / 1e9;
const cpuWattage = 50;
const estimatedEnergyJoules = cpuSeconds * cpuWattage;
logger.info(`\n== ${label} Enerji Tüketim Raporu ==`);
logger.info(`Duvar saati süresi: ${wallSeconds.toFixed(3)} s`);
logger.info(`CPU kullanım süresi: ${cpuSeconds.toFixed(3)} s`);
logger.info(
`Tahmini enerji tüketimi: ${estimatedEnergyJoules.toFixed(
2
)} J (ortalama ${cpuWattage}W kabul edilerek)`
);
return result;
} catch (error) {
throw error;
}
};
// Ana İşlem Akışı
const processData = async () => {
try {
logger.info("Scraping süreci başlatılıyor...");
// Elasticsearch hazırlığı
await initIndex();
// 1. Dünya verilerini çek
logger.info("════════════ DÜNYA VERİLERİ ÇEKİLİYOR ════════════");
const worldData = await fetchWithProgress(
fetchWorldDataDynamic,
"🌍 Dünya verisi",
15,
120000
);
// 2. Bekleme süresi
logger.info("Dünya verisi alındıktan sonra 20 saniye bekleniyor...");
await delay(20000);
// 3. Ülke verilerini çek
logger.info("════════════ ÜLKE VERİLERİ ÇEKİLİYOR ════════════");
const countryData = await fetchWithProgress(
fetchCountryDataDynamic,
"🌐 Ülke verisi",
30,
240000
);
// Sonuçları işle
const results = { world: worldData, country: countryData };
logResults(results);
// Validasyon
const validation = validateData(results.world, results.country);
handleValidation(validation);
// Elasticsearch'e gönder
const { successCount, errorCount } = await sendToElastic(results);
logger.success(`Başarıyla kaydedildi: ${successCount} kayıt`);
if (errorCount > 0) {
logger.warn(`Başarısız kayıtlar: ${errorCount}`);
}
// Snapshot güncelleme
await updateCurrentSnapshot(new Date().toISOString());
} catch (error) {
logger.error(`Kritik Hata: ${error.message}`);
logger.info("5 dakika sonra yeniden denenecek...");
setTimeout(() => processDataWithEnergy(), 300000);
}
};
// Enerji ölçümü dahil ana işlem çağrısı
const processDataWithEnergy = async () => {
await measureEnergyConsumption(processData, "processData");
};
// Yardımcı Fonksiyonlar
const fetchWithProgress = async (fetchFn, label, total, timeout) => {
const bar = new ProgressBar(`${label} [:bar] :percent :etas`, {
complete: "=",
incomplete: " ",
width: 30,
total,
});
const timer = setInterval(() => bar.tick(), 1000);
try {
const result = await Promise.race([
fetchFn(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`${label} zaman aşımı`)), timeout)
),
]);
clearInterval(timer);
bar.update(1);
return result;
} catch (error) {
clearInterval(timer);
throw error;
}
};
const logResults = (results) => {
logger.info("════════════ DÜNYA VERİLERİ ════════════");
if (results.world) {
logger.info(
`🌍 Nüfus: ${results.world.current_population?.toLocaleString()}`
);
logger.info(
`📈 Günlük Büyüme: ${results.world.population_growth?.toLocaleString()}`
);
logger.info(`⏳ Zaman Damgası: ${results.world["@timestamp"]}`);
} else {
logger.error("Dünya verisi yok");
}
logger.info("════════════ ÜLKE VERİLERİ ════════════");
if (results.country?.length > 0) {
logger.info(`✅ Toplam Ülke: ${results.country.length}`);
logger.info(
`🏆 İlk 3 Ülke: ${results.country
.slice(0, 3)
.map((c) => c.country)
.join(", ")}`
);
logger.info(`📊 Ortalama Yaş: ${calculateAverageAge(results.country)}`);
} else {
logger.error("Ülke verisi yok");
}
};
const handleValidation = ({ isValid, errors, warnings }) => {
if (!isValid) {
logger.error("Validasyon Hataları:");
errors.forEach((e) => logger.error(`❌ ${e}`));
throw new Error("Kritik validasyon hataları");
}
if (warnings.length > 0) {
logger.warn("Validasyon Uyarıları:");
warnings.forEach((w) => logger.warn(`⚠️ ${w}`));
}
};
const sendToElastic = async ({ world, country }) => {
const body = [];
try {
// Dünya verisini ekle
if (world) {
body.push(
{ index: { _index: process.env.INDEX_NAME } },
{
...world,
type: "world",
is_current: true,
"@timestamp": new Date().toISOString(),
}
);
}
// Ülke verilerini ekle
if (country?.length > 0) {
country.forEach((c) => {
body.push(
{ index: { _index: process.env.INDEX_NAME } },
{
...c,
type: "country",
is_current: true,
"@timestamp": new Date().toISOString(),
current_population: c.current_population || 0,
yearly_change: c.yearly_change || 0,
net_change: c.net_change || 0,
migrants: c.migrants || 0,
med_age: c.med_age || 0,
}
);
});
}
if (body.length === 0) {
logger.warn("Gönderilecek veri yok");
return { successCount: 0, errorCount: 0 };
}
const { body: response } = await client.bulk({
refresh: "wait_for",
body,
});
let successCount = 0;
let errorCount = 0;
const errors = [];
if (response?.items) {
response.items.forEach((item, index) => {
if (item.index.error) {
errorCount++;
errors.push({
document: body[index * 2 + 1],
reason: item.index.error.reason,
});
} else {
successCount++;
}
});
}
if (errorCount > 0) {
logger.error(`İlk 3 hata detayı:`);
errors.slice(0, 3).forEach((err, i) => {
logger.error(`${i + 1}. Hata: ${err.reason}`);
logger.error(`Belge: ${JSON.stringify(err.document)}`);
});
}
return { successCount, errorCount };
} catch (error) {
logger.error("Elasticsearch hatası:");
if (error.meta) {
logger.error(`Hata detayı: ${JSON.stringify(error.meta.body.error)}`);
} else {
logger.error(error.stack);
}
throw error;
}
};
const calculateAverageAge = (countries) => {
const validAges = countries
.map((c) => c.med_age)
.filter((age) => age > 0 && age < 100);
return validAges.length > 0
? (validAges.reduce((sum, age) => sum + age, 0) / validAges.length).toFixed(
1
)
: "N/A";
};
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.clear();
processDataWithEnergy();
setInterval(processDataWithEnergy, 1800000); // Her 30 dakikada bir çalıştır.