Merge pull request '261112_02_ENH: CTI 통화 이력 복구·재시도 로직 제거 및 시작·종료 저장 단일 요청으로 간소화' (#76) from develop into master

Reviewed-on: #76
This commit is contained in:
2026-11-12 15:20:09 +09:00
4 changed files with 41 additions and 275 deletions

View File

@@ -2,25 +2,7 @@ import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {createContactApi} from "@/lib/http-server";
import {errorToResponse} from "@kri/common/http";
import type {ListCallHist, ListCallHistSession} from "@/types/list";
export const GET = async (_req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action, agentSessionId] = slug;
if (action !== "session" || !agentSessionId) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const contactApi = await createContactApi();
const result = await contactApi.get<ListCallHistSession>(
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`,
);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};
import type {ListCallHist} from "@/types/list";
export const PUT = async (req: NextRequest, context: RouteContext) => {
try {
@@ -45,21 +27,3 @@ export const PUT = async (req: NextRequest, context: RouteContext) => {
return errorToResponse(error);
}
};
export const PATCH = async (_req: NextRequest, context: RouteContext) => {
try {
const { slug = [] } = await context.params;
const [action, agentSessionId] = slug;
if (action !== "hangup" || !agentSessionId) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
const contactApi = await createContactApi();
const result = await contactApi.patch<boolean>(
`/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`,
);
return NextResponse.json(result, { status: 200 });
} catch (error: unknown) {
return errorToResponse(error);
}
};

View File

@@ -30,5 +30,4 @@ export const CTI_AUTO_RECONNECT_JITTER_MS = 1000;
// 종료 명령의 응답이 없으면 재요청할 수 있게 하되, 실제 종료로 판정하지 않는다.
export const CTI_HANGUP_TIMEOUT_MS = 10 * 1000;
export const CTI_LOGIN_TIMEOUT_MS = 15 * 1000;
export const CTI_HISTORY_RETRY_MS = 5 * 1000;

View File

@@ -9,7 +9,6 @@ import {
CTI_DIALING_TIMEOUT_MS,
CTI_ERROR_ALERT_THROTTLE_MS,
CTI_HANGUP_TIMEOUT_MS,
CTI_HISTORY_RETRY_MS,
CTI_LOGIN_TIMEOUT_MS,
CTI_ON_CALL_STATUSES,
CTI_STATE_TTL_MS,
@@ -50,28 +49,19 @@ type CtiCall = {
agentSessionId: string | null;
// makeCall 시각. 이 값이 없는 dialing 상태(이전 버전 저장분)는 복원 시 만료된 것으로 본다.
dialStartedAt?: number;
pendingStart?: ListCallCloseRequest;
};
type PendingCallClose = {
call: CtiCall;
// null은 재로그인 11로 확인한 종료 이벤트 유실 통화다.
body: ListCallCloseRequest | null;
attempted?: boolean;
};
// 이전 버전이 저장한 closingCall·pendingCallCloses 필드는 복원 시 무시한다.
type PersistedCtiState = {
version: 3;
agentLoginId: string;
agentStatus: string | null;
activeCall: CtiCall | null;
closingCall: CtiCall | null;
lastCallContext: CtiCallContext | null;
lastCallHistId: number | null;
hangupRequested: boolean;
callClosedReceived: boolean;
updatedAt: number;
pendingCallCloses?: PendingCallClose[];
completedSessionIds?: string[];
latestCall?: CtiCall | null;
};
@@ -86,11 +76,10 @@ type LegacyCtiCall = Omit<CtiCall, "context"> & {
type LegacyPersistedCtiState = Omit<
PersistedCtiState,
"version" | "activeCall" | "closingCall" | "lastCallContext"
"version" | "activeCall" | "lastCallContext"
> & {
version: 2;
activeCall: LegacyCtiCall | null;
closingCall: LegacyCtiCall | null;
lastCallContext: LegacyCtiCallContext | null;
};
@@ -103,7 +92,6 @@ let currentConnectionKey: string | null = null;
let currentLoginParams: CtiLoginParams | null = null;
let agentStatus: string | null = null;
let activeCall: CtiCall | null = null;
let closingCall: CtiCall | null = null;
let lastCallContext: CtiCallContext | null = null;
let lastCallHistId: number | null = null;
let hangupRequested = false;
@@ -113,17 +101,13 @@ let autoReconnectAttempt = 0;
let dialingTimeoutId: ReturnType<typeof setTimeout> | null = null;
let loginTimeoutId: ReturnType<typeof setTimeout> | null = null;
let hangupTimeoutId: ReturnType<typeof setTimeout> | null = null;
let historyRetryTimeoutId: ReturnType<typeof setTimeout> | null = null;
let pendingCallCloses: PendingCallClose[] = [];
let completedSessionIds: string[] = [];
let latestCall: CtiCall | null = null;
let loginCompleted = false;
let recoveryCall: CtiCall | null = null;
let ownerGeneration = 0;
const closingRequests = new Set<PendingCallClose>();
const notifiedCloseFailures = new WeakSet<PendingCallClose>();
const startingRequests = new Map<CtiCall, Promise<void>>();
let savedStarts = new WeakSet<CtiCall>();
// 같은 통화의 StartSessionRecord가 중복 수신돼도 시작 저장은 한 번만 보낸다.
const startRequestedCalls = new WeakSet<CtiCall>();
const lastErrorAlertAt = new Map<string, number>();
const listeners = new Set<() => void>();
@@ -205,9 +189,7 @@ const isCtiCall = (value: unknown): value is CtiCall => {
return (
isCallContext(call.context) &&
(call.agentSessionId === null || typeof call.agentSessionId === "string") &&
(call.dialStartedAt === undefined || typeof call.dialStartedAt === "number") &&
(call.pendingStart === undefined ||
(isCloseRequest(call.pendingStart) && call.pendingStart.agentSessionId === call.agentSessionId))
(call.dialStartedAt === undefined || typeof call.dialStartedAt === "number")
);
};
@@ -235,15 +217,6 @@ const isCloseRequest = (value: unknown): value is ListCallCloseRequest => {
);
};
const isPendingCallClose = (value: unknown): value is PendingCallClose => {
if (typeof value !== "object" || value === null) return false;
const pending = value as Partial<PendingCallClose>;
return isCtiCall(pending.call) && pending.call.agentSessionId !== null &&
(pending.body === null ||
(isCloseRequest(pending.body) && pending.body.agentSessionId === pending.call.agentSessionId)) &&
(pending.attempted === undefined || typeof pending.attempted === "boolean");
};
const isPersistedCtiState = (value: unknown): value is PersistedCtiState => {
if (typeof value !== "object" || value === null) return false;
const state = value as Partial<PersistedCtiState>;
@@ -252,14 +225,11 @@ const isPersistedCtiState = (value: unknown): value is PersistedCtiState => {
typeof state.agentLoginId === "string" &&
(state.agentStatus === null || typeof state.agentStatus === "string") &&
(state.activeCall === null || isCtiCall(state.activeCall)) &&
(state.closingCall === null || isCtiCall(state.closingCall)) &&
(state.lastCallContext === null || isCallContext(state.lastCallContext)) &&
(state.lastCallHistId === null || typeof state.lastCallHistId === "number") &&
typeof state.hangupRequested === "boolean" &&
typeof state.callClosedReceived === "boolean" &&
typeof state.updatedAt === "number" &&
(state.pendingCallCloses === undefined ||
(Array.isArray(state.pendingCallCloses) && state.pendingCallCloses.every(isPendingCallClose))) &&
(state.completedSessionIds === undefined ||
(Array.isArray(state.completedSessionIds) && state.completedSessionIds.every((id) => typeof id === "string"))) &&
(state.latestCall === undefined || state.latestCall === null || isCtiCall(state.latestCall))
@@ -274,7 +244,6 @@ const isLegacyPersistedCtiState = (value: unknown): value is LegacyPersistedCtiS
typeof state.agentLoginId === "string" &&
(state.agentStatus === null || typeof state.agentStatus === "string") &&
(state.activeCall === null || isLegacyCtiCall(state.activeCall)) &&
(state.closingCall === null || isLegacyCtiCall(state.closingCall)) &&
(state.lastCallContext === null || isLegacyCallContext(state.lastCallContext)) &&
(state.lastCallHistId === null || typeof state.lastCallHistId === "number") &&
typeof state.hangupRequested === "boolean" &&
@@ -303,7 +272,6 @@ const toPersistedCtiState = (value: unknown): PersistedCtiState | null => {
...value,
version: CTI_STATE_VERSION,
activeCall: migrateLegacyCall(value.activeCall),
closingCall: migrateLegacyCall(value.closingCall),
lastCallContext: value.lastCallContext ? migrateLegacyCallContext(value.lastCallContext) : null,
};
};
@@ -315,13 +283,11 @@ const persistCtiState = () => {
agentLoginId: currentAgentLoginId,
agentStatus,
activeCall,
closingCall,
lastCallContext,
lastCallHistId,
hangupRequested,
callClosedReceived,
updatedAt: Date.now(),
pendingCallCloses,
completedSessionIds,
latestCall,
} satisfies PersistedCtiState);
@@ -341,21 +307,13 @@ const restoreCtiState = (agentLoginId: string) => {
agentStatus = persistedState.agentStatus;
activeCall = persistedState.activeCall;
closingCall = persistedState.closingCall;
lastCallContext = persistedState.lastCallContext;
lastCallHistId = persistedState.lastCallHistId;
// 이전 연결에서 보낸 종료 명령은 새 연결에서 재시도할 수 있다.
hangupRequested = false;
callClosedReceived = false;
pendingCallCloses = persistedState.pendingCallCloses ?? [];
completedSessionIds = persistedState.completedSessionIds ?? [];
const storedLatest = persistedState.latestCall;
latestCall = activeCall ??
(storedLatest
? [closingCall, ...pendingCallCloses.map((pending) => pending.call)].find(
(call) => call?.agentSessionId === storedLatest.agentSessionId,
) ?? storedLatest
: closingCall ?? pendingCallCloses.at(-1)?.call ?? null);
latestCall = activeCall ?? persistedState.latestCall ?? null;
// 거는 중 새로고침은 dialing을 유지해 재발신을 막고, 타임아웃이 지난 dialing만 정리한다.
const isDialingExpired =
activeCall !== null && activeCall.agentSessionId == null && getDialingRemainingMs(activeCall) === 0;
@@ -369,12 +327,9 @@ const restoreCtiState = (agentLoginId: string) => {
return true;
};
// 이력 복구·종료 재처리 요청은 실패를 CTI 쪽에서 직접 처리하므로 공통 오류 팝업을 띄우지 않는다.
// 통화 이력 저장 실패는 화면 동작을 막지 않도록 공통 오류 팝업 없이 콘솔에만 남긴다.
const silentErrorOptions = { skipResponseErrorHandler: true } as const;
const fetchCallHistBySession = (agentSessionId: string) =>
nextApi.get<ListCallHist>(`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`, silentErrorOptions);
const matchesHistory = (call: CtiCall, result: ListCallHist) =>
result.agentSessionId === call.agentSessionId &&
result.prjctIdx === call.context.prjctIdx && result.sid === call.context.sid &&
@@ -388,16 +343,27 @@ const updateCallHistoryId = (call: CtiCall, result: ListCallHist) => {
notify();
};
// 404는 권한 부족이나 저장 지연일 수도 있어 통화 정보를 삭제하지 않는다.
const recoverLastCallHistId = async (call: CtiCall) => {
if (!call.agentSessionId) return;
const describeHistoryError = (error: unknown) => {
if (!(error instanceof HttpError)) return { message: error instanceof Error ? error.message : String(error) };
const data: unknown = error.data;
const code = typeof data === "object" && data !== null && "code" in data ? data.code : undefined;
return { status: error.status, code };
};
// 통화 시작·종료 이력은 이벤트마다 한 번만 저장한다. 실패해도 재시도하지 않는다.
const saveCallHistory = (call: CtiCall, action: "call-start" | "call-close", body: ListCallCloseRequest) => {
const { prjctIdx, sid } = call.context;
const generation = ownerGeneration;
try {
const result = await fetchCallHistBySession(call.agentSessionId);
if (ownerGeneration === generation) updateCallHistoryId(call, result);
} catch {
console.warn("[CTI] 통화 이력 조회 실패: 통화 상태를 유지합니다.");
}
void nextApi.put<ListCallHist>(
`/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/${action}`, body, silentErrorOptions,
).then((result) => {
if (ownerGeneration !== generation) return;
if (!matchesHistory(call, result)) throw new Error("저장 응답이 통화 정보와 일치하지 않습니다.");
updateCallHistoryId(call, result);
}).catch((error: unknown) => {
if (ownerGeneration !== generation) return;
console.warn(`[CTI] ${action} 이력 저장 실패`, { agentSessionId: body.agentSessionId, ...describeHistoryError(error) });
});
};
const setConnectionState = (next: CtiConnectionState) => {
@@ -443,134 +409,6 @@ const rememberCompletedSession = (id: string) => {
completedSessionIds = [...completedSessionIds.filter((item) => item !== id), id].slice(-50);
};
const scheduleHistoryRetry = () => {
if (historyRetryTimeoutId !== null || !currentAgentLoginId) return;
historyRetryTimeoutId = setTimeout(() => {
historyRetryTimeoutId = null;
if (loginCompleted) flushPendingCallCloses();
}, CTI_HISTORY_RETRY_MS);
};
const finishPendingClose = (pending: PendingCallClose) => {
if (pending.call.agentSessionId) rememberCompletedSession(pending.call.agentSessionId);
pendingCallCloses = pendingCallCloses.filter((item) => item !== pending);
persistCtiState();
notify();
};
// 실패한 종료 저장은 세션별로 보존하고 새 통화 상태와 독립적으로 재처리한다.
const savePendingClose = async (pending: PendingCallClose) => {
if (closingRequests.has(pending)) return;
const agentSessionId = pending.call.agentSessionId;
if (!agentSessionId) return;
const generation = ownerGeneration;
const isCurrent = () => ownerGeneration === generation && pendingCallCloses.includes(pending);
closingRequests.add(pending);
try {
await startingRequests.get(pending.call);
if (!isCurrent()) return;
if (pending.body === null) {
// 시작 저장도 실패했었다면 보존한 요청을 먼저 복구한다. GET 404만으로 새 이력을 만들지는 않는다.
if (pending.call.pendingStart) {
const { prjctIdx, sid } = pending.call.context;
const restored = await nextApi.put<ListCallHist>(
`/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/call-start`, pending.call.pendingStart,
silentErrorOptions);
if (!isCurrent()) return;
if (!matchesHistory(pending.call, restored)) throw new Error("통화 시작 복구 응답 불일치");
delete pending.call.pendingStart;
updateCallHistoryId(pending.call, restored);
persistCtiState();
}
const result = await fetchCallHistBySession(agentSessionId);
if (!isCurrent()) return;
if (!matchesHistory(pending.call, result)) throw new Error("통화 이력 불일치");
updateCallHistoryId(pending.call, result);
// 조회 중 Talking/CallClosed가 도착했다면 이전 판단을 사용하지 않는다.
if (pending.body === null && activeCall?.agentSessionId !== agentSessionId) {
if (result.callStatus !== 4 && result.callStatus !== 9) {
const updated = await nextApi.patch<boolean>(
`/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`, undefined, silentErrorOptions);
if (!isCurrent()) return;
if (!updated && pending.body === null) {
const checked = await fetchCallHistBySession(agentSessionId);
if (!isCurrent()) return;
if (!matchesHistory(pending.call, checked) || (checked.callStatus !== 4 && checked.callStatus !== 9)) {
throw new Error("종료 이력 보정 미완료");
}
}
}
if (pending.body === null) {
finishPendingClose(pending);
return;
}
}
}
const body = pending.body;
if (!body || !isCurrent()) return;
// 응답만 유실된 재시도는 중복 PUT에 의한 endDt 변경을 줄인다.
if (pending.attempted) {
try {
const result = await fetchCallHistBySession(agentSessionId);
if (!isCurrent()) return;
if (matchesHistory(pending.call, result) && result.callStatus === 4 &&
result.totalTime === body.totalTime && result.talkTime === body.talkTime &&
result.recordFileName === body.recordFileName) {
updateCallHistoryId(pending.call, result);
finishPendingClose(pending);
return;
}
} catch (error) {
if (!(error instanceof HttpError && error.status === 404)) throw error;
}
}
if (!isCurrent()) return;
pending.attempted = true;
persistCtiState();
const { prjctIdx, sid } = pending.call.context;
const result = await nextApi.put<ListCallHist>(
`/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/call-close`, body, silentErrorOptions);
if (!isCurrent()) return;
if (!matchesHistory(pending.call, result)) throw new Error("종료 저장 응답 불일치");
updateCallHistoryId(pending.call, result);
finishPendingClose(pending);
} catch (error) {
// 404는 이력 없음·권한 없음처럼 재시도해도 바뀌지 않으므로 무한 재시도하지 않고 정리한다.
if (isCurrent() && error instanceof HttpError && error.status === 404) {
console.warn("[CTI] 종료 이력 저장 불가(404): 재시도 정보를 정리합니다.");
finishPendingClose(pending);
return;
}
if (isCurrent()) {
console.warn("[CTI] 종료 이력 저장 실패: 재시도할 정보를 보존합니다.");
if (!notifiedCloseFailures.has(pending)) {
notifiedCloseFailures.add(pending);
alertUnhandledError("CallHistory", "종료 이력 저장을 재시도합니다.");
}
scheduleHistoryRetry();
}
} finally {
closingRequests.delete(pending);
}
};
const flushPendingCallCloses = () => {
pendingCallCloses.forEach((pending) => void savePendingClose(pending));
};
const queueCallClose = (call: CtiCall, body: ListCallCloseRequest | null) => {
let pending = pendingCallCloses.find((item) => item.call.agentSessionId === call.agentSessionId);
if (pending) {
// 실제 종료 이벤트는 재로그인 11에 의한 판단보다 우선한다.
if (body) pending.body = body;
} else {
pending = { call, body };
pendingCallCloses.push(pending);
}
persistCtiState();
void savePendingClose(pending);
};
const buildCallBody = (parsed: Record<string, unknown>, call: CtiCall): ListCallCloseRequest | null => {
const text = (key: string) => typeof parsed[key] === "string" ? parsed[key] : "";
const body: ListCallCloseRequest = {
@@ -586,37 +424,21 @@ const buildCallBody = (parsed: Record<string, unknown>, call: CtiCall): ListCall
};
const saveCallStart = (parsed: Record<string, unknown>, call: CtiCall) => {
if (savedStarts.has(call) || startingRequests.has(call)) return;
if (startRequestedCalls.has(call)) return;
const body = buildCallBody(parsed, call);
if (!body) {
alertUnhandledError("StartSessionRecord", "통화 시작 정보가 올바르지 않습니다.");
return;
}
const { prjctIdx, sid } = call.context;
const generation = ownerGeneration;
call.pendingStart = body;
persistCtiState();
const request = nextApi.put<ListCallHist>(
`/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/call-start`, body,
).then((result) => {
if (ownerGeneration !== generation) return;
if (!matchesHistory(call, result)) throw new Error("통화 시작 저장 응답 불일치");
savedStarts.add(call);
delete call.pendingStart;
updateCallHistoryId(call, result);
persistCtiState();
}).catch(() => {
if (ownerGeneration === generation) alertUnhandledError("CallHistory", "통화 시작 이력을 저장하지 못했습니다.");
}).finally(() => { startingRequests.delete(call); });
startingRequests.set(call, request);
startRequestedCalls.add(call);
saveCallHistory(call, "call-start", body);
};
// 재로그인 11로 화면 상태만 해제된 통화도 이후 CallClosed로 마감할 수 있도록 마지막 통화를 함께 찾는다.
const findEventCall = (agentSessionId: string): CtiCall | null => {
if (!agentSessionId || completedSessionIds.includes(agentSessionId)) return null;
if (activeCall?.agentSessionId === agentSessionId) return activeCall;
if (closingCall?.agentSessionId === agentSessionId) return closingCall;
const pending = pendingCallCloses.find((item) => item.call.agentSessionId === agentSessionId);
if (pending) return pending.call;
if (latestCall?.agentSessionId === agentSessionId) return latestCall;
return activeCall?.agentSessionId === null ? activeCall : null;
};
@@ -674,19 +496,13 @@ const handleIncomingMessage = (raw: unknown) => {
setAgentStatus(status);
const call = recoveryCall;
recoveryCall = null;
if (status === "11" && call?.agentSessionId &&
(activeCall === call || closingCall === call)) {
// 통화가 유지됐다면 Talking이 재전송된다. 11은 단절 중 종료된 복원 대상에만 적용한다.
if (activeCall === call) activeCall = null;
if (closingCall === call) closingCall = null;
if (status === "11" && call?.agentSessionId && activeCall === call) {
// 통화가 유지됐다면 Talking이 재전송된다. 11이면 화면의 통화 상태만 해제하고 이력은 CallClosed로만 마감한다.
activeCall = null;
clearDialingTimeout();
queueCallClose(call, null);
} else if (call?.agentSessionId) {
void recoverLastCallHistId(call);
}
persistCtiState();
setConnectionState("open");
flushPendingCallCloses();
return;
}
if (!loginCompleted) return;
@@ -719,18 +535,13 @@ const handleIncomingMessage = (raw: unknown) => {
alertUnhandledError("Talking", "통화 대상 정보를 복원할 수 없습니다.");
break;
}
// 종료 데이터가 이미 있으면 지연된 Talking으로 통화를 재개하지 않는다.
const pending = pendingCallCloses.find((item) => item.call === call);
if (pending?.body) break;
// 종료된 세션은 findEventCall에서 제외되므로 지연된 Talking으로 통화를 재개하지 않는다.
if (activeCall && activeCall !== call) break;
pendingCallCloses = pendingCallCloses.filter((item) => item !== pending);
activeCall = call;
if (closingCall === call) closingCall = null;
latestCall = call;
clearDialingTimeout();
callClosedReceived = false;
setAgentStatus("3");
void recoverLastCallHistId(call);
break;
}
case "CallClosed": {
@@ -748,9 +559,10 @@ const handleIncomingMessage = (raw: unknown) => {
callClosedReceived = true;
agentStatus = "4";
}
if (closingCall === call) closingCall = null;
queueCallClose(call, body);
rememberCompletedSession(body.agentSessionId);
persistCtiState();
notify();
saveCallHistory(call, "call-close", body);
break;
}
case "HangUp":
@@ -796,20 +608,13 @@ const logout = () => {
teardownSocket();
clearAutoReconnect();
clearDialingTimeout();
if (historyRetryTimeoutId !== null) clearTimeout(historyRetryTimeoutId);
historyRetryTimeoutId = null;
currentAgentLoginId = null;
currentConnectionKey = null;
currentLoginParams = null;
activeCall = null;
closingCall = null;
recoveryCall = null;
latestCall = null;
pendingCallCloses = [];
completedSessionIds = [];
startingRequests.clear();
savedStarts = new WeakSet<CtiCall>();
closingRequests.clear();
lastCallContext = null;
lastCallHistId = null;
callClosedReceived = false;
@@ -864,7 +669,7 @@ const connectAndLogin = (params: CtiLoginParams) => {
currentConnectionKey = key;
currentLoginParams = params;
if (shouldRestore) restoreCtiState(params.agentLoginId);
recoveryCall = activeCall ?? closingCall;
recoveryCall = activeCall;
openSocketAndLogin(params);
};

View File

@@ -308,8 +308,6 @@ export type ListCallHist = ListCallCloseRequest & {
regDt: string;
};
export type ListCallHistSession = ListCallHist;
export type ListReserveRequest = {
prjctIdx: number;
sid: string;