1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-01-11 18:24:43 +02:00

Improved ntp time

This commit is contained in:
Laurent Cozic 2020-09-09 00:34:27 +01:00
parent 1f70a76c7e
commit f41ba67e15
3 changed files with 16 additions and 6 deletions

View File

@ -44,6 +44,9 @@ const KvStore = require('lib/services/KvStore');
const MigrationService = require('lib/services/MigrationService');
const { toSystemSlashes } = require('lib/path-utils.js');
const ntpClient = require('lib/vendor/ntp-client');
ntpClient.dgram = require('dgram');
class BaseApplication {
constructor() {
this.logger_ = new Logger();

View File

@ -1,7 +1,7 @@
const ntpClient = require('lib/vendor/ntp-client');
const Mutex = require('async-mutex').Mutex;
let lastSyncTime = 0;
let nextSyncTime = 0;
let timeOffset = 0;
const fetchingTimeMutex = new Mutex();
@ -24,7 +24,7 @@ async function networkTime():Promise<Date> {
}
function shouldSyncTime() {
return !lastSyncTime || Date.now() - lastSyncTime >= 5 * 1000;
return !nextSyncTime || Date.now() > nextSyncTime;
}
export default async function():Promise<Date> {
@ -34,9 +34,14 @@ export default async function():Promise<Date> {
try {
if (shouldSyncTime()) {
const date = await networkTime();
lastSyncTime = Date.now();
nextSyncTime = Date.now() + 60 * 1000;
timeOffset = date.getTime() - Date.now();
}
} catch (error) {
// Fallback to application time since
// most of the time it's actually correct
nextSyncTime = Date.now() + 20 * 1000;
timeOffset = 0;
} finally {
release();
}

View File

@ -14,11 +14,11 @@
(function (exports) {
"use strict";
var dgram = require('dgram');
exports.defaultNtpPort = 123;
exports.defaultNtpServer = "pool.ntp.org";
exports.dgram = null;
/**
* Amount of acceptable time to await for a response from the remote server.
* Configured default to 10 seconds.
@ -40,7 +40,9 @@
server = server || exports.defaultNtpServer;
port = port || exports.defaultNtpPort;
var client = dgram.createSocket("udp4"),
if (!exports.dgram) throw new Error('dgram package has not been set!!');
var client = exports.dgram.createSocket("udp4"),
ntpData = new Buffer(48);
// RFC 2030 -> LI = 0 (no warning, 2 bits), VN = 3 (IPv4 only, 3 bits), Mode = 3 (Client Mode, 3 bits) -> 1 byte