.
This commit is contained in:
1 parent
db60190e19
commit
843e6435cc
9 files changed
+663
-7
No files matched your search
@@ -0,0 +1,303 @@
|
||||
import { app, BrowserWindow, ipcMain } from 'electron'
|
||||
import type {
|
||||
AutoReservationSnapshot,
|
||||
AutoSalvoAttempt,
|
||||
AutoSalvoConfig,
|
||||
AutoSalvoState,
|
||||
ClockEstimate,
|
||||
ReservationRequest,
|
||||
} from '../../src/type/reservation'
|
||||
import { executeReservation } from './reservation'
|
||||
import { serverClock } from './server-clock'
|
||||
import { computePlannedSendAtMs } from './server-clock-core'
|
||||
|
||||
const SALVO_EVENT = 'reservation:salvo-state'
|
||||
const MAX_TOKEN_TARGET_AGE_MS = 90_000
|
||||
const MAX_ATTEMPTS = 8
|
||||
const MAX_OFFSET_MS = 10_000
|
||||
const MAX_LATE_FIRE_MS = 1_500
|
||||
|
||||
function broadcast(value: AutoSalvoState) {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) window.webContents.send(SALVO_EVENT, value)
|
||||
}
|
||||
}
|
||||
|
||||
function snapshot(base: Omit<ReservationRequest, 'captchaToken'>): AutoReservationSnapshot {
|
||||
return {
|
||||
branchNum: base.branchNum,
|
||||
themeNum: base.themeNum,
|
||||
themeInfoNum: base.themeInfoNum,
|
||||
date: base.date,
|
||||
timeNum: base.timeNum,
|
||||
timeLabel: base.timeLabel,
|
||||
themeName: base.themeName,
|
||||
totalPrice: base.totalPrice,
|
||||
person: base.person,
|
||||
}
|
||||
}
|
||||
|
||||
interface PlannedAttempt {
|
||||
attempt: AutoSalvoAttempt
|
||||
captchaToken: string
|
||||
plannedSendAtMs: number
|
||||
frozenOffsetMs: number
|
||||
frozenOneWayMs: number
|
||||
fired: boolean
|
||||
}
|
||||
|
||||
export class AutoSalvoService {
|
||||
private base?: Omit<ReservationRequest, 'captchaToken'>
|
||||
private planned: PlannedAttempt[] = []
|
||||
private timer?: NodeJS.Timeout
|
||||
private inFlight = 0
|
||||
private stopOnSuccess = true
|
||||
private state: AutoSalvoState = { status: 'idle', stopOnSuccess: true, attempts: [] }
|
||||
|
||||
constructor(
|
||||
private readonly clock: {
|
||||
ensureSample(): Promise<ClockEstimate>
|
||||
getEstimate(): ClockEstimate
|
||||
setAutoTarget(targetServerTimeMs?: number): void
|
||||
} = serverClock,
|
||||
private readonly execute: (request: ReservationRequest) => Promise<Awaited<ReturnType<typeof executeReservation>>> = executeReservation,
|
||||
private readonly emitState: (state: AutoSalvoState) => void = broadcast,
|
||||
) {}
|
||||
|
||||
getState() {
|
||||
return this.state
|
||||
}
|
||||
|
||||
async arm(input: AutoSalvoConfig) {
|
||||
if (this.state.status === 'armed' || this.state.status === 'firing') {
|
||||
throw new Error('이미 다중 시도가 진행 중입니다.')
|
||||
}
|
||||
if (!Number.isFinite(input.targetServerTimeMs)) throw new Error('실행 시각이 올바르지 않습니다.')
|
||||
if (!Number.isFinite(input.userOffsetMs) || input.userOffsetMs < -5_000 || input.userOffsetMs > 5_000) {
|
||||
throw new Error('사용자 오프셋은 -5000ms에서 +5000ms 사이여야 합니다.')
|
||||
}
|
||||
if (input.attempts.length === 0) throw new Error('시도가 하나도 없습니다. 토큰을 먼저 생성해주세요.')
|
||||
if (input.attempts.length > MAX_ATTEMPTS) throw new Error(`시도는 최대 ${MAX_ATTEMPTS}개까지 가능합니다.`)
|
||||
|
||||
const seenTokens = new Set<string>()
|
||||
for (const attempt of input.attempts) {
|
||||
if (attempt.captchaToken.trim().length < 30) throw new Error('각 시도에는 유효한 캡차 토큰이 필요합니다.')
|
||||
if (seenTokens.has(attempt.captchaToken)) throw new Error('같은 캡차 토큰을 두 번 사용할 수 없습니다.')
|
||||
seenTokens.add(attempt.captchaToken)
|
||||
if (!Number.isFinite(attempt.offsetMs) || Math.abs(attempt.offsetMs) > MAX_OFFSET_MS) {
|
||||
throw new Error(`오프셋은 ±${MAX_OFFSET_MS}ms 이내여야 합니다.`)
|
||||
}
|
||||
if (!Number.isFinite(attempt.captchaSolvedAtMs) || attempt.captchaSolvedAtMs > Date.now()) {
|
||||
throw new Error('캡차 토큰 생성 시각이 올바르지 않습니다.')
|
||||
}
|
||||
}
|
||||
|
||||
const estimate = await this.clock.ensureSample()
|
||||
if (estimate.acceptedSamples === 0) throw new Error('유효한 서버시간 표본이 없어 다중 시도를 시작할 수 없습니다.')
|
||||
if (input.targetServerTimeMs <= estimate.estimatedServerTimeMs + 150) {
|
||||
throw new Error('실행 시각은 현재 관측 서버시각보다 최소 0.15초 이후여야 합니다.')
|
||||
}
|
||||
|
||||
const planned: PlannedAttempt[] = input.attempts.map((raw, index) => {
|
||||
const combinedOffsetMs = input.userOffsetMs + raw.offsetMs
|
||||
const effectiveTargetServerMs = input.targetServerTimeMs + combinedOffsetMs
|
||||
const targetLocalTimeMs = effectiveTargetServerMs - estimate.offsetMs
|
||||
const tokenAgeAtTargetMs = targetLocalTimeMs - raw.captchaSolvedAtMs
|
||||
if (tokenAgeAtTargetMs < 0 || tokenAgeAtTargetMs > MAX_TOKEN_TARGET_AGE_MS) {
|
||||
throw new Error(`${raw.offsetMs >= 0 ? '+' : ''}${raw.offsetMs}ms 시도의 토큰이 목표 시각에 90초를 초과합니다. 토큰을 다시 생성하거나 오프셋을 줄여주세요.`)
|
||||
}
|
||||
const plannedSendAtMs = computePlannedSendAtMs(input.targetServerTimeMs, combinedOffsetMs, estimate)
|
||||
return {
|
||||
attempt: {
|
||||
index,
|
||||
offsetMs: raw.offsetMs,
|
||||
effectiveTargetServerMs,
|
||||
plannedSendAtMs,
|
||||
status: 'pending',
|
||||
},
|
||||
captchaToken: raw.captchaToken,
|
||||
plannedSendAtMs,
|
||||
frozenOffsetMs: estimate.offsetMs,
|
||||
frozenOneWayMs: estimate.oneWayMs,
|
||||
fired: false,
|
||||
}
|
||||
})
|
||||
planned.sort((a, b) => a.plannedSendAtMs - b.plannedSendAtMs)
|
||||
|
||||
this.base = input.baseRequest
|
||||
this.planned = planned
|
||||
this.stopOnSuccess = input.stopOnSuccess
|
||||
this.inFlight = 0
|
||||
this.state = {
|
||||
status: 'armed',
|
||||
targetServerTimeMs: input.targetServerTimeMs,
|
||||
userOffsetMs: input.userOffsetMs,
|
||||
armedAtMs: Date.now(),
|
||||
stopOnSuccess: input.stopOnSuccess,
|
||||
snapshot: snapshot(input.baseRequest),
|
||||
attempts: planned.map((item) => item.attempt),
|
||||
warning: estimate.quality === 'poor' || (estimate.calibrationSettings.enabled && !estimate.calibrationReady) ? estimate.warning : undefined,
|
||||
}
|
||||
this.clock.setAutoTarget(planned[0].attempt.effectiveTargetServerMs)
|
||||
this.emit()
|
||||
this.scheduleNext()
|
||||
return this.state
|
||||
}
|
||||
|
||||
disarm(message = '다중 시도가 해제되었습니다.') {
|
||||
if (this.state.status === 'firing') return this.state
|
||||
this.clearTimer()
|
||||
this.planned = []
|
||||
this.base = undefined
|
||||
this.clock.setAutoTarget(undefined)
|
||||
this.state = { status: 'cancelled', stopOnSuccess: this.stopOnSuccess, attempts: this.state.attempts, message }
|
||||
this.emit()
|
||||
return this.state
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.clearTimer()
|
||||
this.planned = []
|
||||
this.base = undefined
|
||||
this.inFlight = 0
|
||||
this.clock.setAutoTarget(undefined)
|
||||
this.state = { status: 'idle', stopOnSuccess: true, attempts: [] }
|
||||
this.emit()
|
||||
}
|
||||
|
||||
private clearTimer() {
|
||||
if (this.timer) clearTimeout(this.timer)
|
||||
this.timer = undefined
|
||||
}
|
||||
|
||||
private nextPending() {
|
||||
return this.planned.find((item) => !item.fired)
|
||||
}
|
||||
|
||||
private scheduleNext() {
|
||||
this.clearTimer()
|
||||
if (this.state.status !== 'armed' && this.state.status !== 'firing') return
|
||||
const next = this.nextPending()
|
||||
if (!next) return
|
||||
const delayMs = Math.max(0, next.plannedSendAtMs - Date.now())
|
||||
this.timer = setTimeout(() => this.fireDue(), Math.min(delayMs, 60_000))
|
||||
}
|
||||
|
||||
private fireDue() {
|
||||
this.clearTimer()
|
||||
const next = this.nextPending()
|
||||
if (!next) return
|
||||
// 아직 발사 시각이 남았으면(타이머 상한/절전 복귀) 다시 대기한다.
|
||||
const remainingMs = next.plannedSendAtMs - Date.now()
|
||||
if (remainingMs > 20) {
|
||||
this.scheduleNext()
|
||||
return
|
||||
}
|
||||
next.fired = true
|
||||
|
||||
const estimate = this.clock.getEstimate()
|
||||
if (estimate.acceptedSamples === 0) {
|
||||
this.markAttempt(next, { status: 'skipped', message: '유효한 서버시간 표본이 없어 건너뜀' })
|
||||
this.afterAttemptSettled()
|
||||
this.scheduleNext()
|
||||
return
|
||||
}
|
||||
if (estimate.estimatedServerTimeMs > next.attempt.effectiveTargetServerMs + MAX_LATE_FIRE_MS) {
|
||||
this.markAttempt(next, { status: 'skipped', message: '목표 시각이 지나 건너뜀' })
|
||||
this.afterAttemptSettled()
|
||||
this.scheduleNext()
|
||||
return
|
||||
}
|
||||
|
||||
if (this.state.status === 'armed') {
|
||||
this.state = { ...this.state, status: 'firing' }
|
||||
}
|
||||
this.markAttempt(next, { status: 'firing' })
|
||||
this.inFlight += 1
|
||||
void this.execute({ ...this.base!, captchaToken: next.captchaToken } as ReservationRequest)
|
||||
.then((result) => {
|
||||
const transport = result.transport
|
||||
const estimatedArrivalServerMs = transport
|
||||
? transport.sentAtMs + next.frozenOffsetMs + next.frozenOneWayMs
|
||||
: undefined
|
||||
this.markAttempt(next, {
|
||||
status: result.success ? 'succeeded' : 'failed',
|
||||
message: result.message,
|
||||
reservationNum: result.reservationNum,
|
||||
actualSendAtMs: transport?.sentAtMs,
|
||||
arrivalErrorMs: estimatedArrivalServerMs === undefined ? undefined : estimatedArrivalServerMs - next.attempt.effectiveTargetServerMs,
|
||||
rttMs: transport?.rttMs,
|
||||
httpStatus: transport?.httpStatus,
|
||||
})
|
||||
if (result.success) {
|
||||
this.state = { ...this.state, succeededIndex: next.attempt.index, result }
|
||||
if (this.stopOnSuccess) this.cancelRemaining('먼저 성공한 시도가 있어 이후 시도를 취소했습니다.')
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
this.markAttempt(next, { status: 'failed', message: error instanceof Error ? error.message : '요청 실패' })
|
||||
})
|
||||
.finally(() => {
|
||||
this.inFlight -= 1
|
||||
this.afterAttemptSettled()
|
||||
})
|
||||
|
||||
this.scheduleNext()
|
||||
}
|
||||
|
||||
private cancelRemaining(message: string) {
|
||||
this.clearTimer()
|
||||
for (const item of this.planned) {
|
||||
if (!item.fired) {
|
||||
item.fired = true
|
||||
this.markAttempt(item, { status: 'skipped', message })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private afterAttemptSettled() {
|
||||
if (this.nextPending() || this.inFlight > 0) return
|
||||
const attempts = this.state.attempts
|
||||
const succeeded = attempts.some((attempt) => attempt.status === 'succeeded')
|
||||
const anyFired = attempts.some((attempt) => attempt.status === 'succeeded' || attempt.status === 'failed')
|
||||
this.clock.setAutoTarget(undefined)
|
||||
this.state = {
|
||||
...this.state,
|
||||
status: succeeded ? 'succeeded' : anyFired ? 'failed' : 'cancelled',
|
||||
message: succeeded
|
||||
? '한 시도가 성공하여 예약이 접수되었습니다.'
|
||||
: anyFired ? '모든 시도가 실패했습니다.' : '실행된 시도가 없습니다.',
|
||||
}
|
||||
this.emit()
|
||||
}
|
||||
|
||||
private markAttempt(planned: PlannedAttempt, patch: Partial<AutoSalvoAttempt>) {
|
||||
planned.attempt = { ...planned.attempt, ...patch }
|
||||
this.state = {
|
||||
...this.state,
|
||||
attempts: this.state.attempts.map((attempt) => attempt.index === planned.attempt.index ? planned.attempt : attempt),
|
||||
}
|
||||
this.emit()
|
||||
}
|
||||
|
||||
private emit() {
|
||||
this.emitState(this.state)
|
||||
}
|
||||
}
|
||||
|
||||
export const autoSalvo = new AutoSalvoService()
|
||||
|
||||
export function registerAutoSalvoHandlers() {
|
||||
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:salvo-arm', (_event, config: AutoSalvoConfig) => safe(() => autoSalvo.arm(config)))
|
||||
ipcMain.handle('reservation:salvo-disarm', () => safe(() => autoSalvo.disarm()))
|
||||
ipcMain.handle('reservation:salvo-get', () => safe(() => autoSalvo.getState()))
|
||||
ipcMain.on('reservation:renderer-unload', () => autoSalvo.reset())
|
||||
app.once('before-quit', () => autoSalvo.reset())
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { registerReservationHandlers } from './reservation'
|
||||
import { registerAutoReservationHandlers } from './auto-reservation'
|
||||
import { registerAutoSalvoHandlers } from './auto-salvo'
|
||||
import { registerClockHandlers } from './server-clock'
|
||||
|
||||
registerReservationHandlers()
|
||||
registerClockHandlers()
|
||||
registerAutoReservationHandlers()
|
||||
registerAutoSalvoHandlers()
|
||||
Reference in new issue
Block a user