-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
667 lines (576 loc) · 19.1 KB
/
Copy pathindex.js
File metadata and controls
667 lines (576 loc) · 19.1 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
const dgram = require("dgram");
const WebSocket = require("ws");
const EventEmitter = require("events");
// NTP epoch starts Jan 1, 1900; Unix epoch starts Jan 1, 1970 (70 years = 2208988800s)
const NTP_DELTA_MS = 2208988800000;
function readNtpTimestamp(buf, pos) {
let intpart = 0, fractpart = 0;
for (let i = 0; i < 4; i++) intpart = (intpart * 256) + buf[pos + i];
for (let i = 4; i < 8; i++) fractpart = (fractpart * 256) + buf[pos + i];
return intpart * 1000 + Math.round((fractpart * 1000) / 0x100000000) - NTP_DELTA_MS;
}
/**
* TimeSync - Class for precise time synchronization
* Simple and intuitive API for synchronizing time with NTP servers
*/
class TimeSync extends EventEmitter {
constructor(options = {}) {
super();
// Synchronization state
this.isSync = false;
this.lastSyncTime = null;
this.systemOffset = 0;
this.syncDate = null;
this.lastRtt = null;
// Smooth correction
this.targetOffset = 0; // Target offset to reach
this.currentOffset = 0; // Current offset (gradually corrected)
this.correctionInProgress = false;
this.correctionStartTime = null; // For correction timeout
// Default configuration
this.config = {
servers: [
"pool.ntp.org",
"time.google.com",
"time.cloudflare.com",
],
timeout: 5000,
retries: 3,
autoSync: false,
autoSyncInterval: 300000, // 5 minutes
locale: undefined, // undefined = system locale
// New options for smooth correction
smoothCorrection: true, // Enable smooth correction
maxCorrectionJump: 1000, // Max brutal correction (1s)
correctionRate: 0.1, // Smooth correction rate (10%/sync)
maxOffsetThreshold: 5000, // Threshold to force brutal correction (5s)
coherenceValidation: true, // Server coherence validation
...options
};
// WebSocket for real-time (optional)
this.wsServer = null;
this.wsClients = new Set();
// Auto-sync
this.autoSyncTimer = null;
this.setupEventHandlers();
}
setupEventHandlers() {
this.on('sync', (data) => {
console.log(`✅ Synchronized with ${data.server} (offset: ${data.offset}ms)`);
});
this.on('error', (error) => {
console.log(`❌ Synchronization error: ${error.message}`);
});
// Advanced events
this.on('coherenceWarning', (data) => {
console.log(`⚠️ Server coherence issue: variance ${data.variance}ms`);
});
this.on('driftWarning', (data) => {
console.log(`📈 Long elapsed time: ${(data.elapsed / 60000).toFixed(1)} minutes`);
});
}
/**
* Synchronize time with NTP server
* @param {Object} options - Synchronization options
* @returns {Promise<Object>} Synchronization info
*/
async sync(options = {}) {
const config = { ...this.config, ...options };
const serverResults = [];
// Test multiple servers for coherence validation
const serversToTest = config.coherenceValidation !== false ?
config.servers.slice(0, Math.min(3, config.servers.length)) :
config.servers;
for (const server of serversToTest) {
try {
const { offset: newOffset, rtt } = await this.getNtpTime(server, config.timeout);
serverResults.push({
server,
offset: newOffset,
rtt,
ntpTime: new Date(Date.now() + newOffset),
systemTime: Date.now()
});
} catch (error) {
const ntpError = new Error(`[${server}] ${error.message}`);
ntpError.server = server;
this.emit('error', ntpError);
continue; // Try next server
}
}
if (serverResults.length === 0) {
throw new Error('Unable to synchronize with any NTP server');
}
// Coherence validation between servers
let selectedResult = serverResults[0];
if (serverResults.length > 1) {
const offsets = serverResults.map(r => r.offset);
const variance = Math.max(...offsets) - Math.min(...offsets);
if (variance > 100) { // Variance > 100ms is suspicious
this.emit('coherenceWarning', {
variance,
servers: serverResults.map(r => ({ server: r.server, offset: r.offset }))
});
// Use median for better robustness
offsets.sort((a, b) => a - b);
const medianOffset = offsets[Math.floor(offsets.length / 2)];
selectedResult = serverResults.find(r => r.offset === medianOffset) || selectedResult;
}
}
const newOffset = selectedResult.offset;
// Smooth correction management
const isFirstSync = !this.isSync;
const offsetDiff = Math.abs(newOffset - this.currentOffset);
if (isFirstSync || !config.smoothCorrection ||
offsetDiff <= config.maxCorrectionJump ||
offsetDiff >= config.maxOffsetThreshold) {
// Brutal correction
this.systemOffset = newOffset;
this.currentOffset = newOffset;
this.targetOffset = newOffset;
this.correctionInProgress = false;
this.correctionStartTime = null; // Reset correction timer
} else {
// Smooth correction
this.targetOffset = newOffset;
this.systemOffset = newOffset; // Keep real offset for stats
this.correctionInProgress = true;
this.correctionStartTime = null; // Will be set in applyGradualCorrection
this.applyGradualCorrection(config.correctionRate);
}
this.isSync = true;
this.lastSyncTime = performance.now();
this.syncDate = new Date();
this.lastRtt = selectedResult.rtt;
const result = {
server: selectedResult.server,
offset: this.systemOffset,
rtt: selectedResult.rtt,
correctedOffset: this.currentOffset,
time: selectedResult.ntpTime,
systemTime: new Date(selectedResult.systemTime),
gradualCorrection: this.correctionInProgress,
offsetDiff: isFirstSync ? 0 : offsetDiff,
serverResults: serverResults.length > 1 ? serverResults : undefined,
coherenceVariance: serverResults.length > 1 ?
Math.max(...serverResults.map(r => r.offset)) - Math.min(...serverResults.map(r => r.offset)) : 0
};
this.emit('sync', result);
// Start auto-sync if requested
if (config.autoSync && !this.autoSyncTimer) {
this.startAutoSync(config.autoSyncInterval);
}
return result;
}
/**
* Queries an NTP server and returns offset + RTT using the 4-timestamp algorithm.
* offset = ((t2 - t1) + (t3 - t4)) / 2 — compensates for network latency
* rtt = (t4 - t1) - (t3 - t2)
* @private
*/
getNtpTime(server, timeout = 5000) {
return new Promise((resolve, reject) => {
const client = dgram.createSocket("udp4");
const packet = Buffer.alloc(48);
packet[0] = 0x1B; // LI=0, VN=3, Mode=3 (client)
let done = false;
const finish = (err, result) => {
if (done) return;
done = true;
clearTimeout(timer);
try { client.close(); } catch { /* socket may already be closed */ }
err ? reject(err) : resolve(result);
};
const timer = setTimeout(
() => finish(new Error(`Timeout after ${timeout}ms`)),
timeout
);
client.on("error", (err) => finish(err));
const t1 = Date.now();
client.send(packet, 0, 48, 123, server, (err) => {
if (err) return finish(err);
client.once("message", (msg) => {
const t4 = Date.now();
if (msg.length < 48) return finish(new Error("Invalid NTP response"));
const t2 = readNtpTimestamp(msg, 32); // server receive timestamp
const t3 = readNtpTimestamp(msg, 40); // server transmit timestamp
const offset = Math.round(((t2 - t1) + (t3 - t4)) / 2);
const rtt = (t4 - t1) - (t3 - t2);
finish(null, { offset, rtt });
});
});
});
}
/**
* Returns current synchronized time
* @returns {Date} Precise time
*/
now() {
if (!this.isSync) {
throw new Error('Clock not synchronized. Call sync() first.');
}
const currentPerf = performance.now();
const elapsed = currentPerf - this.lastSyncTime;
// Detect significant drift for automatic recalculation
if (elapsed > 3600000) { // More than 1 hour since last sync
console.log('⚠️ Long elapsed time detected, consider re-syncing');
this.emit('driftWarning', { elapsed });
}
// Use gradually corrected offset if available
const activeOffset = this.correctionInProgress ? this.currentOffset : this.systemOffset;
return new Date(Date.now() + activeOffset);
}
/**
* Returns time in ISO format
* @returns {string} ISO timestamp
*/
timestamp() {
return this.now().toISOString();
}
/**
* Returns the offset from system time
* @returns {number} Offset in milliseconds
*/
offset() {
if (!this.isSync) return 0;
// Return gradually corrected offset if available
return this.correctionInProgress ? this.currentOffset : this.systemOffset;
}
/**
* Checks if clock is synchronized
* @returns {boolean}
*/
isSynchronized() {
return this.isSync;
}
/**
* Returns synchronization statistics
* @returns {Object}
*/
stats() {
return {
synchronized: this.isSync,
lastSync: this.syncDate,
offset: this.systemOffset,
rtt: this.lastRtt,
correctedOffset: this.currentOffset,
targetOffset: this.targetOffset,
correctionInProgress: this.correctionInProgress,
uptime: this.isSync ? performance.now() - this.lastSyncTime : 0,
config: {
smoothCorrection: this.config.smoothCorrection,
maxCorrectionJump: this.config.maxCorrectionJump,
correctionRate: this.config.correctionRate,
maxOffsetThreshold: this.config.maxOffsetThreshold
}
};
}
/**
* Starts automatic synchronization
* @param {number} interval - Interval in milliseconds
*/
startAutoSync(interval = 300000) {
if (this.autoSyncTimer) {
clearInterval(this.autoSyncTimer);
}
this.autoSyncTimer = setInterval(() => {
this.sync().catch(err => {
this.emit('error', err);
});
}, interval);
console.log(`🔄 Auto-sync enabled (${interval / 1000}s)`);
}
/**
* Stops automatic synchronization
*/
stopAutoSync() {
if (this.autoSyncTimer) {
clearInterval(this.autoSyncTimer);
this.autoSyncTimer = null;
console.log('🛑 Auto-sync disabled');
}
}
/**
* Starts a WebSocket server to broadcast time in real-time
* @param {number} port - WebSocket server port
* @returns {number} Port used
*/
startWebSocketServer(port = 8080) {
if (this.wsServer) {
throw new Error('WebSocket server already started');
}
this.wsServer = new WebSocket.Server({ port });
this.wsServer.on('connection', (ws) => {
this.wsClients.add(ws);
console.log(`🔌 WebSocket client connected (${this.wsClients.size} total)`);
// Send time immediately
if (this.isSync) {
ws.send(JSON.stringify({
type: 'time',
data: {
timestamp: this.timestamp(),
offset: this.offset(),
synchronized: true
}
}));
}
ws.on('close', () => {
this.wsClients.delete(ws);
console.log(`🔌 WebSocket client disconnected (${this.wsClients.size} remaining)`);
});
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
this.handleWebSocketMessage(ws, data);
} catch {
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid JSON format'
}));
}
});
});
// Broadcast time every second
this.wsTimer = setInterval(() => {
if (this.isSync && this.wsClients.size > 0) {
this.broadcastTime();
}
}, 1000);
console.log(`🌐 WebSocket server started on port ${port}`);
return port;
}
/**
* Stops the WebSocket server
*/
stopWebSocketServer() {
if (this.wsTimer) {
clearInterval(this.wsTimer);
this.wsTimer = null;
}
if (this.wsServer) {
this.wsServer.close();
this.wsClients.clear();
this.wsServer = null;
console.log('🌐 WebSocket server stopped');
}
}
/**
* Handles WebSocket messages
* @private
*/
handleWebSocketMessage(ws, data) {
switch (data.type) {
case 'getTime':
if (this.isSync) {
ws.send(JSON.stringify({
type: 'time',
data: {
timestamp: this.timestamp(),
offset: this.offset(),
synchronized: true
}
}));
} else {
ws.send(JSON.stringify({
type: 'error',
message: 'Clock not synchronized'
}));
}
break;
case 'sync':
this.sync().then(() => {
ws.send(JSON.stringify({
type: 'syncComplete',
message: 'Synchronization complete'
}));
}).catch(error => {
ws.send(JSON.stringify({
type: 'error',
message: error.message
}));
});
break;
default:
ws.send(JSON.stringify({
type: 'error',
message: 'Unknown command. Use: getTime, sync'
}));
}
}
/**
* Broadcasts time to all WebSocket clients
* @private
*/
broadcastTime() {
const message = JSON.stringify({
type: 'time',
data: {
timestamp: this.timestamp(),
offset: this.offset(),
synchronized: this.isSync
}
});
this.wsClients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
/**
* Formats a date/time
* @param {Date|string|number} date - Date to format
* @param {string} format - Output format
* @returns {string}
*/
format(date = null, format = 'iso', locale = undefined) {
const time = date ? new Date(date) : this.now();
const loc = locale ?? this.config.locale;
switch (format) {
case 'iso':
return time.toISOString();
case 'locale':
return time.toLocaleString(loc);
case 'timestamp':
return time.getTime().toString();
case 'utc':
return time.toUTCString();
case 'date':
return time.toLocaleDateString(loc);
case 'time':
return time.toLocaleTimeString(loc);
default:
return time.toString();
}
}
/**
* Calculates the difference between two dates
* @param {Date|string|number} date1
* @param {Date|string|number} date2
* @returns {number} Difference in milliseconds
*/
diff(date1, date2 = null) {
const d1 = new Date(date1);
const d2 = date2 ? new Date(date2) : this.now();
return Math.abs(d2.getTime() - d1.getTime());
}
/**
* Displays a message with precise time
* @param {string} message
*/
log(message) {
const time = this.isSync ? this.timestamp() : new Date().toISOString();
console.log(`[${time}] ${message}`);
}
/**
* Applies gradual offset correction
* @private
*/
applyGradualCorrection(rate = 0.1) {
if (!this.correctionInProgress) return;
const diff = this.targetOffset - this.currentOffset;
// Convergence threshold to avoid infinite oscillations
if (Math.abs(diff) < 0.5) { // Convergence within 0.5ms
this.currentOffset = this.targetOffset;
this.correctionInProgress = false;
this.emit('correctionComplete', {
finalOffset: this.currentOffset,
targetReached: true,
converged: true
});
return;
}
// Timeout verification to avoid infinite corrections
if (!this.correctionStartTime) {
this.correctionStartTime = performance.now();
}
const elapsed = performance.now() - this.correctionStartTime;
if (elapsed > 30000) { // 30 second timeout
console.log('⚠️ Correction timeout, applying final offset');
this.currentOffset = this.targetOffset;
this.correctionInProgress = false;
this.correctionStartTime = null;
this.emit('correctionComplete', {
finalOffset: this.currentOffset,
targetReached: true,
timeout: true
});
return;
}
const correction = diff * rate;
this.currentOffset += correction;
// Adaptive interval based on correction size
const nextInterval = Math.max(50, Math.min(200, Math.abs(diff) * 0.1));
// Schedule next correction
setTimeout(() => {
this.applyGradualCorrection(rate);
}, nextInterval);
}
/**
* Enables or disables gradual correction
* @param {boolean} enabled - Enable gradual correction
* @param {Object} options - Correction options
*/
setSmoothCorrection(enabled, options = {}) {
this.config.smoothCorrection = enabled;
if (options.maxCorrectionJump !== undefined) {
this.config.maxCorrectionJump = options.maxCorrectionJump;
}
if (options.correctionRate !== undefined) {
this.config.correctionRate = options.correctionRate;
}
if (options.maxOffsetThreshold !== undefined) {
this.config.maxOffsetThreshold = options.maxOffsetThreshold;
}
console.log(`🔧 Smooth correction: ${enabled ? 'enabled' : 'disabled'}`);
if (enabled) {
console.log(` - Max jump: ${this.config.maxCorrectionJump}ms`);
console.log(` - Rate: ${this.config.correctionRate * 100}%`);
console.log(` - Brutal threshold: ${this.config.maxOffsetThreshold}ms`);
}
}
/**
* Forces brutal correction (ignores gradual correction)
*/
forceCorrection() {
if (this.correctionInProgress) {
this.currentOffset = this.targetOffset;
this.correctionInProgress = false;
this.emit('correctionComplete', {
finalOffset: this.currentOffset,
forced: true
});
console.log('⚡ Forced correction applied');
}
}
}
// Global instance for simple usage
const timeSync = new TimeSync();
// Simple API - direct functions
const api = {
// Main methods
sync: (options) => timeSync.sync(options),
now: () => timeSync.now(),
timestamp: () => timeSync.timestamp(),
offset: () => timeSync.offset(),
stats: () => timeSync.stats(),
isSynchronized: () => timeSync.isSynchronized(),
// Auto-sync
startAutoSync: (interval) => timeSync.startAutoSync(interval),
stopAutoSync: () => timeSync.stopAutoSync(),
// Gradual correction
setSmoothCorrection: (enabled, options) => timeSync.setSmoothCorrection(enabled, options),
forceCorrection: () => timeSync.forceCorrection(),
// WebSocket
startWebSocketServer: (port) => timeSync.startWebSocketServer(port),
stopWebSocketServer: () => timeSync.stopWebSocketServer(),
// Utilities
format: (date, format, locale) => timeSync.format(date, format, locale),
diff: (date1, date2) => timeSync.diff(date1, date2),
log: (message) => timeSync.log(message),
// Events
on: (event, callback) => timeSync.on(event, callback),
off: (event, callback) => timeSync.off(event, callback),
// Class for advanced usage
TimeSync
};
module.exports = api;