Offer polling instead of inotify for OSes other than Linux

This commit is contained in:
Leo Vasanko 2023-11-07 15:37:47 -08:00
parent d42f0f7601
commit 2695fc67f3

View File

@ -1,10 +1,10 @@
import asyncio import asyncio
import shutil import shutil
import sys
import threading import threading
import time import time
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
import inotify.adapters
import msgspec import msgspec
from sanic.log import logging from sanic.log import logging
@ -31,6 +31,7 @@ disk_usage = None
def watcher_thread(loop): def watcher_thread(loop):
global disk_usage, rootpath global disk_usage, rootpath
import inotify.adapters
while True: while True:
rootpath = config.config.path rootpath = config.config.path
@ -74,6 +75,29 @@ def watcher_thread(loop):
i = None # Free the inotify object i = None # Free the inotify object
def watcher_thread_poll(loop):
global disk_usage, rootpath
while True:
rootpath = config.config.path
old = format_tree() if tree[""] else None
with tree_lock:
# Initialize the tree from filesystem
tree[""] = walk(rootpath)
print(" ".join(tree[""].dir.keys()))
msg = format_tree()
if msg != old:
asyncio.run_coroutine_threadsafe(broadcast(msg), loop)
# Disk usage update
du = shutil.disk_usage(rootpath)
if du != disk_usage:
disk_usage = du
asyncio.run_coroutine_threadsafe(broadcast(format_du()), loop)
time.sleep(1.0)
def format_du(): def format_du():
return msgspec.json.encode( return msgspec.json.encode(
{ {
@ -201,7 +225,10 @@ async def broadcast(msg):
async def start(app, loop): async def start(app, loop):
config.load_config() config.load_config()
app.ctx.watcher = threading.Thread(target=watcher_thread, args=[loop]) app.ctx.watcher = threading.Thread(
target=watcher_thread if sys.platform == "linux" else watcher_thread_poll,
args=[loop],
)
app.ctx.watcher.start() app.ctx.watcher.start()