File size: 6,045 Bytes
da906bd
 
 
 
 
 
 
 
 
 
 
eeb144a
 
da906bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262c3c2
da906bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Application startup ordering and cancellation-owned resource shutdown."""
import asyncio
from collections import OrderedDict
from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Any, Literal, Protocol

import aiohttp

from backend.reader.document.application.ranges import RangeFlightState
from backend.reader.document.domain.range_cache import RangeCacheState
from backend.search.infrastructure.executor import SearchExecutor


class LifecycleState(RangeCacheState, RangeFlightState, Protocol):
    search_executor: SearchExecutor
    http_session: aiohttp.ClientSession
    upstream_semaphore: asyncio.Semaphore
    reader_index_build_task: asyncio.Task[None] | None
    reader_index_warm_task: asyncio.Task[None] | None
    reader_assets_lock: asyncio.Lock
    reader_assets_task: asyncio.Task[None] | None
    download_warm_enabled: bool
    download_warm_task: asyncio.Task[None] | None
    download_warm_at: float


@dataclass(frozen=True)
class LifecycleDependencies:
    # Hooks resolve the composition root's current implementations when called.
    load_data: Callable[[], None]
    create_executor: Callable[[], SearchExecutor]
    create_http_session: Callable[[], aiohttp.ClientSession]
    initialize_bucket: Callable[[], None]
    mark_user_activity: Callable[[], None]
    warm_reader_indexes: Callable[[], Coroutine[Any, Any, None]]
    shutdown_bucket: Callable[[], Awaitable[None]]
    shutdown_ranges: Callable[[], Awaitable[None]]


TaskName = Literal["reader_index_warm_task", "reader_index_build_task",
                   "reader_assets_task", "download_warm_task"]


@asynccontextmanager
async def lifespan(state: Callable[[], LifecycleState],
                   deps: LifecycleDependencies) -> AsyncGenerator[None, None]:
    deps.load_data()
    state().search_executor = deps.create_executor()
    state().reader_index_build_task = None
    state().reader_index_warm_task = None
    state().http_session = deps.create_http_session()
    state().upstream_semaphore = asyncio.Semaphore(8)
    state().download_warm_enabled = True
    state().download_warm_task = None
    state().download_warm_at = float("-inf")
    state().reader_assets_lock = asyncio.Lock()
    state().reader_assets_task = None
    deps.initialize_bucket()
    state().reader_range_cache = OrderedDict()
    state().reader_range_cache_bytes = 0
    state().reader_range_flights = {}
    state().reader_range_flight_owners = set()
    deps.mark_user_activity()
    state().reader_index_warm_task = asyncio.create_task(deps.warm_reader_indexes())
    # Preserve the startup boundary: only a fully started lifespan owns cleanup.
    body_error: BaseException | None = None
    try:
        yield
    except BaseException as exc:
        body_error = exc
    finally:
        errors: list[BaseException] = []

        async def attempt(action: Callable[[], Awaitable[None]]) -> bool:
            try:
                await action()
                return True
            except BaseException as exc:
                errors.append(exc)
                return False

        async def stop_task(name: TaskName) -> None:
            task: asyncio.Task[None] | None = getattr(state(), name)
            if task is not None:
                task.cancel()
                result = (await asyncio.gather(task, return_exceptions=True))[0]
                setattr(state(), name, None)
                if isinstance(result, BaseException) and not isinstance(result, asyncio.CancelledError):
                    errors.append(result)

        async def cleanup_resources() -> None:
            state().download_warm_enabled = False
            warm_stopped = await attempt(lambda: stop_task("reader_index_warm_task"))
            build_stopped = await attempt(lambda: stop_task("reader_index_build_task"))
            executor_closed = await attempt(state().search_executor.close)
            if executor_closed:
                del state().search_executor
            assets_stopped = await attempt(lambda: stop_task("reader_assets_task"))
            download_stopped = await attempt(lambda: stop_task("download_warm_task"))
            # Failure to drain a producer is not proof that its resources are free.
            if not all((warm_stopped, build_stopped, executor_closed, assets_stopped, download_stopped)):
                return
            bucket_closed = await attempt(deps.shutdown_bucket)
            ranges_closed = await attempt(deps.shutdown_ranges)
            if bucket_closed and ranges_closed:
                state().reader_range_cache.clear()
                state().reader_range_cache_bytes = 0
                await attempt(state().http_session.close)

        # Own the entire sequence, including later Reader/session awaits.
        cleanup = asyncio.create_task(cleanup_resources())
        cancelled: asyncio.CancelledError | None = None
        while not cleanup.done():
            try:
                await asyncio.shield(cleanup)
            except asyncio.CancelledError as exc:
                if cancelled is None:
                    cancelled = exc
            except BaseException:
                break
        try:
            cleanup.result()
        except BaseException as exc:
            errors.append(exc)
        failure = (errors[0] if len(errors) == 1 else
                   BaseExceptionGroup("Lifespan cleanup errors", errors) if errors else None)
        if body_error is not None or cancelled is not None:
            if failure is not None:
                asyncio.get_running_loop().call_exception_handler({
                    "message": "Lifespan resource close failed while handling an exception",
                    "exception": failure,
                    "task": cleanup,
                })
        if body_error is not None:
            raise body_error
        if cancelled is not None:
            raise cancelled
        if failure is not None:
            raise failure