import { afterEach, describe, expect, it, vi } from 'vitest' import { AutoSalvoService } from '../electron/main/auto-salvo' import { CLOCK_CALIBRATION_DEFAULTS, type AutoSalvoConfig, type ClockEstimate, type ReservationResult } from '../src/type/reservation' function estimate(): ClockEstimate { const now = Date.now() return { monitoring: true, observedAtMs: now, estimatedServerTimeMs: now, offsetMs: 0, driftPpm: 0, minRttMs: 60, p50RttMs: 62, p95RttMs: 70, oneWayMs: 0, uncertaintyMs: 400, sampleAgeMs: 0, acceptedSamples: 8, rawOffsetMs: 0, boundaryCount: 5, boundaryOffsetMs: 0, boundaryUncertaintyMs: 40, boundarySpreadMs: 15, recommendedCorrectionMs: 0, calibrationReady: true, calibrationApplied: true, calibrationSettings: CLOCK_CALIBRATION_DEFAULTS, remoteIp: '13.125.18.86', quality: 'fair', samples: [], } } function config(targetServerTimeMs: number, tokenCount: number, stepMs: number, stopOnSuccess = false): AutoSalvoConfig { const solvedAtMs = Date.now() const attempts = Array.from({ length: tokenCount }, (_, index) => ({ offsetMs: Math.round((index - (tokenCount - 1) / 2) * stepMs), captchaToken: `token-${index}-${'x'.repeat(40)}`, captchaSolvedAtMs: solvedAtMs, })) return { targetServerTimeMs, userOffsetMs: 0, stopOnSuccess, attempts, baseRequest: { branchNum: 22, themeNum: 66, themeInfoNum: 44, date: '2026-08-18', timeNum: 2309, timeLabel: '14:25', themeName: '내 방', totalPrice: 60_000, person: 2, name: '테스트', phone: '010-1234-5678', }, } } function result(reservationNum: string, success = true): ReservationResult { return { success, message: success ? '완료' : '실패', reservationNum: success ? reservationNum : undefined, transport: { sentAtMs: Date.now(), receivedAtMs: Date.now() + 60, rttMs: 60, httpStatus: success ? 200 : 409, remoteIp: '13.125.18.86', reusedSocket: false, }, } } describe('multi-attempt (salvo) auto reservation scheduler', () => { afterEach(() => vi.useRealTimers()) it('fires one attempt per token at each ± offset', async () => { vi.useFakeTimers() vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z')) const execute = vi.fn<() => Promise>().mockImplementation(async () => result('R', false)) const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() } const service = new AutoSalvoService(clock, execute, vi.fn()) await service.arm(config(Date.now() + 2_000, 3, 300)) await vi.advanceTimersByTimeAsync(3_000) expect(execute).toHaveBeenCalledTimes(3) const tokensUsed = execute.mock.calls.map((call) => (call[0] as { captchaToken: string }).captchaToken) expect(new Set(tokensUsed).size).toBe(3) expect(service.getState().status).toBe('failed') expect(service.getState().attempts.map((attempt) => attempt.status)).toEqual(['failed', 'failed', 'failed']) }) it('cancels remaining attempts after the first success when stopOnSuccess is set', async () => { vi.useFakeTimers() vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z')) const execute = vi.fn<() => Promise>().mockResolvedValue(result('R-1')) const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() } const service = new AutoSalvoService(clock, execute, vi.fn()) await service.arm(config(Date.now() + 2_000, 4, 300, true)) await vi.advanceTimersByTimeAsync(4_000) expect(execute).toHaveBeenCalledTimes(1) const state = service.getState() expect(state.status).toBe('succeeded') expect(state.succeededIndex).toBe(0) expect(state.attempts.filter((attempt) => attempt.status === 'skipped')).toHaveLength(3) }) it('rejects a token that would be older than 90s at its target', async () => { vi.useFakeTimers() vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z')) const execute = vi.fn<() => Promise>() const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() } const service = new AutoSalvoService(clock, execute, vi.fn()) await expect(service.arm(config(Date.now() + 120_000, 2, 300))).rejects.toThrow(/90초/) expect(execute).not.toHaveBeenCalled() }) it('disarming clears the schedule and prevents submission', async () => { vi.useFakeTimers() vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z')) const execute = vi.fn<() => Promise>() const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() } const service = new AutoSalvoService(clock, execute, vi.fn()) await service.arm(config(Date.now() + 2_000, 3, 300)) service.disarm() await vi.advanceTimersByTimeAsync(3_000) expect(execute).not.toHaveBeenCalled() expect(service.getState().status).toBe('cancelled') }) })