Skip to content

Commit

Permalink
require a magic response for dev reload server to reconnect (#115)
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin authored Dec 21, 2023
1 parent 4274a8d commit 429275b
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
20 changes: 13 additions & 7 deletions src/npm-fastui/src/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FC, useContext, useEffect } from 'react'
import { sleep } from './tools'
import { ErrorContext } from './hooks/error'
import { fireLoadEvent } from './events'
import { ConfigContext } from './hooks/config'

let devConnected = false

Expand All @@ -20,6 +21,7 @@ export const DevReload: FC<{ enabled?: boolean }> = ({ enabled }) => {

const DevReloadActive = () => {
const { setError } = useContext(ErrorContext)
const { rootUrl } = useContext(ConfigContext)

useEffect(() => {
let listening = true
Expand All @@ -34,21 +36,22 @@ const DevReloadActive = () => {
if (!listening || failCount >= 5) {
return count
}
const response = await fetch('/api/__dev__/reload')
const response = await fetch(rootUrl + '/__dev__/reload')
count++
console.debug(`dev reload connected ${count}...`)
// if the response is okay, and we previously failed, clear error
if (response.ok && failCount > 0) {
setError(null)
} else if (response.status === 404) {
console.log('dev reload endpoint not found, disabling dev reload')
return count
}
// await like this means we wait for the entire response to be received
const text = await response.text()
if (response.status === 404) {
console.log('dev reload endpoint not found, disabling dev reload')
return count
} else if (response.ok) {
if (response.ok && text.startsWith('fastui-dev-reload')) {
failCount = 0
const value = parseInt(text.replace(/\./g, '')) || 0
const valueMatch = text.match(/(\d+)$/)
const value = valueMatch ? parseInt(valueMatch[1]!) : 0
if (value !== lastValue) {
lastValue = value
// wait long enough for the server to be back online
Expand All @@ -57,6 +60,9 @@ const DevReloadActive = () => {
fireLoadEvent({ reloadValue: value })
setError(null)
}
} else if (response.ok) {
console.log("dev reload endpoint didn't return magic value, disabling dev reload")
return count
} else {
failCount++
await sleep(2000)
Expand All @@ -72,6 +78,6 @@ const DevReloadActive = () => {
devConnected = false
}
}
}, [setError])
}, [setError, rootUrl])
return <></>
}
3 changes: 2 additions & 1 deletion src/python-fastui/fastui/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,15 @@ async def lifespan(self, app: FastAPI):
yield

async def dev_reload_endpoints(self):
return StreamingResponse(self.ping())
return StreamingResponse(self.ping(), media_type='text/plain')

def _on_signal(self, *_args: _t.Any):
# print('setting stop', _args)
self.stop.set()

async def ping(self):
# print('connected', os.getpid())
yield b'fastui-dev-reload\n'
yield b'.'
while True:
try:
Expand Down
19 changes: 19 additions & 0 deletions src/python-fastui/tests/test_dev.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from unittest.mock import patch

from fastui.dev import dev_fastapi_app
from httpx import AsyncClient


def mock_signal(_sig, on_signal):
on_signal()


async def test_dev_connect():
with patch('fastui.dev.signal.signal', new=mock_signal):
app = dev_fastapi_app()
async with app.router.lifespan_context(app):
async with AsyncClient(app=app, base_url='http://test') as client:
r = await client.get('/api/__dev__/reload')
assert r.status_code == 200
assert r.headers['content-type'] == 'text/plain; charset=utf-8'
assert r.text.startswith('fastui-dev-reload\n')

0 comments on commit 429275b

Please sign in to comment.