|
| 1 | +"""Shared initialization service for Basic Memory. |
| 2 | +
|
| 3 | +This module provides shared initialization functions used by both CLI and API |
| 4 | +to ensure consistent application startup across all entry points. |
| 5 | +""" |
| 6 | + |
| 7 | +import asyncio |
| 8 | +from typing import Optional, Tuple |
| 9 | + |
| 10 | +from loguru import logger |
| 11 | + |
| 12 | +from basic_memory import db |
| 13 | +from basic_memory.config import ProjectConfig, config_manager |
| 14 | +from basic_memory.sync import SyncService, WatchService |
| 15 | + |
| 16 | +# Import this inside functions to avoid circular imports |
| 17 | +# from basic_memory.cli.commands.sync import get_sync_service |
| 18 | + |
| 19 | + |
| 20 | +async def initialize_database(app_config: ProjectConfig) -> None: |
| 21 | + """Run database migrations to ensure schema is up to date. |
| 22 | +
|
| 23 | + Args: |
| 24 | + app_config: The Basic Memory project configuration |
| 25 | + """ |
| 26 | + try: |
| 27 | + logger.info("Running database migrations...") |
| 28 | + await db.run_migrations(app_config) |
| 29 | + logger.info("Migrations completed successfully") |
| 30 | + except Exception as e: |
| 31 | + logger.error(f"Error running migrations: {e}") |
| 32 | + # Allow application to continue - it might still work |
| 33 | + # depending on what the error was, and will fail with a |
| 34 | + # more specific error if the database is actually unusable |
| 35 | + |
| 36 | + |
| 37 | +async def initialize_file_sync( |
| 38 | + app_config: ProjectConfig, |
| 39 | +) -> Tuple[Optional[SyncService], Optional[WatchService], Optional[asyncio.Task]]: |
| 40 | + """Initialize file synchronization services. |
| 41 | +
|
| 42 | + Args: |
| 43 | + app_config: The Basic Memory project configuration |
| 44 | +
|
| 45 | + Returns: |
| 46 | + Tuple of (sync_service, watch_service, watch_task) if sync is enabled, |
| 47 | + or (None, None, None) if sync is disabled |
| 48 | + """ |
| 49 | + # Load app configuration |
| 50 | + basic_memory_config = config_manager.load_config() |
| 51 | + logger.info(f"Sync changes enabled: {basic_memory_config.sync_changes}") |
| 52 | + logger.info( |
| 53 | + f"Update permalinks on move enabled: {basic_memory_config.update_permalinks_on_move}" |
| 54 | + ) |
| 55 | + |
| 56 | + if not basic_memory_config.sync_changes: |
| 57 | + logger.info("Sync changes disabled. Skipping watch service.") |
| 58 | + return None, None, None |
| 59 | + |
| 60 | + try: |
| 61 | + # Import here to avoid circular imports |
| 62 | + from basic_memory.cli.commands.sync import get_sync_service |
| 63 | + |
| 64 | + # Initialize sync service |
| 65 | + sync_service = await get_sync_service() |
| 66 | + |
| 67 | + # Initialize watch service |
| 68 | + watch_service = WatchService( |
| 69 | + sync_service=sync_service, |
| 70 | + file_service=sync_service.entity_service.file_service, |
| 71 | + config=app_config, |
| 72 | + ) |
| 73 | + |
| 74 | + # Start background sync task |
| 75 | + logger.info(f"Starting watch service to sync file changes in dir: {app_config.home}") |
| 76 | + |
| 77 | + # Create the background task for running sync |
| 78 | + async def run_background_sync(): |
| 79 | + # Run initial full sync |
| 80 | + await sync_service.sync(app_config.home, show_progress=False) |
| 81 | + # Start watching for changes |
| 82 | + await watch_service.run() |
| 83 | + |
| 84 | + watch_task = asyncio.create_task(run_background_sync()) |
| 85 | + |
| 86 | + return sync_service, watch_service, watch_task |
| 87 | + except Exception as e: |
| 88 | + logger.error(f"Error initializing file sync: {e}") |
| 89 | + return None, None, None |
| 90 | + |
| 91 | + |
| 92 | +async def initialize_app( |
| 93 | + app_config: ProjectConfig, |
| 94 | +) -> Tuple[Optional[SyncService], Optional[WatchService], Optional[asyncio.Task]]: |
| 95 | + """Initialize the Basic Memory application. |
| 96 | +
|
| 97 | + This function handles all initialization steps needed for both API and CLI: |
| 98 | + - Running database migrations |
| 99 | + - Setting up file synchronization |
| 100 | +
|
| 101 | + Args: |
| 102 | + app_config: The Basic Memory project configuration |
| 103 | +
|
| 104 | + Returns: |
| 105 | + Tuple of (sync_service, watch_service, watch_task) if sync is enabled, |
| 106 | + or (None, None, None) if sync is disabled or initialization failed |
| 107 | + """ |
| 108 | + # Initialize database first |
| 109 | + await initialize_database(app_config) |
| 110 | + |
| 111 | + # Initialize file sync services |
| 112 | + return await initialize_file_sync(app_config) |
| 113 | + |
| 114 | + |
| 115 | +def ensure_initialization(app_config: ProjectConfig) -> None: |
| 116 | + """Ensure initialization runs in a synchronous context. |
| 117 | +
|
| 118 | + This is a wrapper for the async initialize_app function that can be |
| 119 | + called from synchronous code like CLI entry points. |
| 120 | +
|
| 121 | + Args: |
| 122 | + app_config: The Basic Memory project configuration |
| 123 | + """ |
| 124 | + try: |
| 125 | + asyncio.run(initialize_database(app_config)) |
| 126 | + except Exception as e: |
| 127 | + logger.error(f"Error during initialization: {e}") |
| 128 | + # Continue execution even if initialization fails |
| 129 | + # The command might still work, or will fail with a |
| 130 | + # more specific error message |
0 commit comments