|
| 1 | +import logging |
| 2 | +from typing import Any, Dict, List, Optional, Type |
| 3 | + |
| 4 | +from jupyter_scheduler.backends import BackendConfig, DescribeBackendResponse |
| 5 | +from jupyter_scheduler.environments import EnvironmentManager |
| 6 | +from jupyter_scheduler.orm import create_tables |
| 7 | +from jupyter_scheduler.pydantic_v1 import BaseModel |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +def import_class(class_path: str) -> Type: |
| 13 | + """Import a class from a fully qualified path like 'module.submodule.ClassName'.""" |
| 14 | + module_path, class_name = class_path.rsplit(".", 1) |
| 15 | + module = __import__(module_path, fromlist=[class_name]) |
| 16 | + return getattr(module, class_name) |
| 17 | + |
| 18 | + |
| 19 | +class BackendInstance(BaseModel): |
| 20 | + """A running backend with its configuration and initialized scheduler.""" |
| 21 | + |
| 22 | + config: BackendConfig |
| 23 | + scheduler: Any # BaseScheduler at runtime, but Any to support test mocks |
| 24 | + |
| 25 | + |
| 26 | +class BackendRegistry: |
| 27 | + """Registry for storing, initializing, and routing to scheduler backends.""" |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, |
| 31 | + configs: List[BackendConfig], |
| 32 | + legacy_job_backend: str, |
| 33 | + preferred_backends: Optional[Dict[str, str]] = None, |
| 34 | + ): |
| 35 | + self._configs = configs |
| 36 | + self._backends: Dict[str, BackendInstance] = {} |
| 37 | + self._legacy_job_backend = legacy_job_backend |
| 38 | + self._preferred_backends = preferred_backends or {} |
| 39 | + self._extension_map: Dict[str, List[str]] = {} |
| 40 | + |
| 41 | + def initialize( |
| 42 | + self, |
| 43 | + root_dir: str, |
| 44 | + environments_manager: EnvironmentManager, |
| 45 | + db_url: str, |
| 46 | + config: Optional[Any] = None, |
| 47 | + ): |
| 48 | + """Instantiate all backends from configs.""" |
| 49 | + seen_ids = set() |
| 50 | + for cfg in self._configs: |
| 51 | + if cfg.id in seen_ids: |
| 52 | + raise ValueError(f"Duplicate backend ID: '{cfg.id}'") |
| 53 | + if ":" in cfg.id: |
| 54 | + raise ValueError(f"Backend ID cannot contain ':': '{cfg.id}'") |
| 55 | + seen_ids.add(cfg.id) |
| 56 | + |
| 57 | + for cfg in self._configs: |
| 58 | + try: |
| 59 | + instance = self._create_backend(cfg, root_dir, environments_manager, db_url, config) |
| 60 | + self._backends[cfg.id] = instance |
| 61 | + |
| 62 | + for ext in cfg.file_extensions: |
| 63 | + ext_lower = ext.lower().lstrip(".") |
| 64 | + if ext_lower not in self._extension_map: |
| 65 | + self._extension_map[ext_lower] = [] |
| 66 | + self._extension_map[ext_lower].append(cfg.id) |
| 67 | + |
| 68 | + logger.info(f"Initialized backend: {cfg.id} ({cfg.name})") |
| 69 | + except Exception as e: |
| 70 | + logger.error(f"Failed to initialize backend {cfg.id}: {e}") |
| 71 | + raise |
| 72 | + |
| 73 | + def _create_backend( |
| 74 | + self, |
| 75 | + cfg: BackendConfig, |
| 76 | + root_dir: str, |
| 77 | + environments_manager: EnvironmentManager, |
| 78 | + global_db_url: str, |
| 79 | + config: Optional[Any] = None, |
| 80 | + ) -> BackendInstance: |
| 81 | + """Import scheduler class, instantiate it, and return a BackendInstance. |
| 82 | +
|
| 83 | + Creates database tables if not found and backend uses default SQLAlchemy storage. |
| 84 | + """ |
| 85 | + scheduler_class = import_class(cfg.scheduler_class) |
| 86 | + |
| 87 | + backend_db_url = cfg.db_url or global_db_url |
| 88 | + |
| 89 | + # Create SQL tables only if backend uses default SQLAlchemy storage. |
| 90 | + # Backends with custom database_manager_class handle their own storage. |
| 91 | + if backend_db_url and cfg.database_manager_class is None: |
| 92 | + create_tables(backend_db_url) |
| 93 | + |
| 94 | + scheduler = scheduler_class( |
| 95 | + root_dir=root_dir, |
| 96 | + environments_manager=environments_manager, |
| 97 | + db_url=backend_db_url, |
| 98 | + config=config, |
| 99 | + backend_id=cfg.id, |
| 100 | + ) |
| 101 | + |
| 102 | + if cfg.execution_manager_class: |
| 103 | + scheduler.execution_manager_class = import_class(cfg.execution_manager_class) |
| 104 | + |
| 105 | + return BackendInstance(config=cfg, scheduler=scheduler) |
| 106 | + |
| 107 | + def get_backend(self, backend_id: str) -> Optional[BackendInstance]: |
| 108 | + """Return a backend with matching ID, None if none is found.""" |
| 109 | + return self._backends.get(backend_id) |
| 110 | + |
| 111 | + def get_legacy_job_backend(self) -> BackendInstance: |
| 112 | + """Get the backend for routing legacy jobs (UUID-only IDs from pre-3.0). |
| 113 | +
|
| 114 | + Raises: |
| 115 | + KeyError: If the configured legacy_job_backend ID is not found. |
| 116 | + """ |
| 117 | + if self._legacy_job_backend not in self._backends: |
| 118 | + raise KeyError(f"Legacy job backend '{self._legacy_job_backend}' not found in registry") |
| 119 | + return self._backends[self._legacy_job_backend] |
| 120 | + |
| 121 | + def get_for_file(self, input_uri: str) -> BackendInstance: |
| 122 | + """Auto-select backend by file extension. Prefers configured backend, else alphabetical. |
| 123 | +
|
| 124 | + Raises: |
| 125 | + ValueError: If no backend supports the file extension. |
| 126 | + """ |
| 127 | + ext = "" |
| 128 | + if "." in input_uri: |
| 129 | + ext = input_uri.rsplit(".", 1)[-1].lower() |
| 130 | + |
| 131 | + candidate_ids = self._extension_map.get(ext, []) |
| 132 | + if not candidate_ids: |
| 133 | + raise ValueError(f"No backend supports file extension '.{ext}'") |
| 134 | + |
| 135 | + # 1. Check explicit preference for this extension |
| 136 | + preferred_id = self._preferred_backends.get(ext) |
| 137 | + if preferred_id and preferred_id in candidate_ids: |
| 138 | + return self._backends[preferred_id] |
| 139 | + |
| 140 | + # 2. Otherwise return min by name (first alphabetically) |
| 141 | + candidate_instances = [self._backends[bid] for bid in candidate_ids] |
| 142 | + return min(candidate_instances, key=lambda b: b.config.name) |
| 143 | + |
| 144 | + def describe_backends(self) -> List[DescribeBackendResponse]: |
| 145 | + """Return backend descriptions sorted alphabetically by name. Frontend uses first as default.""" |
| 146 | + backends_sorted = sorted(self._backends.values(), key=lambda b: b.config.name) |
| 147 | + return [ |
| 148 | + DescribeBackendResponse( |
| 149 | + id=b.config.id, |
| 150 | + name=b.config.name, |
| 151 | + description=b.config.description, |
| 152 | + file_extensions=b.config.file_extensions, |
| 153 | + output_formats=b.config.output_formats, |
| 154 | + ) |
| 155 | + for b in backends_sorted |
| 156 | + ] |
| 157 | + |
| 158 | + @property |
| 159 | + def backends(self) -> List[BackendInstance]: |
| 160 | + """Return all backend instances.""" |
| 161 | + return list(self._backends.values()) |
| 162 | + |
| 163 | + def __len__(self) -> int: |
| 164 | + return len(self._backends) |
| 165 | + |
| 166 | + def __contains__(self, backend_id: str) -> bool: |
| 167 | + return backend_id in self._backends |
0 commit comments