Skip to content

Commit 4d64dc9

Browse files
committed
fix(mobile): align stream recovery and candle updates
Signed-off-by: TIANHE <[email protected]>
1 parent f83dca3 commit 4d64dc9

4 files changed

Lines changed: 168 additions & 50 deletions

File tree

‎src/utils/exchangeOrderBookWs.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ export default class ExchangeOrderBookWs {
388388
}
389389

390390
this.connectTimer = setTimeout(() => {
391-
if (generation !== this.generation || this.closed || this.everLive) return
391+
if (generation !== this.generation || this.closed || (this.socket && this.socket.readyState === WebSocket.OPEN)) return
392392
this._failSocket()
393393
}, 8000)
394394

@@ -511,6 +511,11 @@ export default class ExchangeOrderBookWs {
511511

512512
_scheduleReconnect () {
513513
if (this.closed || this.reconnectTimer) return
514+
this.generation += 1
515+
this._clearTimer('connectTimer')
516+
this._clearTimer('emitTimer')
517+
this.pendingSnapshot = null
518+
this.everLive = false
514519
this.reconnectAttempts += 1
515520
this.book = new LocalOrderBook()
516521
this.lastDataAt = 0

‎src/utils/exchangeWs.js‎

Lines changed: 47 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,6 @@ export default class ExchangeKlineWs {
330330
this._onReconnecting = null
331331
this._onReconnected = null
332332
this._reconnectAttempts = 0
333-
this._maxReconnectAttempts = 20
334333
this._reconnectTimer = null
335334
this._pingTimer = null
336335
this._closed = false
@@ -344,6 +343,7 @@ export default class ExchangeKlineWs {
344343
this._dataTimeout = null
345344
this._openGen = 0
346345
this._gotData = false
346+
this._awaitingPongAt = 0
347347
}
348348

349349
/**
@@ -448,9 +448,7 @@ export default class ExchangeKlineWs {
448448
clearTimeout(this._connectTimeout)
449449
this._connectTimeout = null
450450
}
451-
const wasReconnect = this._everConnected
452451
this._everConnected = true
453-
this._reconnectAttempts = 0
454452
this._gotData = false
455453
this._startPing()
456454

@@ -465,22 +463,13 @@ export default class ExchangeKlineWs {
465463

466464
// If no data arrives within 12s after open, the connection or subscription
467465
// likely failed silently, so the caller must continue same-venue REST polling.
468-
if (!this._fallbackUsed) {
469-
this._dataTimeout = setTimeout(() => {
470-
if (myGen !== this._openGen) return
471-
if (!this._gotData && !this._closed) {
472-
console.warn(`[ExchangeWs] ${this._exchangeId} connected but no data received`)
473-
this._ws.onclose = null
474-
try { this._ws.close() } catch (_) {}
475-
this._ws = null
476-
this._tryFallback()
477-
}
478-
}, 12000)
479-
}
480-
481-
if (wasReconnect && this._onReconnected) {
482-
this._onReconnected()
483-
}
466+
this._dataTimeout = setTimeout(() => {
467+
if (myGen !== this._openGen) return
468+
if (!this._gotData && !this._closed) {
469+
console.warn(`[ExchangeWs] ${this._exchangeId} connected but no data received`)
470+
this._tryFallback()
471+
}
472+
}, 12000)
484473
}
485474

486475
this._ws.onmessage = (evt) => {
@@ -491,30 +480,30 @@ export default class ExchangeKlineWs {
491480
this._ws.onerror = () => {}
492481

493482
this._ws.onclose = () => {
494-
if (myGen !== this._openGen) return
495-
if (this._connectTimeout) {
496-
clearTimeout(this._connectTimeout)
497-
this._connectTimeout = null
498-
}
499-
this._clearPing()
500-
if (!this._closed) {
501-
if (!this._everConnected && !this._fallbackUsed) {
502-
this._tryFallback()
503-
} else {
504-
if (this._everConnected && this._onReconnecting) {
505-
this._onReconnecting()
506-
}
507-
this._scheduleReconnect()
508-
}
509-
}
483+
if (myGen !== this._openGen || this._closed) return
484+
this._tryFallback()
510485
}
511486
}
512487

513-
_tryFallback () {
488+
_tryFallback (retry = true) {
489+
this._openGen++
514490
this._fallbackUsed = true
515-
this._closed = true
516491
this._clearTimers()
517-
if (this._onError) this._onError()
492+
if (this._ws) {
493+
this._ws.onclose = null
494+
this._ws.onmessage = null
495+
this._ws.onerror = null
496+
this._ws.onopen = null
497+
try { this._ws.close() } catch (_) {}
498+
this._ws = null
499+
}
500+
if (!retry) {
501+
this._closed = true
502+
if (this._onError) this._onError()
503+
return
504+
}
505+
if (this._onReconnecting) this._onReconnecting()
506+
this._scheduleReconnect()
518507
}
519508

520509
async _decodeMessage (raw) {
@@ -540,10 +529,14 @@ export default class ExchangeKlineWs {
540529
return
541530
}
542531
if (generation !== this._openGen || this._closed) return
543-
if (raw === 'pong' || raw === '') return
532+
if (raw === 'pong') { this._awaitingPongAt = 0; return }
533+
if (raw === '') return
544534

545535
let data
546536
try { data = JSON.parse(raw) } catch (_) { return }
537+
if (!data || typeof data !== 'object' || Array.isArray(data)) return
538+
539+
if (String(data.channel || '').endsWith('.pong')) { this._awaitingPongAt = 0; return }
547540

548541
if (data.ping !== undefined) {
549542
try { this._ws.send(JSON.stringify({ pong: data.ping })) } catch (_) {}
@@ -563,22 +556,26 @@ export default class ExchangeKlineWs {
563556
try { this._ws.close() } catch (_) {}
564557
this._ws = null
565558
}
566-
this._tryFallback()
559+
this._tryFallback(false)
567560
}
568561
return
569562
}
570-
if (data.event === 'pong' || data.ret_msg === 'pong') return
563+
if (data.event === 'pong' || data.op === 'pong' || data.ret_msg === 'pong') { this._awaitingPongAt = 0; return }
571564

572565
let parsed
573566
try {
574567
parsed = this._exchangeConf.parseBar(data, this._context())
575568
} catch (_) {
576569
return
577570
}
578-
if (!parsed) return
571+
if (!parsed || ![parsed.timestamp, parsed.open, parsed.high, parsed.low, parsed.close, parsed.volume].every(Number.isFinite) ||
572+
parsed.timestamp <= 0 || parsed.close <= 0 || parsed.volume < 0) return
579573

580574
if (!this._gotData) {
581575
this._gotData = true
576+
this._reconnectAttempts = 0
577+
if (this._fallbackUsed && this._onReconnected) this._onReconnected()
578+
this._fallbackUsed = false
582579
if (this._dataTimeout) {
583580
clearTimeout(this._dataTimeout)
584581
this._dataTimeout = null
@@ -607,11 +604,7 @@ export default class ExchangeKlineWs {
607604
_scheduleReconnect () {
608605
if (this._closed) return
609606
this._reconnectAttempts++
610-
if (this._reconnectAttempts > this._maxReconnectAttempts) {
611-
if (this._onError) this._onError()
612-
return
613-
}
614-
const delay = Math.min(1000 * Math.pow(2, this._reconnectAttempts - 1), 30000)
607+
const delay = Math.min(5000 * Math.pow(2, Math.min(this._reconnectAttempts - 1, 4)), 60000)
615608
this._reconnectTimer = setTimeout(() => {
616609
this._reconnectTimer = null
617610
this._open()
@@ -624,12 +617,18 @@ export default class ExchangeKlineWs {
624617
if (!interval || typeof this._exchangeConf.ping !== 'function') return
625618
this._pingTimer = setInterval(() => {
626619
if (this._ws && this._ws.readyState === WebSocket.OPEN) {
627-
this._exchangeConf.ping(this._ws, this._context())
620+
if (this._awaitingPongAt && Date.now() - this._awaitingPongAt > 45000) {
621+
this._tryFallback()
622+
return
623+
}
624+
if (!this._awaitingPongAt) this._awaitingPongAt = Date.now()
625+
try { this._exchangeConf.ping(this._ws, this._context()) } catch (_) { this._tryFallback() }
628626
}
629627
}, interval)
630628
}
631629

632630
_clearPing () {
631+
this._awaitingPongAt = 0
633632
if (this._pingTimer) {
634633
clearInterval(this._pingTimer)
635634
this._pingTimer = null

‎src/views/indicator/Chart.vue‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,10 @@ function openAi(){router.push({path:'/ai',query:{symbol:form.symbol,market:form.
167167
async function bootstrap(){void warmBaseChart();try{const loaded=await indicatorApi.getList();indicators.value=loaded.data||[];const id=Number(route.query.indicator_id||route.query.local_copy_id||0);const preferred=indicators.value.find(x=>Number(x.id)===id)||indicators.value[0];if(preferred)await selectIndicator({indicatorId:Number(preferred.id)});else await loadChart()}catch(e){if(!chartData.value?.candles?.length){error.value=e?.localizedMessage||e?.message||t('audit.loadFailed');await warmBaseChart()}}}
168168
function clearStreamFallback(){clearTimeout(streamFallbackTimer);streamFallbackTimer=null}
169169
function flushChartBar(){chartFrame=null;const bar=pendingChartBar;pendingChartBar=null;if(bar)marketChart.value?.updateBar(bar)}
170-
function scheduleChartBar(bar){pendingChartBar=bar;if(chartFrame===null)chartFrame=requestAnimationFrame(flushChartBar)}
170+
function scheduleChartBar(bar){
171+
if(pendingChartBar&&bar.timestamp>pendingChartBar.timestamp){cancelAnimationFrame(chartFrame);flushChartBar()}
172+
pendingChartBar=bar;if(chartFrame===null)chartFrame=requestAnimationFrame(flushChartBar)
173+
}
171174
function stopStream(){streamGeneration++;stream?.disconnect();stream=null;clearStreamFallback();if(chartFrame!==null)cancelAnimationFrame(chartFrame);chartFrame=null;pendingChartBar=null;lastTick=0;pendingBar=null}
172175
function startStream(){
173176
stopStream()

‎tests/unit/streamRecovery.test.mjs‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import assert from 'node:assert/strict'
2+
import test from 'node:test'
3+
import ExchangeKlineWs from '../../src/utils/exchangeWs.js'
4+
import ExchangeOrderBookWs from '../../src/utils/exchangeOrderBookWs.js'
5+
6+
const bar = (timestamp = 60000) => JSON.stringify({ e: 'kline', k: { t: timestamp, o: '100', h: '102', l: '99', c: '101', v: '5', x: false } })
7+
function sockets (t) {
8+
const instances = []
9+
class Socket {
10+
static OPEN = 1
11+
constructor (url) { this.url = url; this.readyState = 0; this.messages = []; instances.push(this) }
12+
send (message) { this.messages.push(message) }
13+
close () { this.readyState = 3 }
14+
open () { this.readyState = 1; this.onopen() }
15+
}
16+
const original = globalThis.WebSocket
17+
globalThis.WebSocket = Socket
18+
t.after(() => { globalThis.WebSocket = original })
19+
t.mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'], now: 100000 })
20+
return instances
21+
}
22+
23+
test('transport failure keeps REST available and recovers only after valid same-venue candles', async t => {
24+
const ws = sockets(t)
25+
const client = new ExchangeKlineWs()
26+
t.after(() => client.disconnect())
27+
let fallback = 0; let recovered = 0; const ticks = []
28+
assert.equal(client.connect('BTC/USDT', '1m', {
29+
onTick: value => ticks.push(value), onReconnecting: () => fallback++, onReconnected: () => recovered++
30+
}, 'binance', { marketType: 'swap' }), true)
31+
t.mock.timers.tick(8000)
32+
assert.equal(fallback, 1)
33+
assert.equal(client._closed, false)
34+
t.mock.timers.tick(5000)
35+
assert.equal(ws.length, 2)
36+
assert.equal(ws[0].url, ws[1].url)
37+
ws[1].open()
38+
assert.equal(recovered, 0)
39+
await client._handleMessage({ data: bar() })
40+
assert.equal(recovered, 1)
41+
assert.equal(ticks.length, 1)
42+
assert.equal(client._reconnectAttempts, 0)
43+
})
44+
45+
test('silent reopened sockets continue bounded backoff; disconnect cancels pending recovery', t => {
46+
const ws = sockets(t)
47+
const client = new ExchangeKlineWs()
48+
t.after(() => client.disconnect())
49+
client.connect('BTC/USDT', '1m', { onTick () {} }, 'binance')
50+
ws[0].open()
51+
t.mock.timers.tick(12000)
52+
t.mock.timers.tick(5000)
53+
ws[1].open()
54+
t.mock.timers.tick(12000)
55+
assert.equal(client._reconnectAttempts, 2)
56+
client.disconnect()
57+
t.mock.timers.tick(120000)
58+
assert.equal(ws.length, 2)
59+
})
60+
61+
test('invalid candles never end fallback and old generations never publish', async t => {
62+
const ws = sockets(t)
63+
const client = new ExchangeKlineWs()
64+
t.after(() => client.disconnect())
65+
let ticks = 0
66+
client.connect('BTC/USDT', '1m', { onTick () { ticks++ } }, 'binance')
67+
ws[0].open()
68+
const oldGeneration = client._openGen
69+
await client._handleMessage({ data: 'null' })
70+
await client._handleMessage({ data: '[]' })
71+
await client._handleMessage({ data: bar().replace('"101"', '"NaN"') })
72+
assert.equal(client._gotData, false)
73+
client._tryFallback()
74+
await client._handleMessage({ data: bar() }, oldGeneration)
75+
assert.equal(ticks, 0)
76+
})
77+
78+
test('missing application pong triggers recovery without falsely reporting a live stream', t => {
79+
const ws = sockets(t)
80+
const client = new ExchangeKlineWs()
81+
t.after(() => client.disconnect())
82+
let fallback = 0
83+
client.connect('BTC/USDT', '1m', { onTick () {}, onReconnecting () { fallback++ } }, 'bitget')
84+
ws[0].open()
85+
client._gotData = true
86+
t.mock.timers.tick(25000)
87+
assert.equal(ws[0].messages.at(-1), 'ping')
88+
t.mock.timers.tick(50000)
89+
assert.equal(fallback, 1)
90+
})
91+
92+
test('order book recovery clears stale queued snapshots and reports live again', async t => {
93+
const ws = sockets(t)
94+
const client = new ExchangeOrderBookWs()
95+
t.after(() => client.disconnect())
96+
const statuses = []; const snapshots = []
97+
client.connect('BTC/USDT', { onStatus: value => statuses.push(value), onSnapshot: value => snapshots.push(value) }, 'binance')
98+
ws[0].open()
99+
const frame = { data: JSON.stringify({ lastUpdateId: 1, bids: [['100', '2']], asks: [['101', '3']] }) }
100+
await client._handleMessage(frame, client.generation)
101+
assert.equal(statuses.at(-1), 'live')
102+
client._failSocket()
103+
t.mock.timers.tick(100)
104+
assert.equal(snapshots.length, 0)
105+
t.mock.timers.tick(1200)
106+
ws[1].open()
107+
await client._handleMessage(frame, client.generation)
108+
assert.equal(statuses.at(-1), 'live')
109+
t.mock.timers.tick(100)
110+
assert.equal(snapshots.length, 1)
111+
})

0 commit comments

Comments
 (0)