Skip to content

Commit f362a63

Browse files
committed
Opt: Patch aiofiles to reduce thread pool size
1 parent 3d262a5 commit f362a63

2 files changed

Lines changed: 40 additions & 10 deletions

File tree

module/webui/app.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from typing import Dict, List, Optional
99

1010
from pywebio import config as webconfig
11-
from pywebio.input import file_upload, input_group, input, select
11+
from pywebio.input import file_upload, input, input_group, select
1212
from pywebio.output import (
1313
Output,
1414
clear,
@@ -32,15 +32,7 @@
3232
use_scope,
3333
)
3434
from pywebio.pin import pin, pin_on_change
35-
from pywebio.session import (
36-
go_app,
37-
info,
38-
local,
39-
register_thread,
40-
run_js,
41-
set_env,
42-
download,
43-
)
35+
from pywebio.session import (download, go_app, info, local, register_thread, run_js, set_env)
4436

4537
import module.webui.lang as lang
4638
from module.config.config import AzurLaneConfig, Function
@@ -64,6 +56,7 @@
6456
from module.webui.discord_presence import close_discord_rpc, init_discord_rpc
6557
from module.webui.fastapi import asgi_app
6658
from module.webui.lang import _t, t
59+
from module.webui.patch import patch_executor
6760
from module.webui.pin import put_input, put_select
6861
from module.webui.process_manager import ProcessManager
6962
from module.webui.remote_access import RemoteAccess
@@ -94,6 +87,7 @@
9487
put_output,
9588
)
9689

90+
patch_executor()
9791
task_handler = TaskHandler()
9892

9993

module/webui/patch.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import asyncio
2+
from functools import partial, wraps
3+
4+
from module.logger import logger
5+
from module.webui.setting import cached_class_property
6+
7+
8+
class CachedThreadPoolExecutor:
9+
@cached_class_property
10+
def executor(cls):
11+
from concurrent.futures.thread import ThreadPoolExecutor
12+
pool = ThreadPoolExecutor(max_workers=5)
13+
logger.info('Patched ThreadPoolExecutor created')
14+
return pool
15+
16+
17+
def wrap(func):
18+
@wraps(func)
19+
async def run(*args, loop=None, executor=None, **kwargs):
20+
if loop is None:
21+
loop = asyncio.get_event_loop()
22+
if executor is None:
23+
executor = CachedThreadPoolExecutor.executor
24+
pfunc = partial(func, *args, **kwargs)
25+
return await loop.run_in_executor(executor, pfunc)
26+
27+
return run
28+
29+
30+
def patch_executor():
31+
"""
32+
Limit pool size in loop.run_in_executor
33+
so starlette.staticfiles -> aiofiles won't create tons of threads
34+
"""
35+
loop = asyncio.get_event_loop()
36+
loop.set_default_executor(CachedThreadPoolExecutor.executor)

0 commit comments

Comments
 (0)