feat: implement SPEC-11 API performance optimizations (#315) · basicmachines-co/basic-memory@5da97e4 · GitHub
Skip to content

Commit 5da97e4

Browse files
phernandezclaude
andauthored
feat: implement SPEC-11 API performance optimizations (#315)
Signed-off-by: phernandez <paul@basicmachines.co> Co-authored-by: Claude <noreply@anthropic.com>
1 parent 17a6733 commit 5da97e4

9 files changed

Lines changed: 320 additions & 79 deletions

File tree

Lines changed: 245 additions & 0 deletions

src/basic_memory/api/app.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,23 @@
2222
webdav,
2323
)
2424
from basic_memory.config import ConfigManager
25-
from basic_memory.services.initialization import initialize_app, initialize_file_sync
25+
from basic_memory.services.initialization import initialize_file_sync
2626

2727

2828
@asynccontextmanager
2929
async def lifespan(app: FastAPI): # pragma: no cover
3030
"""Lifecycle manager for the FastAPI app."""
3131

3232
app_config = ConfigManager().config
33-
# Initialize app and database
3433
logger.info("Starting Basic Memory API")
3534
print(f"fastapi {app_config.projects}")
36-
await initialize_app(app_config)
35+
36+
# Cache database connections in app state for performance (no project reconciliation)
37+
logger.info("Initializing database and caching connections...")
38+
engine, session_maker = await db.get_or_create_db(app_config.database_path)
39+
app.state.engine = engine
40+
app.state.session_maker = session_maker
41+
logger.info("Database connections cached in app state")
3742

3843
logger.info(f"Sync changes enabled: {app_config.sync_changes}")
3944
if app_config.sync_changes:

src/basic_memory/config.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ class BasicMemoryConfig(BaseSettings):
9393
description="Format for generated filenames. False preserves spaces and special chars, True converts them to hyphens for consistency with permalinks",
9494
)
9595

96+
skip_initialization_sync: bool = Field(
97+
default=False,
98+
description="Skip expensive initialization synchronization. Useful for cloud/stateless deployments where project reconciliation is not needed.",
99+
)
100+
96101
# API connection configuration
97102
api_url: Optional[str] = Field(
98103
default=None,
@@ -341,8 +346,6 @@ def save_basic_memory_config(file_path: Path, config: BasicMemoryConfig) -> None
341346
logger.error(f"Failed to save config: {e}")
342347

343348

344-
345-
346349
# setup logging to a single log file in user home directory
347350
user_home = Path.home()
348351
log_dir = user_home / DATA_DIR_NAME

src/basic_memory/deps.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from typing import Annotated
44
from loguru import logger
55

6-
from fastapi import Depends, HTTPException, Path, status
6+
from fastapi import Depends, HTTPException, Path, status, Request
77
from sqlalchemy.ext.asyncio import (
88
AsyncSession,
99
AsyncEngine,
@@ -78,9 +78,24 @@ async def get_project_config(
7878

7979

8080
async def get_engine_factory(
81-
app_config: AppConfigDep,
81+
request: Request,
8282
) -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]: # pragma: no cover
83-
"""Get engine and session maker."""
83+
"""Get cached engine and session maker from app state.
84+
85+
For API requests, returns cached connections from app.state for optimal performance.
86+
For non-API contexts (CLI), falls back to direct database connection.
87+
"""
88+
# Try to get cached connections from app state (API context)
89+
if (
90+
hasattr(request, "app")
91+
and hasattr(request.app.state, "engine")
92+
and hasattr(request.app.state, "session_maker")
93+
):
94+
return request.app.state.engine, request.app.state.session_maker
95+
96+
# Fallback for non-API contexts (CLI)
97+
logger.debug("Using fallback database connection for non-API context")
98+
app_config = get_app_config()
8499
engine, session_maker = await db.get_or_create_db(app_config.database_path)
85100
return engine, session_maker
86101

src/basic_memory/mcp/tools/__init__.py

Lines changed: 1 addition & 0 deletions

0 commit comments

Comments
 (0)