Skip to content

Commit

Permalink
fix(ui): unresponsive (#14)
Browse files Browse the repository at this point in the history
* refactor(go): routes

* refactor(ui): App

* feat(ui): counter

* feat(ui): better websocket

reconnect. ping

* refactor(ui): rename

* fix(ui): ws mining log

* refactor(ui): ticker

* fix(ui): page mining clear all logs in destory hook

* chore(ui): clean code

* feat(go): ws ping

* refactor(ui): use/websocket private vars

* chore(go): clean println

* fix(ui): typo

* fix(ui): stop ticker
  • Loading branch information
2nthony authored Aug 31, 2021
1 parent edef79d commit 6401dfc
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 34 deletions.
40 changes: 37 additions & 3 deletions Router.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ package main
import (
"fmt"
"net/http"
"time"

"github.com/gorilla/websocket"
)

func registerRoutes() {
http.Handle("/", http.FileServer(http.Dir("dist")))
http.HandleFunc("/wsMiningLog", wsMiningLog)
http.HandleFunc("/mining-log", serveWsMiningLog)
}

func wsMiningLog(w http.ResponseWriter, r *http.Request) {
var upgrader = websocket.Upgrader{}
func serveWsMiningLog(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{}

ws, socketErr := upgrader.Upgrade(w, r, nil)
if socketErr != nil {
Expand All @@ -28,4 +29,37 @@ func wsMiningLog(w http.ResponseWriter, r *http.Request) {
fmt.Printf("writeMessageErr: %v\n", writeMessageErr)
}
})

wsPing(ws)
}

func wsPing(ws *websocket.Conn) {
pingCount := 0
var ticker *time.Ticker = time.NewTicker(10 * time.Second)

go func() {
for t := range ticker.C {
fmt.Println("tick:", t)
pingCount += 1

if pingCount >= 30 {
ws.Close()
ticker.Stop()
}
}
}()

for {
_, message, err := ws.ReadMessage()
if err != nil {
fmt.Printf("readMessageErr: %v\n", err)
break
}
m := string(message)

// reset ping count
if m == "ping" {
pingCount = 0
}
}
}
9 changes: 3 additions & 6 deletions client/src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import '@shoelace-style/shoelace/dist/themes/light.css'
import '@shoelace-style/shoelace/dist/themes/dark.css'
import { onMount } from 'svelte'
import { routes, Router } from './router'
import { ipc } from './ipc'
import { log } from './util/log'
Expand All @@ -18,11 +17,9 @@
})
ipc.send('emitPageReady')
onMount(() => {
checkUpdate()
prefersDark()
wsMiningLog()
})
checkUpdate()
prefersDark()
wsMiningLog()
</script>

<main class="p-6 h-screen">
Expand Down
5 changes: 4 additions & 1 deletion client/src/helper/prefersDark.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Use listen just I am lazy
import { onDestroy } from 'svelte'
import { listen } from 'svelte/internal'

export function prefersDark() {
Expand All @@ -9,7 +10,9 @@ export function prefersDark() {
toggleDarkTheme()
}

listen(media, 'change', toggleDarkTheme)
const unlisten = listen(media, 'change', toggleDarkTheme)

onDestroy(unlisten)
}

function toggleDarkTheme() {
Expand Down
32 changes: 29 additions & 3 deletions client/src/helper/wsMiningLog.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { onDestroy } from 'svelte'
import { listen } from 'svelte/internal'
import { useWebsocket } from '../use/websocket'
import { miningLogs } from '../store'
import { ticker } from '../util/ticker'

export function wsMiningLog() {
const { message: onMiningLog } = useWebsocket(
`ws://${location.host}/wsMiningLog`,
)
const {
message: onMiningLog,
ping,
reconnect,
} = useWebsocket(`ws://${location.host}/mining-log`)

onMiningLog((log) => {
miningLogs.update((val) => {
Expand All @@ -17,4 +22,25 @@ export function wsMiningLog() {
return val
})
})

const pingTicker = ticker(10, ping)

const unlisten = listen(
document,
'visibilitychange',
() => {
if (document.visibilityState === 'visible') {
reconnect()
pingTicker.startTicker()
} else {
pingTicker.stopTicker()
}
},
false,
)

onDestroy(() => {
unlisten()
pingTicker.stopTicker()
})
}
5 changes: 4 additions & 1 deletion client/src/pages/mining.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script>
import '@shoelace-style/shoelace/dist/components/button/button'
import '@shoelace-style/shoelace/dist/components/tooltip/tooltip'
import { onMount } from 'svelte'
import { onMount, onDestroy } from 'svelte'
import * as store from '../store'
import { getBalance } from '../server/unMineable'
import IconRefresh from '../components/icons/Refresh.svelte'
Expand Down Expand Up @@ -97,6 +97,9 @@
onMount(() => {
handleGetBalance()
})
onDestroy(() => {
store.miningLogs.set([])
})
</script>

<section class="flex flex-col justify-between h-full">
Expand Down
53 changes: 33 additions & 20 deletions client/src/use/websocket.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,49 @@
import { log } from '../util/log'

/** @type {WebSocket} */
let ws

export function useWebsocket(url, protocol) {
/** @type {WebSocket} */
let ws

const onMessage = []

ws = new WebSocket(url, protocol)
connect(url, protocol)

ws.onmessage = (event) => {
invokeAll(onMessage, event.data)
}
ws.onopen = () => {
log('ws', 'opened.')
function invokeAll(fns, data) {
if (!ws) {
log('ws', 'ws is not available')
return
}

fns.forEach((fn) => fn(data))
}
ws.onclose = () => {
log('ws', 'closed.')
ws = null

function connect(url, protocol) {
ws = new WebSocket(url, protocol)

ws.onmessage = (event) => {
invokeAll(onMessage, event.data)
}
ws.onopen = () => {
log('ws', 'opened.')
}
ws.onclose = () => {
log('ws', 'closed.')
ws = null
}
}

return {
message(fn) {
onMessage.push(fn)
},
}
}

function invokeAll(fns, data) {
if (!ws) {
log('ws', 'ws is not available')
return
ping: () => {
if (!ws) return
ws.send('ping')
},
reconnect: () => {
if (ws) return
connect(url, protocol)
},
}

fns.forEach((fn) => fn(data))
}
30 changes: 30 additions & 0 deletions client/src/util/ticker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export function ticker(second, cb) {
let ticker
let count = 0
const resetCount = () => {
count = 0
}

startTicker()

function startTicker() {
if (ticker) return

ticker = setInterval(() => {
if (count >= second) {
cb()
resetCount()
}

count++
}, 1000)
}

return {
resetCount,
startTicker,
stopTicker: () => {
ticker = clearInterval(ticker)
},
}
}

0 comments on commit 6401dfc

Please sign in to comment.