-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.ts
170 lines (146 loc) · 4.16 KB
/
utils.ts
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import sortBy from 'lodash/sortBy'
export function nonNullable<T>(value: T): value is NonNullable<T> {
return value !== null && value !== undefined
}
export function pmap<MapType, ResultType>(
iterable: Iterable<MapType>,
mapper: (x: MapType, index: number) => Promise<ResultType>,
options: { concurrency: number }
) {
return new Promise<ResultType[]>((resolve, reject) => {
options = Object.assign(
{
concurrency: Infinity
},
options
)
if (typeof mapper !== 'function') {
throw new TypeError('Mapper function is required')
}
const { concurrency } = options
if (!(typeof concurrency === 'number' && concurrency >= 1)) {
throw new TypeError(
// tslint:disable-next-line:max-line-length
`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`
)
}
const ret: ResultType[] = []
const iterator = iterable[Symbol.iterator]()
let isRejected = false
let isIterableDone = false
let resolvingCount = 0
let currentIndex = 0
const next = () => {
if (isRejected) {
return
}
const nextItem = iterator.next()
const i = currentIndex
currentIndex++
if (nextItem.done) {
isIterableDone = true
if (resolvingCount === 0) {
resolve(ret)
}
return
}
resolvingCount++
Promise.resolve(nextItem.value)
.then(element => mapper(element, i))
.then(
value => {
ret[i] = value
resolvingCount--
next()
},
error => {
isRejected = true
reject(error)
}
)
}
for (let i = 0; i < concurrency; i++) {
next()
if (isIterableDone) {
break
}
}
})
}
export function retry<T>(
f: () => Promise<T>,
{
times,
delay,
onRetry
}: { times: number; delay: number; onRetry?(e: Error, times: number): void }
): Promise<T> {
const res = f()
if (times > 0) {
return res.catch(e => {
if (onRetry) onRetry(e, times)
return new Promise((resolve, _) => setTimeout(resolve, delay)).then(_ =>
retry(f, { times: times - 1, delay })
)
})
} else {
return res
}
}
export function withTimeout<T>(promise: Promise<T>, ms: number, lbl: string): Promise<T> {
const timeout = new Promise<T>((_, reject) =>
setTimeout(() => reject(new Error(`${lbl}: timed out after ${ms} ms.`)), ms)
)
return Promise.race([promise, timeout])
}
export class LimitedArray {
constructor(
public maxSize = 500,
{ isReportLatency = false, label }: { isReportLatency: boolean; label?: string }
) {
if (isReportLatency) {
setInterval(() => {
const sources = Object.keys(this.avgLagPerSource)
const report = sortBy(
sources.map(name => ({
name,
place: this.avgPlace[name],
avgLag: this.avgLagPerSource[name]
})),
'place'
)
.map(x => `${x.name}: ${x.place} (${x.avgLag})`)
.join(', ')
console.log(`websocket latency ${label}, ${report}`)
}, 60 * 1000)
}
}
avgLagPerSource: Record<string, number> = {}
avgPlace: Record<string, number> = {}
xs: { value: string; source: string; time: number; counter: number }[] = []
add(value: string, source: string) {
this.xs.push({ value, source, time: Date.now(), counter: 1 })
this.avgPlace[source] = ((this.avgPlace[source] || 1) + 1) / 2
if (this.xs.length >= this.maxSize) {
this.xs.shift()
}
}
has(value: string, source: string) {
const result = this.xs.find(x => x.value === value)
if (result) {
result.counter++
if (!this.avgLagPerSource[source]) {
this.avgLagPerSource[source] = Date.now() - result.time
} else {
this.avgLagPerSource[source] =
(this.avgLagPerSource[source] + (Date.now() - result.time)) / 2
}
if (this.avgPlace[source]) {
this.avgPlace[source] = ((this.avgPlace[source] || 1) + result.counter) / 2
} else {
this.avgPlace[source] = result.counter
}
}
return result
}
}