Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(@yourssu/logging-system): unload event 시 서버로 log 전송 #66

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

owl1753
Copy link
Collaborator

@owl1753 owl1753 commented Oct 16, 2024

1️⃣ 어떤 작업을 했나요? (Summary)

기존 코드에 영향을 미치지 않는 변경사항

  • 없습니다.

기존 코드에 영향을 미치는 변경사항

  • YLSProvider에 visibilitychange 이벤트를 추가하는 코드를 작성했습니다.

버그 픽스

  • 서버로 로그가 잘 전송됩니다.

2️⃣ 알아두시면 좋아요!

  • unload => visibilitychange로 변경하여 bfcache issue와 신뢰성 문제를 해결합니다. (참고)
  • keepalive를 이용하여 브라우저가 종료 되어도 요청을 유지합니다.
  • 응답은 고려하지 않습니다.
  • 브라우저 생명 주기 상 새로고침 시에도 로그가 전송됩니다.

3️⃣ 추후 작업

  • 추후 Pending Beacon API가 정식적으로 지원된다면 이것으로 변경하는 게 좋을 듯 합니다. Pending Beacon API

4️⃣ 체크리스트 (Checklist)

  • main 브랜치의 최신 코드를 pull 받았나요?

});
};

document.addEventListener('visibilitychange', handleVisibilityChange, { once: true });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useEffect 내부에 적용해서 cleanup 있을 때 함께 정리할 수 있도록 하면 더 좋을 것 같아요.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refactor: cleanup 함수 추가 cleanup 함수를 추가하라는 말씀이신가요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refactor: cleanup 함수 추가
현재 코드에서 이 변경 사항 차이점이 있는 건가요?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Hanna922

refactor: cleanup 함수 추가 현재 코드에서 이 변경 사항 차이점이 있는 건가요?

YLSProvider보다 상위 Provider나 App 컴포넌트 내에서 리렌더링이 일어나면, 이벤트 리스너가 다시 등록 되면서, 메모리 누수의 가능성이 있을 것 같아요.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

once: true 속성이 이벤트 리스너를 자동으로 제거하는 것으로 알고 있는데 제거 전에 리렌더링이 발생할 수 있다는 말씀이실까요??
remove 기능만 하는 거라면 변경 전과 동일한 것으로 알고 있어서 여쭤봅니당

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Provider 컴포넌트는 여전히 이벤트 리스너 호출 후 once: true로 지워지는 것보다 먼저 리렌더링 될 수 있어서 클린업을 해야 하지 않을까 싶어요


SetLocalStorageClear();

await axiosInstance.put('/log/list', data, {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

브라우저 이탈상황에서 await문은 아래의 이벤트 리스너 호출 부분을 블로킹하게 될 것 같아요.

호출 순서를 변경해야 할 것 같아요.
async await으로 처리할 필요가 있을까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refactor: async/await 제거 await 쓰면 blocking 되는 줄 몰랐네요...

};

document.addEventListener('visibilitychange', handleVisibilityChange, { once: true });
});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Provider가 최상위에서 정의될텐데, 의존성 배열이 없으면 기대하지 않은 렌더링 상황에서 매번 호출될 것 같아요. (이벤트 리스너가 계속 등록되고 삭제될 듯합니다)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix: useEffect에 의존성 배열 추가에서 수정했습니다.

Copy link

@minai621 minai621 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

찾아보니까 keep-alive는 tcp 세션을 유지해주는 역할이라고 하는데, 브라우저가 이탈했을 때 전송을 유지하지 않는 것 같아요

@minai621
Copy link

@EATSTEAK
요청을 클라이언트에서 처리하면 브라우저 이탈시 동작을 보장하지 못할 것 같은데, 서비스 워커에서 시도해보는게 어떨까요? 최고 기술자 EATSTEAK의 의견이 궁금합니다.

@owl1753 owl1753 requested a review from minai621 October 16, 2024 08:52
SetLocalStorageClear();

void axiosInstance.put('/log/list', data, {
httpAgent: new http.Agent({ keepAlive: true }),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이전에 이야기했듯이 http.AgentkeepAlive는 TCP keepalive를 위한 프로퍼티네요. fetch 사용해서 재작성이 필요해 보입니다.
다만 Firefox에서는 fetch의 keepalive 옵션이 지원되지 않으므로(131 기준 Experimental) 백엔드와 소통하여 POST 메소드를 하나 만드는 편이 좋아보입니다.

참고 - Node.js http.Agent
참고 - Can I use keepalive?

Comment on lines +39 to +62
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') return;

const logList: LogType[] = JSON.parse(localStorage.getItem('yls-web') as string) || [];
const data: LogRequestList = {
logRequestList: logList,
};

SetLocalStorageClear();

void axiosInstance.put('/log/list', data, {
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
});
};

document.addEventListener('visibilitychange', handleVisibilityChange);

return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useEffect를 사용해서 이벤트를 리스닝하게 되면 재랜더링시마다 이벤트를 재등록하게 되는데, useRef를 이용해서 등록하게 되면 그런 문제가 없을 듯 합니다.

Suggested change
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') return;
const logList: LogType[] = JSON.parse(localStorage.getItem('yls-web') as string) || [];
const data: LogRequestList = {
logRequestList: logList,
};
SetLocalStorageClear();
void axiosInstance.put('/log/list', data, {
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
});
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
const documentRef = useRef(document);
const logRequestListRef = useRef<LogRequestList>({ logRequestList: [] });
function handleVisibilityChange() {
if (documentRef.current.visibilityState === 'visible') return;
const logRequestList: LogType[] = JSON.parse(localStorage.getItem('yls-web') as string) || [];
logRequestListRef.current = {
logRequestList,
};
}
document.current.addEventListener('visibilitychange', handleVisibilityChange);
useEffect(() => {
SetLocalStorageClear();
void axiosInstance.put('/log/list', logRequestListRef.current, {
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
});
}, []);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

bug: 페이지 이탈 시 로그 전송 안되는 현상
4 participants