"""Process-wide services, built once at startup.
The API and the worker both create a :class:`Services` object and pass it
where needed, instead of using module-level globals. Tests build one with
fakes.
"""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
from s365b.core.config import Settings
from s365b.core.secrets import SecretBox, load_master_key
from s365b.db.models import AppPurpose, AppRegistration, RepositoryConfig, Tenant
from s365b.db.session import Database
from s365b.graph.auth import CertificateCredential, TokenProvider
from s365b.graph.client import GraphClient
from s365b.modules.registry import ModuleRegistry
from s365b.storage.backends import FilesystemBackend, StorageBackend
from s365b.storage.repository import Repository
[docs]
def app_key_context(app: AppRegistration) -> str:
"""Associated-data string for an app registration's encrypted private key.
Args:
app: The app registration row.
Returns:
Context string passed to :class:`SecretBox`.
"""
return f"app_registration:{app.id}:private_key"
[docs]
def repo_passphrase_context(repo: RepositoryConfig) -> str:
"""Associated-data string for a repository's encrypted passphrase.
Args:
repo: The repository row.
Returns:
Context string passed to :class:`SecretBox`.
"""
return f"repository:{repo.repo_id}:passphrase"
[docs]
GraphFactory = Callable[[Tenant, AppRegistration], GraphClient]
@dataclass
[docs]
class Services:
"""Shared services for one process.
Attributes:
settings: Process settings.
db: Database access.
registry: Allowed modules.
secrets: Encrypts/decrypts secrets stored in the database.
graph_factory: Builds a Graph client for an app registration;
replaced in tests.
msal_app_factory: MSAL app class for Entra sign-in; replaced in tests.
device_code_factory: Builds the setup wizard's device code client
from a public client ID; replaced in tests.
credential_factory: Builds the app-only token provider for an app
registration; replaced in tests.
"""
[docs]
registry: ModuleRegistry
[docs]
graph_factory: GraphFactory | None = None
[docs]
msal_app_factory: Any = None
[docs]
device_code_factory: Callable[[str], Any] | None = None
[docs]
credential_factory: Callable[[Tenant, AppRegistration], TokenProvider] | None = None
[docs]
enqueue_factory: Callable[[int, str], Awaitable[None]] | None = None
[docs]
retention_factory: Callable[[int, str], Awaitable[None]] | None = None
[docs]
restore_factory: Callable[[int], Awaitable[None]] | None = None
[docs]
notifier_factory: Callable[[str], Any] | None = None
_repos: dict[int, Repository] = field(default_factory=dict)
_queue: Any = None
@classmethod
[docs]
def from_settings(cls, settings: Settings) -> Services:
"""Build the real services from settings.
Args:
settings: Process settings.
Returns:
The services.
"""
return cls(
settings=settings,
db=Database(settings),
registry=ModuleRegistry.from_entry_points(settings.modules),
secrets=SecretBox(load_master_key(settings.master_key_file)),
)
[docs]
def graph_for(self, tenant: Tenant, app: AppRegistration) -> GraphClient:
"""Return a Graph client authenticated as an app registration.
Args:
tenant: The tenant.
app: The Backup, Restore or Notifications app.
Returns:
A new Graph client; close it with ``aclose()``.
"""
if self.graph_factory is not None:
return self.graph_factory(tenant, app)
# Several objects are backed up at once (e.g. 4 mailboxes with 4
# requests each); modules limit their own per-object concurrency.
return GraphClient(self.credential_for(tenant, app), max_concurrency=16)
[docs]
async def enqueue_backup(self, job_id: int, requested_by: str) -> None:
"""Queue a backup job for the worker.
Uses the same queueing lock as the scheduler, so a job that is
already waiting is not queued twice.
Args:
job_id: Backup job ID.
requested_by: Username shown on the run.
Raises:
procrastinate.exceptions.AlreadyEnqueued: If the job is already
waiting to run.
"""
if self.enqueue_factory is not None:
await self.enqueue_factory(job_id, requested_by)
return
from s365b.jobs.tasks import build_app, run_backup_job
if self._queue is None:
self._queue = await build_app(self.settings).open_async()
await run_backup_job.configure(queueing_lock=f"backup-job-{job_id}").defer_async(
job_id=job_id, requested_by=requested_by
)
[docs]
async def enqueue_retention(self, repository_id: int, requested_by: str) -> None:
"""Queue a retention run for a repository.
Args:
repository_id: Repository row ID.
requested_by: Username shown on the run.
Raises:
procrastinate.exceptions.AlreadyEnqueued: If one is already waiting.
"""
if self.retention_factory is not None:
await self.retention_factory(repository_id, requested_by)
return
from s365b.jobs.tasks import build_app, run_retention
if self._queue is None:
self._queue = await build_app(self.settings).open_async()
await run_retention.configure(queueing_lock=f"retention-{repository_id}").defer_async(
repository_id=repository_id, requested_by=requested_by
)
[docs]
async def enqueue_restore(self, run_id: int) -> None:
"""Hand a queued restore run to a worker.
Args:
run_id: The job run, already recorded as queued.
"""
if self.restore_factory is not None:
await self.restore_factory(run_id)
return
from s365b.jobs.tasks import build_app, run_restore
if self._queue is None:
self._queue = await build_app(self.settings).open_async()
await run_restore.defer_async(run_id=run_id)
[docs]
async def aclose(self) -> None:
"""Close the job queue connection and the database pool."""
if self._queue is not None:
await self._queue.close_async()
self._queue = None
await self.db.dispose()
[docs]
def credential_for(self, tenant: Tenant, app: AppRegistration) -> TokenProvider:
"""Return the app-only token provider (certificate credential) for an app.
Args:
tenant: The tenant.
app: The app registration.
Returns:
A token provider.
"""
if self.credential_factory is not None:
return self.credential_factory(tenant, app)
key_pem = self.secrets.decrypt(app.private_key_enc, app_key_context(app)).decode()
return CertificateCredential(tenant.tenant_id, app.client_id, key_pem, app.certificate_pem)
[docs]
def backend_for(self, repo: RepositoryConfig) -> StorageBackend:
"""Return the storage backend of a repository.
Args:
repo: The repository row.
Returns:
The backend.
Raises:
ValueError: For backends not implemented yet.
"""
if repo.backend == "filesystem":
from pathlib import Path
return FilesystemBackend(Path(repo.location))
raise ValueError(f"storage backend {repo.backend!r} is not supported yet")
[docs]
async def open_repository(self, repo: RepositoryConfig) -> Repository:
"""Open (or reuse) a repository, refreshing its index.
Args:
repo: The repository row.
Returns:
The open repository.
"""
cached = self._repos.get(repo.id)
if cached is not None:
await cached.reload_index()
return cached
passphrase = self.secrets.decrypt(
repo.passphrase_enc, repo_passphrase_context(repo)
).decode()
opened = await Repository.open(self.backend_for(repo), passphrase)
self._repos[repo.id] = opened
return opened
__all__ = ["AppPurpose", "GraphFactory", "Services", "app_key_context", "repo_passphrase_context"]