Files
test-project-161/electron/main/server-clock.ts
T
2026-08-12 17:28:30 +09:00

260 lines
11 KiB
TypeScript

import { BrowserWindow, ipcMain } from 'electron'
import {
CLOCK_CALIBRATION_DEFAULTS,
type ClockCalibrationSettings,
type ClockEstimate,
type ClockSample,
type TimingTestRequest,
type TimingTestResult,
} from '../../src/type/reservation'
import { edgeBrowserHeaders, requestKeyescape } from './keyescape-http'
import { appendClockSample, computePlannedSendAtMs, estimateClock, observationToSample } from './server-clock-core'
const CLOCK_EVENT = 'reservation:clock-state'
const BASE_INTERVAL_MS = 5_000
const NEAR_INTERVAL_MS = 1_000
const FINAL_INTERVAL_MS = 250
function headerValue(value: string | string[] | undefined) {
return Array.isArray(value) ? value.join(', ') : value
}
function broadcast(channel: string, value: unknown) {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) window.webContents.send(channel, value)
}
}
export class ServerClockService {
private samples: ClockSample[] = []
private sequence = 0
private timer?: NodeJS.Timeout
private inFlight?: Promise<ClockSample>
private userMonitoring = false
private autoTargetServerTimeMs?: number
private lastError?: string
private settings: ClockCalibrationSettings = { ...CLOCK_CALIBRATION_DEFAULTS }
private precisionBoundaryServerMs?: number
getEstimate(): ClockEstimate {
const estimate = estimateClock(this.samples, Date.now(), this.isRunning(), this.settings)
if (this.lastError && estimate.quality !== 'unavailable') {
estimate.warning = this.lastError
if (estimate.quality === 'good') estimate.quality = 'fair'
}
return estimate
}
configure(input: ClockCalibrationSettings) {
const integer = (value: number, minimum: number, maximum: number, fallback: number) => Number.isFinite(value)
? Math.round(Math.min(maximum, Math.max(minimum, value)))
: fallback
const requiredBoundaryCount = integer(input.requiredBoundaryCount, 3, 12, CLOCK_CALIBRATION_DEFAULTS.requiredBoundaryCount)
this.settings = {
enabled: Boolean(input.enabled),
autoApply: Boolean(input.autoApply),
scanWindowMs: integer(input.scanWindowMs, 100, 450, CLOCK_CALIBRATION_DEFAULTS.scanWindowMs),
probeIntervalMs: integer(input.probeIntervalMs, 25, 200, CLOCK_CALIBRATION_DEFAULTS.probeIntervalMs),
initialBoundarySpacingSec: integer(input.initialBoundarySpacingSec, 1, 10, CLOCK_CALIBRATION_DEFAULTS.initialBoundarySpacingSec),
requiredBoundaryCount,
historySize: integer(input.historySize, requiredBoundaryCount, 30, Math.max(requiredBoundaryCount, CLOCK_CALIBRATION_DEFAULTS.historySize)),
maxBoundarySpreadMs: integer(input.maxBoundarySpreadMs, 30, 500, CLOCK_CALIBRATION_DEFAULTS.maxBoundarySpreadMs),
maxProbeRttMs: integer(input.maxProbeRttMs, 100, 1_500, CLOCK_CALIBRATION_DEFAULTS.maxProbeRttMs),
maintenanceIntervalSec: integer(input.maintenanceIntervalSec, 5, 120, CLOCK_CALIBRATION_DEFAULTS.maintenanceIntervalSec),
sampleWindowSize: integer(input.sampleWindowSize, 60, 600, CLOCK_CALIBRATION_DEFAULTS.sampleWindowSize),
}
this.samples = this.samples.slice(-this.settings.sampleWindowSize)
this.precisionBoundaryServerMs = undefined
this.emit()
this.scheduleNext()
return this.getEstimate()
}
async start() {
this.userMonitoring = true
await this.probeNow().catch(() => undefined)
this.scheduleNext()
return this.getEstimate()
}
stop() {
this.userMonitoring = false
this.scheduleNext()
this.emit()
return this.getEstimate()
}
setAutoTarget(targetServerTimeMs?: number) {
this.autoTargetServerTimeMs = targetServerTimeMs
if (targetServerTimeMs) void this.probeNow().catch(() => undefined)
this.scheduleNext()
}
async ensureSample() {
if (this.getEstimate().acceptedSamples === 0) await this.probeNow()
return this.getEstimate()
}
async probeNow(): Promise<ClockSample> {
if (this.inFlight) return this.inFlight
this.inFlight = this.performProbe().finally(() => { this.inFlight = undefined })
return this.inFlight
}
private async performProbe(): Promise<ClockSample> {
try {
const response = await requestKeyescape({
method: 'HEAD',
path: `/?clock_probe=${Date.now()}-${this.sequence + 1}`,
headers: {
...edgeBrowserHeaders({ referer: 'https://www.keyescape.com/' }),
'Cache-Control': 'no-cache, no-store, max-age=0',
Pragma: 'no-cache',
},
timeoutMs: 5_000,
})
const sample = observationToSample({
id: ++this.sequence,
sentAtMs: response.sentAtMs,
receivedAtMs: response.receivedAtMs,
rttMs: response.rttMs,
serverDateHeader: headerValue(response.headers.date),
remoteIp: response.remoteIp,
reusedSocket: response.reusedSocket,
ageHeader: headerValue(response.headers.age),
viaHeader: headerValue(response.headers.via),
cacheHeader: headerValue(response.headers['x-cache']),
statusCode: response.statusCode,
})
if (sample.accepted && sample.rttMs > this.settings.maxProbeRttMs) {
sample.accepted = false
sample.rejectionReason = `설정된 최대 RTT ${this.settings.maxProbeRttMs}ms 초과`
}
const previousIp = this.getEstimate().remoteIp
this.samples = appendClockSample(this.samples, sample, this.settings.sampleWindowSize)
if (sample.accepted && previousIp && sample.remoteIp !== previousIp) this.precisionBoundaryServerMs = undefined
this.lastError = undefined
this.emit()
return sample
} catch (error) {
this.lastError = error instanceof Error ? error.message : '서버시간 측정에 실패했습니다.'
this.emit()
throw error
} finally {
this.scheduleNext()
}
}
async runTimingTest(request: TimingTestRequest): Promise<TimingTestResult> {
if (!Number.isFinite(request.targetServerTimeMs)) throw new Error('테스트 목표 시각이 올바르지 않습니다.')
if (!Number.isFinite(request.userOffsetMs) || Math.abs(request.userOffsetMs) > 5_000) {
throw new Error('오프셋은 -5000ms에서 +5000ms 사이여야 합니다.')
}
const estimate = await this.ensureSample()
const plannedSendAtMs = computePlannedSendAtMs(request.targetServerTimeMs, request.userOffsetMs, estimate)
const delay = plannedSendAtMs - Date.now()
if (delay < 150 || delay > 60_000) throw new Error('시간 테스트는 0.15초에서 60초 이내의 미래 시각만 사용할 수 있습니다.')
await new Promise<void>((resolve) => setTimeout(resolve, delay))
const estimateAtSend = this.getEstimate()
const sample = await this.probeNow()
const estimatedArrivalServerMs = sample.sentAtMs + estimateAtSend.offsetMs + sample.rttMs / 2
const effectiveTarget = request.targetServerTimeMs + request.userOffsetMs
return {
targetServerTimeMs: request.targetServerTimeMs,
plannedSendAtMs,
actualSendAtMs: sample.sentAtMs,
estimatedArrivalServerMs,
arrivalErrorMs: estimatedArrivalServerMs - effectiveTarget,
schedulerJitterMs: sample.sentAtMs - plannedSendAtMs,
rttMs: sample.rttMs,
uncertaintyMs: estimateAtSend.uncertaintyMs,
remoteIp: sample.remoteIp,
reusedSocket: sample.reusedSocket,
}
}
dispose() {
this.userMonitoring = false
this.autoTargetServerTimeMs = undefined
if (this.timer) clearTimeout(this.timer)
this.timer = undefined
this.samples = []
this.precisionBoundaryServerMs = undefined
}
private isRunning() {
return this.userMonitoring || this.autoTargetServerTimeMs !== undefined
}
private regularInterval() {
if (!this.autoTargetServerTimeMs) return BASE_INTERVAL_MS
const estimate = this.getEstimate()
const remaining = this.autoTargetServerTimeMs - estimate.estimatedServerTimeMs
if (remaining <= 2_000) return FINAL_INTERVAL_MS
if (remaining <= 15_000) return NEAR_INTERVAL_MS
return BASE_INTERVAL_MS
}
private precisionInterval() {
if (!this.settings.enabled || this.getEstimate().acceptedSamples === 0) return Number.POSITIVE_INFINITY
const now = Date.now()
let estimate = this.getEstimate()
// The first Date sample has an unknown phase within its one-second bucket.
// Scan continuously only until one transition is found, then probe narrowly
// around predicted boundaries to avoid permanent high request rates.
if (estimate.boundaryCount === 0) return Math.max(75, this.settings.probeIntervalMs)
if (this.precisionBoundaryServerMs === undefined) {
const boundaryBasedServerNow = now + (estimate.boundaryOffsetMs ?? estimate.offsetMs)
this.precisionBoundaryServerMs = Math.ceil((boundaryBasedServerNow + this.settings.scanWindowMs + 25) / 1_000) * 1_000
}
let localBoundary = this.precisionBoundaryServerMs - (estimate.boundaryOffsetMs ?? estimate.offsetMs)
while (now > localBoundary + this.settings.scanWindowMs) {
const spacingSec = estimate.calibrationReady
? this.settings.maintenanceIntervalSec
: this.settings.initialBoundarySpacingSec
this.precisionBoundaryServerMs += spacingSec * 1_000
estimate = this.getEstimate()
localBoundary = this.precisionBoundaryServerMs - (estimate.boundaryOffsetMs ?? estimate.offsetMs)
}
const scanStartsAt = localBoundary - this.settings.scanWindowMs
if (now < scanStartsAt) return Math.max(10, scanStartsAt - now)
return this.settings.probeIntervalMs
}
private nextInterval() {
return Math.min(this.regularInterval(), this.precisionInterval())
}
private scheduleNext() {
if (this.timer) clearTimeout(this.timer)
this.timer = undefined
if (!this.isRunning()) return
this.timer = setTimeout(() => void this.probeNow().catch(() => undefined), this.nextInterval())
}
private emit() {
broadcast(CLOCK_EVENT, this.getEstimate())
}
}
export const serverClock = new ServerClockService()
export function registerClockHandlers() {
const safe = async <T>(task: () => T | Promise<T>) => {
try {
return { ok: true, data: await task() }
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : '시간 기능 오류가 발생했습니다.' }
}
}
ipcMain.handle('reservation:clock-start', () => safe(() => serverClock.start()))
ipcMain.handle('reservation:clock-stop', () => safe(() => serverClock.stop()))
ipcMain.handle('reservation:clock-get', () => safe(() => serverClock.getEstimate()))
ipcMain.handle('reservation:clock-configure', (_event, settings: ClockCalibrationSettings) => safe(() => serverClock.configure(settings)))
ipcMain.handle('reservation:clock-test', (_event, request: TimingTestRequest) => safe(() => serverClock.runTimingTest(request)))
}