Commit 6ea0ec1e authored by fanxuehui's avatar fanxuehui

refactor:

parent b30763b3
let flag = false;
export default (...rest) => {
if (!flag) return;
console.log(...rest);
};
export const switchLog = b => {
flag = b;
};
import * as rrweb from "rrweb"; import * as rrweb from "rrweb";
import TracksWorker from "./tracks.worker"; import TracksWorker from "./tracks.worker";
import utils from "./utils";
export default class Monitor { class Monitor {
rrwebHandler = null; rrwebHandler = null;
initialized = false;
listenedRoute = false;
tracksWorker = new TracksWorker(); tracksWorker = new TracksWorker();
constructor({ system = "unknow", userIdentifier = "unknow", env = "prod", log = false }) { init({ system, userIdentifier, env = "prod", log = false }) {
console.log("初始化"); if (!system || !userIdentifier) {
console.error("system,userIdentifier是必传的");
}
if (!this.initialized) {
this.tracksWorker.postMessage({ this.tracksWorker.postMessage({
type: "init", type: "init",
payload: { payload: {
system, system,
userIdentifier, userIdentifier,
config: {
env, env,
log, log,
}
}, },
}); });
this.record();
} else {
this.reset({ userIdentifier });
}
} }
/** /**
* 关闭rrweb * 关闭rrweb
...@@ -42,7 +48,14 @@ export default class Monitor { ...@@ -42,7 +48,14 @@ export default class Monitor {
* 路由监听 * 路由监听
*/ */
listenOnHash() { listenOnHash() {
// console.log(window.onhashchange()); if (this.listenedRoute) return;
let timer = null;
window.addEventListener("hashchange", () => {
clearTimeout(timer);
timer = setTimeout(() => {
this.reset({ path: location.hash });
}, 1000);
});
} }
/** /**
* 停止录制 * 停止录制
...@@ -64,12 +77,6 @@ export default class Monitor { ...@@ -64,12 +77,6 @@ export default class Monitor {
console.log("重置数据"); console.log("重置数据");
this.tracksWorker.postMessage({ type: "reset", payload: event }); this.tracksWorker.postMessage({ type: "reset", payload: event });
} }
/**
* 发送信息
* @param {*} action
* @memberof Monitor
*/
postMessage(action) {
this.tracksWorker.postMessage(action);
}
} }
export default new Monitor();
// 数据维护,上报 // 数据维护,上报
import md5 from "md5";
import Counter from "./counter"; import Counter from "./counter";
import { dataWrapper, log } from './utils'; import { dataWrapper } from "./utils";
import log from "./log";
class Reporter { class Reporter {
// 基础配置 // 基础配置
baseInfo = { baseInfo = {
system: '', system: "",
userIdentifier: '', userIdentifier: "",
path: '', path: "",
}; };
// 系统配置
config = { config = {
env: 'prod', env: "prod",
log: false log: false,
}; };
environmentUrl = ''; // 环境配置 environmentUrl = ""; // 环境配置
isUploading = false; // 是否在上传cdn isUploading = false; // 是否在上传cdn
bus = []; // 上传分片数据 bus = []; // 上传分片数据
counter = new Counter(); // 计数器和recordKey一起重置 counter = new Counter(); // 计数器和recordKey一起重置
cache = [] // cdn数据缓存 cache = []; // cdn数据缓存
constructor(recordKey) { init({ recordKey, env, log, ...baseInfo }) {
this.recordKey = recordKey; this.recordKey = recordKey;
this.baseInfo = baseInfo;
this.setEnvironment(env);
} }
// 设置参数内容 // 设置参数内容
setData(dataObj) { setData(dataObj) {
// 设置配置内容
this.config = dataObj.config || this.config;
this.setEnvironment(this.config.env);
// 设置基础信息 系统名 + 用户标示 + 当前访问路径 // 设置基础信息 系统名 + 用户标示 + 当前访问路径
dataObj.config && delete dataObj.config
this.baseInfo = { this.baseInfo = {
...this.baseInfo, ...this.baseInfo,
...dataObj ...dataObj,
} };
} }
// 设置系统环境变量 // 设置系统环境变量
setEnvironment(env) { setEnvironment(env) {
if (env === 'dev') { if (env === "dev") {
this.environmentUrl = 'http://hunter.duibadev.com.cn'; this.environmentUrl = "http://hunter.duibadev.com.cn";
} else if (env === 'prod') { } else if (env === "prod") {
this.environmentUrl = 'http://hunter.dui88.com.cn'; this.environmentUrl = "http://hunter.dui88.com.cn";
} }
} }
// 上传CDN // 上传CDN
toCDN(payload) { toCDN(payload) {
this.isUploading = true; this.isUploading = true;
const blob = new Blob([JSON.stringify(payload)], {type : 'application/json'}); const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
const formData = new FormData(); const formData = new FormData();
const trackId = this.counter.count; const trackId = this.counter.count;
formData.append('file', blob, `${this.recordKey + trackId}.json`); formData.append("file", blob, `${this.recordKey + trackId}.json`);
try { try {
fetch(`${this.environmentUrl}/upload`, { fetch(`${this.environmentUrl}/upload`, {
// fetch(`http://172.16.47.148:3000/upload`, { // fetch(`http://172.16.47.148:3000/upload`, {
method: 'POST', method: "POST",
credentials: 'include', credentials: "include",
body: formData body: formData,
}).then(res => { })
.then(res => {
return res.json(); return res.json();
}).then(res => { })
.then(res => {
// 如果cache中有数据,说明是多次提交并且数据缓存在了cache中,那么我们全量快照可能在cache[0] // 如果cache中有数据,说明是多次提交并且数据缓存在了cache中,那么我们全量快照可能在cache[0]
const snapArr = this.cache && this.cache.length > 0 ? this.cache : this.bus; const snapArr = this.cache && this.cache.length > 0 ? this.cache : this.bus;
const snapIndex = snapArr.findIndex((item, index) => { const snapIndex = snapArr.findIndex((item, index) => {
...@@ -72,19 +72,19 @@ class Reporter { ...@@ -72,19 +72,19 @@ class Reporter {
path: this.path, path: this.path,
recordKey: this.recordKey, recordKey: this.recordKey,
trackId: trackId, trackId: trackId,
isCDN: true isCDN: true,
} };
log(this.config.log, 'type=2定位', snapIndex); log("type=2定位", snapIndex);
log(this.config.log, 'cnd Url', res.data.url); log("cnd Url", res.data.url);
// 向cache或者bus中注入 // 向cache或者bus中注入
if(this.cache && this.cache.length > 0) { if (this.cache && this.cache.length > 0) {
this.cache[0].splice(snapIndex, 1, dataWrapper(extra, res.data.url)); this.cache[0].splice(snapIndex, 1, dataWrapper(extra, res.data.url));
} else { } else {
this.bus.splice(snapIndex, 1, dataWrapper(extra, res.data.url)); this.bus.splice(snapIndex, 1, dataWrapper(extra, res.data.url));
} }
this.isUploading = false; this.isUploading = false;
// 如果cache里面有数据需要上传的,那么先上传 // 如果cache里面有数据需要上传的,那么先上传
if(this.cache && this.cache.length > 0) { if (this.cache && this.cache.length > 0) {
this.cache.map(item => { this.cache.map(item => {
this.report(item); this.report(item);
}); });
...@@ -93,7 +93,7 @@ class Reporter { ...@@ -93,7 +93,7 @@ class Reporter {
return res; return res;
}); });
} catch (e) { } catch (e) {
log(this.config.log, '上传失败,原因:', e.message); log("上传失败,原因:", e.message);
} }
} }
toBus(data) { toBus(data) {
...@@ -103,40 +103,44 @@ class Reporter { ...@@ -103,40 +103,44 @@ class Reporter {
path: this.path, path: this.path,
recordKey: this.recordKey, recordKey: this.recordKey,
trackId: this.counter.next(), trackId: this.counter.next(),
isCDN: false isCDN: false,
} };
this.bus.push(dataWrapper(extra, data)); this.bus.push(dataWrapper(extra, data));
} }
// 上传 // 上传
report(data) { report(data) {
log(this.config.log, '上传数据', data); log("上传数据", data);
const reportData = data; const reportData = data;
this.bus = []; this.bus = [];
if (this.isUploading) { if (this.isUploading) {
log(this.config.log, 'cdn数据正在上传,先将内容存到cache', this.cache); log("cdn数据正在上传,先将内容存到cache", this.cache);
this.cache.push(reportData); this.cache.push(reportData);
return; return;
} }
try { try {
fetch(`${this.environmentUrl}/behavior/record`, { fetch(`${this.environmentUrl}/behavior/record`, {
// fetch(`http://172.16.47.148:3000/behavior/record`, { // fetch(`http://172.16.47.148:3000/behavior/record`, {
method: 'POST', method: "POST",
credentials: 'include', credentials: "include",
'Content-Type': 'application/json;charset=utf-8', "Content-Type": "application/json;charset=utf-8",
body: JSON.stringify({tracks: data}) body: JSON.stringify({ tracks: data }),
}).then(res => { }).then(res => {
log(this.config.log, '上传返回的内容', res); log("上传返回的内容", res);
}); });
} catch (e) { } catch (e) {
log(this.config.log, '上传失败,原因:', e.message); log("上传失败,原因:", e.message);
} }
} }
generateKey() {
const { path, userIdentifier } = this;
this.recordKey = md5(path + userIdentifier + Date.parse(new Date()));
}
// 重置数据(分条使用) // 重置数据(分条使用)
reset(recordKey) { reset() {
this.cache = []; this.cache = [];
this.bus = []; this.bus = [];
this.counter.reset(); this.counter.reset();
this.recordKey = recordKey; this.generateKey();
} }
} }
......
// 入口,格式化数据,模块管理 // 入口,格式化数据,模块管理
import md5 from "md5";
import Reporter from "./reporter"; import Reporter from "./reporter";
import { log } from './utils'; import log, { switchLog } from "./log";
const reporter = new Reporter("recordKey"); let reporter = new Reporter();
onmessage = ({ data: { type, payload } }) => { onmessage = ({ data: { type, payload } }) => {
switch (type) { switch (type) {
case "init": case "init":
reporter.setData(payload); switchLog(payload.log);
log(reporter.config.log, 'init参数', payload); reporter.init(payload);
log("init参数", payload);
break; break;
case "record": case "record":
// todo : 数据本地存储 // todo : 数据本地存储
reporter.toBus(payload); reporter.toBus(payload);
log(reporter.config.log, 'bus', reporter.bus); log("bus", reporter.bus);
// todo : 全量快照上传cdn // todo : 全量快照上传cdn
log(reporter.config.log, 'track type', payload.type); log("track type", payload.type);
if (payload.type === 2) { if (payload.type === 2) {
reporter.toCDN(payload); reporter.toCDN(payload);
} }
...@@ -31,14 +31,12 @@ onmessage = ({ data: { type, payload } }) => { ...@@ -31,14 +31,12 @@ onmessage = ({ data: { type, payload } }) => {
break; break;
case "reset": case "reset":
// todo : 重置参数,重新生成recordKey // todo : 重置参数,重新生成recordKey
const { path, email } = payload; reporter.setData(payload);
reporter.setData({path}); reporter.reset();
let recordKey = md5(path + email + Date.parse(new Date())); log("path", reporter.baseInfo.path);
reporter.reset(recordKey); log("分片id", reporter.recordKey);
log(reporter.config.log, 'path', reporter.baseInfo.path);
log(reporter.config.log, '分片id', reporter.recordKey);
break; break;
default: default:
log(reporter.config.log, 'unknow action', type); log("unknow action", type);
} }
}; };
...@@ -9,11 +9,3 @@ export const dataWrapper = (extraData, event) => { ...@@ -9,11 +9,3 @@ export const dataWrapper = (extraData, event) => {
track: event, track: event,
}; };
}; };
/**
* 是否打印日志
* @param {boolean} log
*/
export const log = (log, ...rest) => {
console.log(rest);
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment