This commit is contained in:
dahyeon committed 2026-08-12 10:48:33 -07:00
1 parent 7dbbf22515
commit 499890cdaa
6 files changed
+35 -3

No files matched your search

+3 -2
View File
@@ -7,7 +7,7 @@ import type {
ClockEstimate, ClockEstimate,
ReservationRequest, ReservationRequest,
} from '../../src/type/reservation' } from '../../src/type/reservation'
import { executeReservation } from './reservation' import { executeReservation, executeReservationConcurrent } from './reservation'
import { serverClock } from './server-clock' import { serverClock } from './server-clock'
import { computePlannedSendAtMs } from './server-clock-core' import { computePlannedSendAtMs } from './server-clock-core'
@@ -60,7 +60,7 @@ export class AutoSalvoService {
getEstimate(): ClockEstimate getEstimate(): ClockEstimate
setAutoTarget(targetServerTimeMs?: number): void setAutoTarget(targetServerTimeMs?: number): void
} = serverClock, } = serverClock,
private readonly execute: (request: ReservationRequest) => Promise<Awaited<ReturnType<typeof executeReservation>>> = executeReservation, private readonly execute: (request: ReservationRequest) => Promise<Awaited<ReturnType<typeof executeReservation>>> = executeReservationConcurrent,
private readonly emitState: (state: AutoSalvoState) => void = broadcast, private readonly emitState: (state: AutoSalvoState) => void = broadcast,
) {} ) {}
@@ -228,6 +228,7 @@ export class AutoSalvoService {
arrivalErrorMs: estimatedArrivalServerMs === undefined ? undefined : estimatedArrivalServerMs - next.attempt.effectiveTargetServerMs, arrivalErrorMs: estimatedArrivalServerMs === undefined ? undefined : estimatedArrivalServerMs - next.attempt.effectiveTargetServerMs,
rttMs: transport?.rttMs, rttMs: transport?.rttMs,
httpStatus: transport?.httpStatus, httpStatus: transport?.httpStatus,
serverDateMs: transport?.observedServerDateMs,
}) })
if (result.success) { if (result.success) {
this.state = { ...this.state, succeededIndex: next.attempt.index, result } this.state = { ...this.state, succeededIndex: next.attempt.index, result }
+6
View File
@@ -341,6 +341,12 @@ export async function executeReservation(rawRequest: ReservationRequest): Promis
} }
} }
// 다중 시도(살보)용: 단일 실행 잠금을 거치지 않고 각 시도를 실제로 병렬 전송한다.
// 각 시도가 서로 다른 토큰을 소비하므로 잠금으로 서로를 막지 않는다.
export function executeReservationConcurrent(rawRequest: ReservationRequest): Promise<ReservationResult> {
return executeReservationOnce(rawRequest)
}
function handle<TArgs extends unknown[], TResult>( function handle<TArgs extends unknown[], TResult>(
channel: string, channel: string,
handler: (...args: TArgs) => Promise<TResult>, handler: (...args: TArgs) => Promise<TResult>,
+10 -1
View File
@@ -75,6 +75,13 @@ function parseKstInput(value: string) {
) )
} }
// 서버가 응답 Date 헤더로 알려준 서버 시각을 분:초만 표시한다 (HTTP Date는 초 단위).
function formatServerMmSs(epochMs: number) {
return new Intl.DateTimeFormat('en-GB', {
timeZone: 'Asia/Seoul', hour12: false, minute: '2-digit', second: '2-digit',
}).format(epochMs)
}
function formatClock(epochMs: number) { function formatClock(epochMs: number) {
return new Intl.DateTimeFormat('ko-KR', { return new Intl.DateTimeFormat('ko-KR', {
timeZone: 'Asia/Seoul', timeZone: 'Asia/Seoul',
@@ -517,7 +524,8 @@ export default function AutomationPanel({
<label className="flex items-center gap-2 text-[10px] font-semibold text-ink-muted"><input type="checkbox" checked={stopOnSuccess} onChange={(event) => setStopOnSuccess(event.target.checked)} disabled={salvoArmed} className="accent-coral" />첫 성공 시 이후 취소</label> <label className="flex items-center gap-2 text-[10px] font-semibold text-ink-muted"><input type="checkbox" checked={stopOnSuccess} onChange={(event) => setStopOnSuccess(event.target.checked)} disabled={salvoArmed} className="accent-coral" />첫 성공 시 이후 취소</label>
{attemptCount > 0 && !salvoArmed && <button onClick={() => setOffsets(defaultSalvoOffsets(attemptCount))} className="rounded-lg border border-line px-2.5 py-1.5 text-[10px] font-semibold text-ink-muted hover:text-ink">오프셋 기본값</button>} {attemptCount > 0 && !salvoArmed && <button onClick={() => setOffsets(defaultSalvoOffsets(attemptCount))} className="rounded-lg border border-line px-2.5 py-1.5 text-[10px] font-semibold text-ink-muted hover:text-ink">오프셋 기본값</button>}
</div> </div>
{attemptCount > 0 && <p className="mt-2 text-[10px] leading-4 text-ink-muted">시도 <span className="font-semibold text-ink">{attemptCount}</span>개 · 오프셋 <span className="font-mono text-ink">{salvoTokenState.map((item) => `${item.offsetMs >= 0 ? '+' : ''}${item.offsetMs}`).join(' / ')}</span> ms · 목표 시각 대비 각 시도가 이 오프셋에서 발사됩니다.</p>} {attemptCount > 0 && <p className="mt-2 text-[10px] leading-4 text-ink-muted">시도 <span className="font-semibold text-ink">{attemptCount}</span>개 · 오프셋 <span className="font-mono text-ink">{salvoTokenState.map((item) => `${item.offsetMs >= 0 ? '+' : ''}${item.offsetMs}`).join(' / ')}</span> ms · 각 시도가 목표 시각 대비 이 오프셋에서 실제로 병렬 전송됩니다.</p>}
{attemptCount > 1 && !stopOnSuccess && <p className="mt-1 text-[10px] leading-4 text-warning">‘첫 성공 시 이후 취소’를 끄면 여러 시도가 동시에 성공해 중복 예약될 수 있습니다.</p>}
{salvoState.attempts.length > 0 && ( {salvoState.attempts.length > 0 && (
<div className="mt-3 overflow-hidden rounded-xl border border-line-soft"> <div className="mt-3 overflow-hidden rounded-xl border border-line-soft">
@@ -548,6 +556,7 @@ export default function AutomationPanel({
<DetailRow label="실제 발송" value={attempt.actualSendAtMs === undefined ? '—' : formatClock(attempt.actualSendAtMs)} /> <DetailRow label="실제 발송" value={attempt.actualSendAtMs === undefined ? '—' : formatClock(attempt.actualSendAtMs)} />
<DetailRow label="도착 오차" value={attempt.arrivalErrorMs === undefined ? '—' : `${attempt.arrivalErrorMs >= 0 ? '+' : ''}${attempt.arrivalErrorMs.toFixed(1)}ms`} /> <DetailRow label="도착 오차" value={attempt.arrivalErrorMs === undefined ? '—' : `${attempt.arrivalErrorMs >= 0 ? '+' : ''}${attempt.arrivalErrorMs.toFixed(1)}ms`} />
<DetailRow label="응답 RTT" value={attempt.rttMs === undefined ? '—' : `${attempt.rttMs.toFixed(1)}ms`} /> <DetailRow label="응답 RTT" value={attempt.rttMs === undefined ? '—' : `${attempt.rttMs.toFixed(1)}ms`} />
<DetailRow label="서버 응답 시각" value={attempt.serverDateMs === undefined ? '—' : formatServerMmSs(attempt.serverDateMs)} />
<DetailRow label="HTTP 상태" value={attempt.httpStatus === undefined ? '—' : String(attempt.httpStatus)} /> <DetailRow label="HTTP 상태" value={attempt.httpStatus === undefined ? '—' : String(attempt.httpStatus)} />
</dl> </dl>
) : ( ) : (
+1
View File
@@ -245,6 +245,7 @@ export interface AutoSalvoAttempt {
arrivalErrorMs?: number arrivalErrorMs?: number
rttMs?: number rttMs?: number
httpStatus?: number httpStatus?: number
serverDateMs?: number
status: 'pending' | 'firing' | 'succeeded' | 'failed' | 'skipped' status: 'pending' | 'firing' | 'succeeded' | 'failed' | 'skipped'
message?: string message?: string
reservationNum?: string reservationNum?: string
+15
View File
@@ -82,6 +82,21 @@ describe('multi-attempt (salvo) auto reservation scheduler', () => {
expect(service.getState().attempts.map((attempt) => attempt.status)).toEqual(['failed', 'failed', 'failed']) expect(service.getState().attempts.map((attempt) => attempt.status)).toEqual(['failed', 'failed', 'failed'])
}) })
it('fires every attempt in parallel without waiting for earlier requests to resolve', async () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
// 첫 요청이 계속 진행 중이어도(응답 없음) 뒤 시도들이 자기 시각에 발사되어야 한다.
const execute = vi.fn<() => Promise<ReservationResult>>().mockImplementation(() => new Promise<ReservationResult>(() => {}))
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)
expect(service.getState().status).toBe('firing')
})
it('cancels remaining attempts after the first success when stopOnSuccess is set', async () => { it('cancels remaining attempts after the first success when stopOnSuccess is set', async () => {
vi.useFakeTimers() vi.useFakeTimers()
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z')) vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 90 KiB