@magmacomputing/tempo-plugin-ntp
A lightweight, high-precision Community plugin for the Tempo ecosystem that provides client-server network time synchronization and monotonic clock drift compensation using Cristian's algorithm, HTTP Server-Timing headers, jitter rejection, and Exponential Moving Average (EMA) smoothing.
Installation
npm install @magmacomputing/tempo-plugin-ntpArchitecture & Registration
Plugin Installation
import { Tempo } from '@magmacomputing/tempo';
import { NtpPlugin } from '@magmacomputing/tempo-plugin-ntp';
Tempo.use(NtpPlugin, {
server: '/api/time', // Default time synchronization endpoint
syncInterval: '15m', // Automatic periodic re-sync
interceptFetch: ['https://api.mycorp.com', '/api/'] // Passively calibrate only on trusted endpoints
});
// Explicitly calibrate against the server before querying calibrated time
await Tempo.ntp.sync();
const now = Tempo.ntp.now();Configuration Options (NtpSyncOptions)
| Option | Type | Default | Description |
|---|---|---|---|
server | string | undefined | Dedicated HTTP time endpoint returning Date or Server-Timing: clock=<epochMs>. |
syncInterval | string | number | undefined | Periodic re-sync interval (e.g. '15m', '1h', or ms). |
interceptFetch | boolean | string | string[] | RegExp | Function | false | Passively sniff headers from application fetch calls. Can be true (sniff all), a path prefix, origin array, regex, or predicate. |
trustedOrigins | string | string[] | RegExp | Function | undefined | Whitelist of allowed origins or URL prefixes to sample when interceptFetch: true is enabled. |
maxAcceptableRttMs | number | 1000 | Maximum round-trip time threshold in milliseconds. Jittery or delayed requests are discarded. |
alpha | number | 0.3 | Exponential Moving Average (EMA) smoothing factor between 0.0 and 1.0. |
Auto-Installation (Side-Effect Import)
import { Tempo } from '@magmacomputing/tempo';
import '@magmacomputing/tempo-plugin-ntp/install';
// Synchronize and query true calibrated server time
await Tempo.ntp.sync();
const now = Tempo.ntp.now();Documentation Guide
Explore detailed guides on architecture, production use-cases, and algorithms:
- Use Cases & Production Patterns: Real-world architectures for financial countdowns, live auctions, zero-overhead passive calibration (
interceptFetch), distributed logging synchronization, and TOTP authentication. - Ticker Integration & Atomic Clocks: Integrating with
@magmacomputing/tempo-plugin-tickerto build true-time, drift-compensated continuous execution loops and scheduled intervals (ntp: true). - Cristian Algorithm & Precision Specs: Mathematical models for round-trip time (RTT) offset calculations, sub-millisecond
Server-Timingheaders, statistical jitter filtering, and EMA smoothing.
Interactive REPL
// 🌐 Network Time Sync & Drift Calibration (@magmacomputing/tempo-plugin-ntp)
const { NtpPlugin } = await import('@magmacomputing/tempo-plugin-ntp');
Tempo.use(NtpPlugin);
console.log('Calibrating clock with remote time source...');
const sample = await Tempo.ntp.sync('https://worldtimeapi.org/api/timezone/Etc/UTC');
console.log('Sync Result: Offset', sample.offsetMs, 'ms (Uncertainty: ±' + sample.uncertaintyMs + 'ms, Samples: ' + sample.sampleCount + ')');
console.log('Calibrated Tempo:', Tempo.ntp.now().format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}.{ms}'));
return `Calibrated! Offset: ${Tempo.ntp.offset}ms | Local: ${new Tempo().format('{hh}:{mi}:{ss}.{ms}')} vs NTP: ${Tempo.ntp.now().format('{hh}:{mi}:{ss}.{ms}')}`;import { Tempo } from '@magmacomputing/tempo';
import { NtpPlugin } from '@magmacomputing/tempo-plugin-ntp';
// 1. Install the plugin (points to same-origin or CORS-enabled time endpoint)
Tempo.use(NtpPlugin, { server: '/api/time' });
// 2. Perform an initial sync
await Tempo.ntp.sync();
// 3. Query true calibrated atomic time (100% synchronous!)
const atomicNow = Tempo.ntp.now();
console.log(`True UTC Time: ${atomicNow.format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}.{ms}')}`);
console.log(`Measured Drift Offset: ${Tempo.ntp.offset}ms`);
console.log(`Uncertainty Window: ±${Tempo.ntp.drift.uncertaintyMs}ms`);Comprehensive API Reference
Tempo.ntp.now(timeZone?: string): Tempo
Synchronously returns a new Tempo instance anchored to the calibrated atomic server timestamp.
Tempo.ntp.sync(endpoint?: string): Promise<ClockDriftState>
Asynchronously sends a lightweight HTTP request to measure Round-Trip Time (RTT) and updates the Exponential Moving Average (EMA) drift offset.
Tempo.ntp.offset: number
Getter returning the current clock drift offset in milliseconds (serverTime = localTime + offset).
Tempo.ntp.drift: ClockDriftState
Getter returning the full telemetry state snapshot:
interface ClockDriftState {
readonly offsetMs: number;
readonly uncertaintyMs: number;
readonly lastSyncedAt: number;
readonly sampleCount: number;
}Tempo.ntp.isCalibrated: boolean
Getter indicating whether at least one valid synchronization sample has been successfully processed.
Tempo.ntp.reset(): void
Resets the calibration state and sample count back to zero.
tempo.toNtpTime(): Tempo
Instance method that returns a new Tempo instance offset by the current NTP clock drift.
Licensing
This is a Community plugin. It is completely free and open-source for personal and commercial use. No license token is required.