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