sendStrategy.ts
2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import storage from './loggerAndStorage'
class AsyncSendStrategy {
private callback: (() => void) | null = null
private sendTime: number = 1000 * 5
private sendNum: number = 10
private dataHasSend: boolean = true
private dataHasChange: boolean = false
private syncStorage: boolean = false
private failTime: number = 0
private is_first_batch_write: boolean = true
start(): void {
this.batchInterval()
}
private batchInterval(): void {
const _this = this
function loopWrite(): void {
setTimeout(() => {
_this.batchWrite()
loopWrite()
}, 500)
}
function loopSend(): void {
setTimeout(() => {
_this.batchSend()
loopSend()
}, _this.sendTime * Math.pow(2, _this.failTime))
}
loopWrite()
loopSend()
}
private batchWrite(): void {
const _this = this
if (this.dataHasChange) {
if (this.is_first_batch_write) {
this.is_first_batch_write = false
setTimeout(() => {
_this.batchSend()
}, 1000)
}
this.dataHasChange = false
if (this.syncStorage) {
// storage.uploadTrack();
// 缓存数据--uploadTrack
// setStorageSync(STORAGE_PREPARE_DATA_KEY, tracker.store.mem.mdata);
}
}
}
private batchSend(): void {
if (this.dataHasSend) {
let data
let len
const mdata = storage.getTrack()
if (mdata.length >= this.sendNum) {
data = mdata.slice(0, this.sendNum)
} else {
data = mdata
}
len = data.length
if (len > 0) {
this.dataHasSend = false
this.webRequest({
data,
len,
success: this.batchRemove.bind(this),
fail: this.sendFail.bind(this)
})
}
}
}
private batchRemove(len: number): void {
// 删除数据
storage.removeTrack()
this.dataHasSend = true
this.dataHasChange = true
this.batchWrite()
this.failTime = 0
}
private sendFail(): void {
this.dataHasSend = true
this.failTime++
}
private webRequest(option: { data: any; len: number; success: (len: number) => void; fail: () => void }): void {
// if (option.data.length > 0) {
// const data = kit.batchTrackData(option.data);
// logger.info('上报数据监控:', decodeURIComponent(data));
// const temp = JSON.parse(decodeURIComponent(data));
// uploadStroageData(temp, option);
// } else {
// option.success(option.len);
// }
}
}