Skip to content

Commit 8aec6ae

Browse files
committed
Use RTT midpoint to adjust Date.now
Measure local time before and after fetching server time and compute offset using the midpoint (compensates for network latency). Round the calculated offset and lower the adjustment threshold from 5000ms to 500ms to avoid applying small corrections. Also rename timing variables for clarity.
1 parent 36ae7bf commit 8aec6ae

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

packages/napcat-core/helper/server-time.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,17 @@ export const OriginalDateNow: () => number = Date.now.bind(Date);
1414
* @returns 偏移量(毫秒)
1515
*/
1616
export function hookGlobalDateNow (getServerTimeFn: () => string): number {
17-
const localNow = OriginalDateNow();
17+
const start = OriginalDateNow();
1818
const serverTimeStr = getServerTimeFn();
19+
const end = OriginalDateNow();
1920
const serverTimeMs = parseInt(serverTimeStr, 10);
2021

2122
if (isNaN(serverTimeMs) || serverTimeMs <= 0) {
2223
return 0;
2324
}
2425

25-
const offsetMs = serverTimeMs - localNow;
26+
// 补偿网络延迟:假定往返时间对称,服务器时间对应本地时间的中点 (start + end) / 2
27+
const offsetMs = Math.round(serverTimeMs - (start + end) / 2);
2628

2729
if (Math.abs(offsetMs) > 5000) {
2830
Date.now = () => OriginalDateNow() + offsetMs;

0 commit comments

Comments
 (0)