296 lines
11 KiB
TypeScript
296 lines
11 KiB
TypeScript
import {
|
|
CLOCK_CALIBRATION_DEFAULTS,
|
|
type ClockCalibrationSettings,
|
|
type ClockEstimate,
|
|
type ClockSample,
|
|
} from '../../src/type/reservation'
|
|
|
|
export interface RawClockObservation {
|
|
id: number
|
|
sentAtMs: number
|
|
receivedAtMs: number
|
|
rttMs: number
|
|
serverDateHeader?: string
|
|
remoteIp: string
|
|
reusedSocket: boolean
|
|
protocol?: 'http/1.1' | 'h2'
|
|
connectionId?: string
|
|
ageHeader?: string
|
|
viaHeader?: string
|
|
cacheHeader?: string
|
|
statusCode: number
|
|
}
|
|
|
|
const MAX_ACCEPTED_RTT_MS = 2_000
|
|
|
|
function finite(value: number, fallback = 0) {
|
|
return Number.isFinite(value) ? value : fallback
|
|
}
|
|
|
|
export function observationToSample(observation: RawClockObservation): ClockSample {
|
|
const serverDateMs = Date.parse(observation.serverDateHeader ?? '')
|
|
const midpointMs = (observation.sentAtMs + observation.receivedAtMs) / 2
|
|
const age = Number(observation.ageHeader ?? '0')
|
|
const cacheHit = /hit/i.test(observation.cacheHeader ?? '')
|
|
let rejectionReason: string | undefined
|
|
|
|
if (observation.statusCode < 200 || observation.statusCode >= 400) rejectionReason = `HTTP ${observation.statusCode}`
|
|
else if (!Number.isFinite(serverDateMs)) rejectionReason = 'Date 헤더 없음'
|
|
else if (Number.isFinite(age) && age > 0) rejectionReason = '캐시된 응답'
|
|
else if (cacheHit || observation.viaHeader) rejectionReason = '프록시 캐시 경로'
|
|
else if (observation.rttMs <= 0 || observation.rttMs > MAX_ACCEPTED_RTT_MS) rejectionReason = 'RTT 이상치'
|
|
|
|
return {
|
|
id: observation.id,
|
|
sentAtMs: observation.sentAtMs,
|
|
receivedAtMs: observation.receivedAtMs,
|
|
midpointMs,
|
|
serverDateMs: finite(serverDateMs),
|
|
rttMs: observation.rttMs,
|
|
offsetEstimateMs: finite(serverDateMs) + 500 - midpointMs,
|
|
offsetMinMs: finite(serverDateMs) - observation.receivedAtMs,
|
|
offsetMaxMs: finite(serverDateMs) + 1_000 - observation.sentAtMs,
|
|
remoteIp: observation.remoteIp,
|
|
reusedSocket: observation.reusedSocket,
|
|
protocol: observation.protocol,
|
|
connectionId: observation.connectionId,
|
|
accepted: !rejectionReason,
|
|
rejectionReason,
|
|
}
|
|
}
|
|
|
|
export function quantile(values: number[], percentile: number): number {
|
|
if (values.length === 0) return 0
|
|
const sorted = [...values].sort((a, b) => a - b)
|
|
const index = (sorted.length - 1) * Math.min(1, Math.max(0, percentile))
|
|
const lower = Math.floor(index)
|
|
const upper = Math.ceil(index)
|
|
if (lower === upper) return sorted[lower]
|
|
return sorted[lower] + (sorted[upper] - sorted[lower]) * (index - lower)
|
|
}
|
|
|
|
function weightedMedian(items: Array<{ value: number; weight: number }>): number {
|
|
if (items.length === 0) return 0
|
|
const sorted = [...items].sort((a, b) => a.value - b.value)
|
|
const total = sorted.reduce((sum, item) => sum + item.weight, 0)
|
|
let accumulated = 0
|
|
for (const item of sorted) {
|
|
accumulated += item.weight
|
|
if (accumulated >= total / 2) return item.value
|
|
}
|
|
return sorted.at(-1)?.value ?? 0
|
|
}
|
|
|
|
function estimateDrift(samples: ClockSample[], nowMs: number) {
|
|
if (samples.length < 6) return { currentOffsetMs: 0, driftPpm: 0, usable: false }
|
|
const origin = samples[Math.floor(samples.length / 2)].midpointMs
|
|
let sumWeight = 0
|
|
let sumX = 0
|
|
let sumY = 0
|
|
let sumXX = 0
|
|
let sumXY = 0
|
|
|
|
for (const sample of samples) {
|
|
const x = sample.midpointMs - origin
|
|
const y = sample.offsetEstimateMs
|
|
const weight = 1 / Math.max(sample.rttMs, 1) ** 2
|
|
sumWeight += weight
|
|
sumX += weight * x
|
|
sumY += weight * y
|
|
sumXX += weight * x * x
|
|
sumXY += weight * x * y
|
|
}
|
|
|
|
const denominator = sumWeight * sumXX - sumX * sumX
|
|
if (Math.abs(denominator) < 1e-9) return { currentOffsetMs: 0, driftPpm: 0, usable: false }
|
|
const rawSlope = (sumWeight * sumXY - sumX * sumY) / denominator
|
|
const slope = Math.max(-200e-6, Math.min(200e-6, rawSlope))
|
|
const intercept = (sumY - slope * sumX) / sumWeight
|
|
return {
|
|
currentOffsetMs: intercept + slope * (nowMs - origin),
|
|
driftPpm: slope * 1_000_000,
|
|
usable: true,
|
|
}
|
|
}
|
|
|
|
export interface BoundaryEstimate {
|
|
count: number
|
|
offsetMs: number
|
|
uncertaintyMs: number
|
|
spreadMs: number
|
|
}
|
|
|
|
export function estimateBoundaryOffset(
|
|
samples: ClockSample[],
|
|
settings: ClockCalibrationSettings = CLOCK_CALIBRATION_DEFAULTS,
|
|
): BoundaryEstimate | undefined {
|
|
const candidates: Array<{ boundaryMs: number; offsetMs: number; uncertaintyMs: number; atMs: number }> = []
|
|
for (let index = 1; index < samples.length; index += 1) {
|
|
const previous = samples[index - 1]
|
|
const current = samples[index]
|
|
if (!previous.accepted || !current.accepted) continue
|
|
if (previous.remoteIp !== current.remoteIp) continue
|
|
if (previous.rttMs > settings.maxProbeRttMs || current.rttMs > settings.maxProbeRttMs) continue
|
|
if (current.serverDateMs - previous.serverDateMs !== 1_000) continue
|
|
const gap = current.midpointMs - previous.midpointMs
|
|
if (gap <= 0 || gap > Math.max(250, settings.probeIntervalMs * 3)) continue
|
|
const localBoundaryMs = (previous.midpointMs + current.midpointMs) / 2
|
|
candidates.push({
|
|
boundaryMs: current.serverDateMs,
|
|
offsetMs: current.serverDateMs - localBoundaryMs,
|
|
uncertaintyMs: gap / 2 + Math.max(previous.rttMs, current.rttMs) / 2
|
|
+ (previous.reusedSocket && current.reusedSocket ? 0 : 25),
|
|
atMs: current.receivedAtMs,
|
|
})
|
|
}
|
|
|
|
const uniqueBoundaries = [...candidates.reduce((map, candidate) => {
|
|
const existing = map.get(candidate.boundaryMs)
|
|
if (!existing || candidate.uncertaintyMs < existing.uncertaintyMs) map.set(candidate.boundaryMs, candidate)
|
|
return map
|
|
}, new Map<number, typeof candidates[number]>()).values()].sort((a, b) => a.atMs - b.atMs)
|
|
const recent = uniqueBoundaries.slice(-settings.historySize)
|
|
if (recent.length === 0) return undefined
|
|
const center = quantile(recent.map((item) => item.offsetMs), 0.5)
|
|
const absoluteDeviations = recent.map((item) => Math.abs(item.offsetMs - center))
|
|
const mad = quantile(absoluteDeviations, 0.5)
|
|
const rejectionLimit = Math.max(settings.maxBoundarySpreadMs, mad * 3 * 1.4826)
|
|
const filtered = recent.filter((item) => Math.abs(item.offsetMs - center) <= rejectionLimit)
|
|
if (filtered.length === 0) return undefined
|
|
|
|
const offsetMs = weightedMedian(filtered.map((item) => ({
|
|
value: item.offsetMs,
|
|
weight: 1 / Math.max(item.uncertaintyMs, 1) ** 2,
|
|
})))
|
|
const spreadMs = quantile(filtered.map((item) => Math.abs(item.offsetMs - offsetMs)), 0.9)
|
|
const typicalMeasurementUncertainty = quantile(filtered.map((item) => item.uncertaintyMs), 0.5)
|
|
const uncertaintyMs = Math.max(
|
|
spreadMs,
|
|
typicalMeasurementUncertainty / Math.sqrt(filtered.length),
|
|
)
|
|
return { count: filtered.length, offsetMs, uncertaintyMs, spreadMs }
|
|
}
|
|
|
|
export function estimateClock(
|
|
samples: ClockSample[],
|
|
nowMs = Date.now(),
|
|
monitoring = false,
|
|
settings: ClockCalibrationSettings = CLOCK_CALIBRATION_DEFAULTS,
|
|
): ClockEstimate {
|
|
const allRecent = samples.slice(-settings.sampleWindowSize)
|
|
const accepted = allRecent.filter((sample) => sample.accepted && sample.rttMs <= settings.maxProbeRttMs)
|
|
if (accepted.length === 0) {
|
|
return {
|
|
monitoring,
|
|
observedAtMs: nowMs,
|
|
estimatedServerTimeMs: nowMs,
|
|
offsetMs: 0,
|
|
driftPpm: 0,
|
|
minRttMs: 0,
|
|
p50RttMs: 0,
|
|
p95RttMs: 0,
|
|
oneWayMs: 0,
|
|
uncertaintyMs: 1_000,
|
|
sampleAgeMs: Number.POSITIVE_INFINITY,
|
|
acceptedSamples: 0,
|
|
rawOffsetMs: 0,
|
|
boundaryCount: 0,
|
|
recommendedCorrectionMs: 0,
|
|
calibrationReady: false,
|
|
calibrationApplied: false,
|
|
calibrationSettings: settings,
|
|
remoteIp: '',
|
|
protocol: undefined,
|
|
connectionId: undefined,
|
|
connectionReused: undefined,
|
|
quality: 'unavailable',
|
|
warning: '유효한 서버시간 표본이 없습니다.',
|
|
samples: allRecent,
|
|
}
|
|
}
|
|
|
|
const rtts = accepted.map((sample) => sample.rttMs)
|
|
const minRttMs = Math.min(...rtts)
|
|
const p50RttMs = quantile(rtts, 0.5)
|
|
const p95RttMs = quantile(rtts, 0.95)
|
|
const lowLatencyCutoff = Math.max(minRttMs + 25, p50RttMs)
|
|
const lowLatency = accepted.filter((sample) => sample.rttMs <= lowLatencyCutoff)
|
|
const medianOffset = weightedMedian(lowLatency.map((sample) => ({
|
|
value: sample.offsetEstimateMs,
|
|
weight: 1 / Math.max(sample.rttMs, 1) ** 2,
|
|
})))
|
|
const drift = estimateDrift(lowLatency, nowMs)
|
|
const boundary = settings.enabled ? estimateBoundaryOffset(accepted, settings) : undefined
|
|
const rawOffsetMs = drift.usable ? medianOffset * 0.75 + drift.currentOffsetMs * 0.25 : medianOffset
|
|
const calibrationReady = Boolean(boundary && boundary.count >= settings.requiredBoundaryCount
|
|
&& boundary.spreadMs <= settings.maxBoundarySpreadMs)
|
|
const calibrationApplied = Boolean(calibrationReady && settings.autoApply)
|
|
let offsetMs = calibrationApplied ? boundary!.offsetMs : rawOffsetMs
|
|
let uncertaintyMs = Math.max(
|
|
500 + minRttMs / 2,
|
|
quantile(lowLatency.map((sample) => Math.abs(sample.offsetEstimateMs - medianOffset)), 0.9) + p95RttMs / 2,
|
|
)
|
|
|
|
if (calibrationApplied && boundary) {
|
|
uncertaintyMs = Math.max(boundary.uncertaintyMs, minRttMs / 2)
|
|
}
|
|
|
|
const latest = accepted.at(-1)!
|
|
const sampleAgeMs = Math.max(0, nowMs - latest.receivedAtMs)
|
|
let quality: ClockEstimate['quality'] = 'poor'
|
|
let warning: string | undefined
|
|
if (uncertaintyMs <= 300 && p95RttMs <= 250 && sampleAgeMs <= 5_000) quality = 'good'
|
|
else if (uncertaintyMs <= 700 && sampleAgeMs <= 10_000) quality = 'fair'
|
|
else warning = sampleAgeMs > 10_000
|
|
? '마지막 표본이 오래되었습니다. 네트워크 상태를 확인하세요.'
|
|
: '서버 Date 헤더 해상도 또는 RTT 변동으로 추정 오차가 큽니다.'
|
|
if (settings.enabled && !calibrationReady) {
|
|
warning = `초 경계 정밀 보정을 학습 중입니다 (${boundary?.count ?? 0}/${settings.requiredBoundaryCount}).`
|
|
}
|
|
|
|
return {
|
|
monitoring,
|
|
observedAtMs: nowMs,
|
|
estimatedServerTimeMs: nowMs + offsetMs,
|
|
offsetMs,
|
|
driftPpm: drift.driftPpm,
|
|
minRttMs,
|
|
p50RttMs,
|
|
p95RttMs,
|
|
oneWayMs: minRttMs / 2,
|
|
uncertaintyMs,
|
|
sampleAgeMs,
|
|
acceptedSamples: accepted.length,
|
|
rawOffsetMs,
|
|
boundaryCount: boundary?.count ?? 0,
|
|
boundaryOffsetMs: boundary?.offsetMs,
|
|
boundaryUncertaintyMs: boundary?.uncertaintyMs,
|
|
boundarySpreadMs: boundary?.spreadMs,
|
|
recommendedCorrectionMs: boundary ? boundary.offsetMs - rawOffsetMs : 0,
|
|
calibrationReady,
|
|
calibrationApplied,
|
|
calibrationSettings: settings,
|
|
remoteIp: latest.remoteIp,
|
|
protocol: latest.protocol,
|
|
connectionId: latest.connectionId,
|
|
connectionReused: latest.reusedSocket,
|
|
quality,
|
|
warning,
|
|
samples: allRecent,
|
|
}
|
|
}
|
|
|
|
export function appendClockSample(samples: ClockSample[], sample: ClockSample, maxSamples = CLOCK_CALIBRATION_DEFAULTS.sampleWindowSize) {
|
|
const previousIp = [...samples].reverse().find((item) => item.accepted)?.remoteIp
|
|
const routeChanged = sample.accepted && previousIp && sample.remoteIp && previousIp !== sample.remoteIp
|
|
return [...(routeChanged ? [] : samples), sample].slice(-maxSamples)
|
|
}
|
|
|
|
export function computePlannedSendAtMs(
|
|
targetServerTimeMs: number,
|
|
userOffsetMs: number,
|
|
estimate: Pick<ClockEstimate, 'offsetMs' | 'oneWayMs'>,
|
|
) {
|
|
return targetServerTimeMs + userOffsetMs - estimate.offsetMs - estimate.oneWayMs
|
|
}
|