openreplay/frontend/app/player/web/MessageManager.ts
Delirium 2ed4bba33e
feat(tracker/ui): support for multi tab sessions (#1236)
* feat(tracker): add support for multi tab sessions

* feat(backend): added support of multitabs

* fix(backend): added support of deprecated batch meta message to pre-decoder

* fix(backend): fixed nil meta issue for TabData messages in sink

* feat(player): add tabmanager

* feat(player): basic tabchange event support

* feat(player): pick tabstate for console panel and timeline

* fix(player): only display tabs that are created

* feat(player): connect performance, xray and events to tab state

* feat(player): merge all tabs data for overview

* feat(backend/tracker): extract tabdata into separate message from batchmeta

* fix(tracker): fix new session check

* fix(backend): remove batchmetadeprecated

* fix(backend): fix switch case

* fix(player): fix for tab message size

* feat(tracker): check for active tabs with broadcast channel

* feat(tracker): prevent multiple messages

* fix(tracker): ignore beacons from same tab, only ask if token isnt present yet, add small delay before start to wait for answer

* feat(player): support new msg struct in assist player

* fix(player): fix some livepl components for multi tab states

* feat(tracker): add option to disable multitab

* feat(tracker): add multitab to assist plugin

* feat(player): back compat for tab id

* fix(ui): fix missing list in controls

* fix(ui): optional list update

* feat(ui): fix visuals for multitab; use window focus event for tabs

* fix(tracker): fix for dying tests (added tabid to writer, refactored other tests)

* feat(ui): update LivePlayerSubHeader.tsx to support tabs

* feat(backend): added tabs support to devtools mob files

* feat(ui): connect state to current tab properly

* feat(backend): added multitab support to assits

* feat(backend): removed data check in agent message

* feat(backend): debug on

* fix(backend): fixed typo in message broadcast

* feat(backend): fixed issue in connect method

* fix(assist): fixed typo

* feat(assist): added more debug logs

* feat(assist): removed one log

* feat(assist): more logs

* feat(assist): use query.peerId

* feat(assist): more logs

* feat(assist): fixed session update

* fix(assist): fixed getSessions

* fix(assist): fixed request_control broadcast

* fix(assist): fixed typo

* fix(assist): added missed line

* fix(assist): fix typo

* feat(tracker): multitab support for assist sessions

* fix(tracker): fix dead tests (tabid prop)

* fix(tracker): fix yaml

* fix(tracker): timers issue

* fix(ui): fix ui E2E tests with magic?

* feat(assist): multitabs support for ee version

* fix(assist): added missed method import

* fix(tracker): fix fix events in assist

* feat(assist): added back compatibility for sessions without tabId

* fix(assist): apply message's top layer structure before broadcast call

* fix(assist): added random tabID for prev version

* fix(assist): added random tabID for prev version (ee)

* feat(assist): added debug logs

* fix(assist): fix typo in sessions_agents_count method

* fix(assist): fixed more typos in copy-pastes

* fix(tracker): fix restart timings

* feat(backend): added tabIDs for some events

* feat(ui): add tab change event to the user steps bar

* Revert "feat(backend): added tabIDs for some events"

This reverts commit 1467ad7f9f.

* feat(ui): revert timeline and xray to grab events from all tabs

* fix(ui): fix typo

---------

Co-authored-by: Alexander Zavorotynskiy <zavorotynskiy@pm.me>
2023-06-07 10:40:32 +02:00

324 lines
9.8 KiB
TypeScript

// @ts-ignore
import { Decoder } from 'syncod';
import logger from 'App/logger';
import type { Store, ILog } from 'Player';
import ListWalker from '../common/ListWalker';
import MouseMoveManager from './managers/MouseMoveManager';
import ActivityManager from './managers/ActivityManager';
import { MouseThrashing, MType } from './messages';
import type { Message, MouseClick } from './messages';
import Screen, {
INITIAL_STATE as SCREEN_INITIAL_STATE,
State as ScreenState,
} from './Screen/Screen';
import type { InitialLists } from './Lists';
import type { SkipInterval } from './managers/ActivityManager';
import TabSessionManager, { TabState } from 'Player/web/TabManager';
import ActiveTabManager from 'Player/web/managers/ActiveTabManager';
interface RawList {
event: Record<string, any>[] & { tabId: string | null };
frustrations: Record<string, any>[] & { tabId: string | null };
stack: Record<string, any>[] & { tabId: string | null };
exceptions: ILog[];
}
export interface State extends ScreenState {
skipIntervals: SkipInterval[];
connType?: string;
connBandwidth?: number;
location?: string;
tabStates: {
[tabId: string]: TabState;
};
domContentLoadedTime?: { time: number; value: number };
domBuildingTime?: number;
loadTime?: { time: number; value: number };
error: boolean;
messagesLoading: boolean;
ready: boolean;
lastMessageTime: number;
firstVisualEvent: number;
messagesProcessed: boolean;
currentTab: string;
tabs: string[];
tabChangeEvents: { tabId: string; timestamp: number; tabName: string }[];
}
export const visualChanges = [
MType.MouseMove,
MType.MouseClick,
MType.CreateElementNode,
MType.SetInputValue,
MType.SetInputChecked,
MType.SetViewportSize,
MType.SetViewportScroll,
];
export default class MessageManager {
static INITIAL_STATE: State = {
...SCREEN_INITIAL_STATE,
tabStates: {},
skipIntervals: [],
error: false,
ready: false,
lastMessageTime: 0,
firstVisualEvent: 0,
messagesProcessed: false,
messagesLoading: false,
currentTab: '',
tabs: [],
tabChangeEvents: [],
};
private clickManager: ListWalker<MouseClick> = new ListWalker();
private mouseThrashingManager: ListWalker<MouseThrashing> = new ListWalker();
private activityManager: ActivityManager | null = null;
private mouseMoveManager: MouseMoveManager;
private activeTabManager = new ActiveTabManager();
public readonly decoder = new Decoder();
private readonly sessionStart: number;
private lastMessageTime: number = 0;
private firstVisualEventSet = false;
public readonly tabs: Record<string, TabSessionManager> = {};
private tabChangeEvents: Record<string, number>[] = [];
private activeTab = '';
constructor(
private readonly session: Record<string, any>,
private readonly state: Store<State & { time: number }>,
private readonly screen: Screen,
private readonly initialLists?: Partial<InitialLists>,
private readonly uiErrorHandler?: { error: (error: string) => void }
) {
this.mouseMoveManager = new MouseMoveManager(screen);
this.sessionStart = this.session.startedAt;
this.activityManager = new ActivityManager(this.session.duration.milliseconds); // only if not-live
}
public getListsFullState = () => {
const fullState: Record<string, any> = {};
for (let tab in Object.keys(this.tabs)) {
fullState[tab] = this.tabs[tab].getListsFullState();
}
return Object.values(this.tabs)[0].getListsFullState();
};
public updateLists(lists: RawList) {
Object.keys(this.tabs).forEach((tab) => {
this.tabs[tab]!.updateLists(lists);
// once upon a time we wanted to insert events for each tab individually
// but then evil magician came and said "no, you don't want to do that"
// because it was bad for database size
// const list = {
// event: lists.event.filter((e) => e.tabId === tab),
// frustrations: lists.frustrations.filter((e) => e.tabId === tab),
// stack: lists.stack.filter((e) => e.tabId === tab),
// exceptions: lists.exceptions.filter((e) => e.tabId === tab),
// };
// // saving some microseconds here probably
// if (Object.values(list).some((l) => l.length > 0)) {
// this.tabs[tab]!.updateLists(list);
// }
})
}
public _sortMessagesHack = (msgs: Message[]) => {
Object.values(this.tabs).forEach((tab) => tab._sortMessagesHack(msgs));
};
private waitingForFiles: boolean = false;
public onFileReadSuccess = () => {
if (this.activityManager) {
this.activityManager.end();
this.state.update({ skipIntervals: this.activityManager.list });
}
Object.values(this.tabs).forEach((tab) => tab.onFileReadSuccess?.());
};
public onFileReadFailed = (e: any) => {
logger.error(e);
this.state.update({ error: true });
this.uiErrorHandler?.error('Error requesting a session file');
};
public onFileReadFinally = () => {
this.waitingForFiles = false;
this.state.update({ messagesProcessed: true });
};
public startLoading = () => {
this.waitingForFiles = true;
this.state.update({ messagesProcessed: false });
this.setMessagesLoading(true);
};
resetMessageManagers() {
this.clickManager = new ListWalker();
this.mouseMoveManager = new MouseMoveManager(this.screen);
this.activityManager = new ActivityManager(this.session.duration.milliseconds);
this.activeTabManager = new ActiveTabManager();
Object.values(this.tabs).forEach((tab) => tab.resetMessageManagers());
}
move(t: number): any {
// usually means waiting for messages from live session
if (Object.keys(this.tabs).length === 0) return;
this.activeTabManager.moveReady(t).then((tabId) => {
// Moving mouse and setting :hover classes on ready view
this.mouseMoveManager.move(t);
const lastClick = this.clickManager.moveGetLast(t);
if (!!lastClick && t - lastClick.time < 600) {
// happened during last 600ms
this.screen.cursor.click();
}
const lastThrashing = this.mouseThrashingManager.moveGetLast(t);
if (!!lastThrashing && t - lastThrashing.time < 300) {
this.screen.cursor.shake();
}
const activeTabs = this.state.get().tabs;
if (tabId && !activeTabs.includes(tabId)) {
this.state.update({ tabs: activeTabs.concat(tabId) });
}
if (tabId && this.activeTab !== tabId) {
this.state.update({ currentTab: tabId });
this.activeTab = tabId;
}
if (this.tabs[this.activeTab]) {
this.tabs[this.activeTab].move(t);
} else {
console.error(
'missing tab state',
this.tabs,
this.activeTab,
tabId,
this.activeTabManager.list
);
}
});
if (
this.waitingForFiles &&
this.lastMessageTime <= t &&
t !== this.session.duration.milliseconds
) {
this.setMessagesLoading(true);
}
}
public changeTab(tabId: string) {
this.activeTab = tabId;
this.state.update({ currentTab: tabId });
this.tabs[tabId].move(this.state.get().time);
}
public updateChangeEvents() {
this.state.update({ tabChangeEvents: this.tabChangeEvents });
}
distributeMessage = (msg: Message & { tabId: string }): void => {
if (!this.tabs[msg.tabId]) {
this.tabs[msg.tabId] = new TabSessionManager(
this.session,
this.state,
this.screen,
msg.tabId,
this.setSize,
this.sessionStart,
this.initialLists
);
}
const lastMessageTime = Math.max(msg.time, this.lastMessageTime);
this.lastMessageTime = lastMessageTime;
this.state.update({ lastMessageTime });
if (visualChanges.includes(msg.tp)) {
this.activityManager?.updateAcctivity(msg.time);
}
switch (msg.tp) {
case MType.TabChange:
const prevChange = this.activeTabManager.last;
if (!prevChange || prevChange.tabId !== msg.tabId) {
this.tabChangeEvents.push({
tabId: msg.tabId,
timestamp: this.sessionStart + msg.time,
toTab: mapTabs(this.tabs)[msg.tabId],
fromTab: prevChange?.tabId ? mapTabs(this.tabs)[prevChange.tabId] : '',
type: 'TABCHANGE',
});
this.activeTabManager.append(msg);
}
break;
case MType.MouseThrashing:
this.mouseThrashingManager.append(msg);
break;
case MType.MouseMove:
this.mouseMoveManager.append(msg);
break;
case MType.MouseClick:
this.clickManager.append(msg);
break;
default:
switch (msg.tp) {
case MType.CreateDocument:
if (!this.firstVisualEventSet) {
this.activeTabManager.append({ tp: MType.TabChange, tabId: msg.tabId, time: 0 });
this.state.update({
firstVisualEvent: msg.time,
currentTab: msg.tabId,
tabs: [msg.tabId],
});
this.firstVisualEventSet = true;
}
}
this.tabs[msg.tabId].distributeMessage(msg);
break;
}
};
setMessagesLoading = (messagesLoading: boolean) => {
if (!messagesLoading) {
this.updateChangeEvents();
}
this.screen.display(!messagesLoading);
this.state.update({ messagesLoading, ready: !messagesLoading && !this.state.get().cssLoading });
};
decodeMessage(msg: Message) {
return this.tabs[this.activeTab].decodeMessage(msg);
}
private setSize({ height, width }: { height: number; width: number }) {
this.screen.scale({ height, width });
this.state.update({ width, height });
}
// TODO: clean managers?
clean() {
this.state.update(MessageManager.INITIAL_STATE);
}
}
function mapTabs(tabs: Record<string, TabState>) {
const tabIds = Object.keys(tabs);
const tabMap = {};
tabIds.forEach((tabId) => {
tabMap[tabId] = `Tab ${tabIds.indexOf(tabId)+1}`;
});
return tabMap;
}