Skip to content

Commit cbb4319

Browse files
committed
Enhance state management and logging functionality
- Updated `serve` function in `run.py` to utilize the `workers` argument in development mode. - Improved `executed_state` function in `executed_state.py` to handle multiple new states more efficiently, including error handling for state insertion. - Modified `LogsManager` in `logs_manager.py` to dynamically set logging level based on the application mode (development or production). - Added logging for state creation in `create_next_state.py` to improve traceability. These changes aim to enhance the application's performance and maintainability in different environments.
1 parent 2326ef0 commit cbb4319

4 files changed

Lines changed: 51 additions & 8 deletions

File tree

state-manager/app/controller/executed_state.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from beanie import PydanticObjectId
2+
from beanie.operators import In
23
from app.models.executed_models import ExecutedRequestModel, ExecutedResponseModel
34

45
from fastapi import HTTPException, status, BackgroundTasks
@@ -36,11 +37,11 @@ async def executed_state(namespace_name: str, state_id: PydanticObjectId, body:
3637
state.parents = {**state.parents, state.identifier: state.id}
3738

3839
await state.save()
39-
4040
background_tasks.add_task(create_next_state, state)
4141

42+
new_states = []
4243
for output in body.outputs[1:]:
43-
new_state = State(
44+
new_states.append(State(
4445
node_name=state.node_name,
4546
namespace_name=state.namespace_name,
4647
identifier=state.identifier,
@@ -54,9 +55,20 @@ async def executed_state(namespace_name: str, state_id: PydanticObjectId, body:
5455
**state.parents,
5556
state.identifier: state.id
5657
}
57-
)
58-
await new_state.save()
59-
background_tasks.add_task(create_next_state, new_state)
58+
))
59+
60+
if len(new_states) > 0:
61+
inserted_ids = (await State.insert_many(new_states)).inserted_ids
62+
63+
inserted_states = await State.find(
64+
In(State.id, inserted_ids)
65+
).to_list()
66+
67+
if len(inserted_states) != len(new_states):
68+
raise Exception(f"Failed to insert all new states. Expected {len(new_states)} states, but only {len(inserted_states)} were inserted")
69+
70+
for inserted_state in inserted_states:
71+
background_tasks.add_task(create_next_state, inserted_state)
6072

6173
return ExecutedResponseModel(status=StateStatusEnum.EXECUTED)
6274

state-manager/app/singletons/logs_manager.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import structlog
22
import logging
3+
import os
4+
import sys
35
from .SingletonDecorator import singleton
46

57

@@ -28,9 +30,37 @@ def __init__(self):
2830
handler.setFormatter(formatter)
2931
logger = logging.getLogger()
3032
logger.addHandler(handler)
31-
logger.setLevel(logging.INFO)
33+
34+
# Check if running in development mode
35+
# Development mode is determined by the --mode argument passed to run.py
36+
is_development = self._is_development_mode()
37+
38+
if is_development:
39+
# In development mode, set level to WARNING to disable INFO logs
40+
logger.setLevel(logging.WARNING)
41+
else:
42+
# In production mode, keep INFO level
43+
logger.setLevel(logging.INFO)
3244

3345
self.logger = structlog.get_logger()
3446

47+
def _is_development_mode(self) -> bool:
48+
"""
49+
Check if the application is running in development mode.
50+
Development mode is determined by checking if '--mode' 'development'
51+
is in the command line arguments.
52+
"""
53+
# Check command line arguments for development mode
54+
if '--mode' in sys.argv:
55+
try:
56+
mode_index = sys.argv.index('--mode')
57+
if mode_index + 1 < len(sys.argv) and sys.argv[mode_index + 1] == 'development':
58+
return True
59+
except (ValueError, IndexError):
60+
pass
61+
62+
# Fallback: check environment variable
63+
return os.getenv('MODE', '').lower() == 'development'
64+
3565
def get_logger(self):
3666
return self.logger

state-manager/app/tasks/create_next_state.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
logger = LogsManager().get_logger()
1515

1616
async def create_next_state(state: State):
17+
logger.info(f"Creating next state for {state.identifier}")
1718
graph_template = None
1819

1920
if state is None or state.id is None:

state-manager/run.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@
1212

1313
def serve():
1414
mode = args.mode
15+
workers = args.workers
1516
if mode == "development":
16-
uvicorn.run("app.main:app", reload=True, host="0.0.0.0", port=8000)
17+
uvicorn.run("app.main:app", workers=workers, reload=True, host="0.0.0.0", port=8000)
1718
elif mode == "production":
18-
workers = args.workers
1919
print(f"Running with {workers} workers")
2020
uvicorn.run("app.main:app", workers=workers, host="0.0.0.0", port=8000)
2121
else:

0 commit comments

Comments
 (0)