File size: 4,190 Bytes
584697d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60df0e0
584697d
 
 
 
 
 
 
 
 
 
60df0e0
 
 
 
 
584697d
 
60df0e0
 
584697d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Revision-bound joins and packed pools over published Reader indexes."""
from __future__ import annotations

from array import array
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass
from typing import TypedDict, cast

JsonObject = dict[str, object]
CacheKey = tuple[int, str, str]
ReaderPool = tuple[Sequence[int], dict[int, JsonObject]]


class ReaderJoinCache(TypedDict):
    all: dict[int, JsonObject]
    repos: dict[str, dict[int, JsonObject]]


@dataclass(frozen=True)
class PoolState:
    """Borrow published collections; never copy corpus records or packed IDs."""

    identity: CacheKey
    records: list[JsonObject]
    indices: Sequence[int]
    repos: dict[str, Sequence[int]]
    keys: dict[str, int]
    join_key: CacheKey | None
    join: ReaderJoinCache
    pool_key: CacheKey | None
    pools: dict[str | None, array[int]]


@dataclass(frozen=True)
class PoolDependencies:
    state: Callable[[], PoolState]
    indexes_ready: Callable[[], bool]
    asset_snapshot: Callable[[], JsonObject]
    assets: Callable[[], Awaitable[JsonObject]]
    ensure_indexes: Callable[[], None]
    ensure_indexes_async: Callable[[], Awaitable[None]]
    cold_dependencies: Callable[[], Awaitable[JsonObject]]
    publish_join: Callable[[CacheKey, ReaderJoinCache], None]
    publish_pools: Callable[[CacheKey, dict[str | None, array[int]]], None]
    asset_eligible: Callable[[JsonObject, JsonObject], bool]
    converted: Callable[[JsonObject, str | None], dict[int, JsonObject]]


def converted_reader_indices(assets: JsonObject, full_repo: str | None,
                             deps: PoolDependencies) -> dict[int, JsonObject]:
    deps.ensure_indexes()
    state = deps.state()
    cache: ReaderJoinCache = state.join
    if state.join_key != state.identity:
        converted: dict[int, JsonObject] = {}
        for key, entry in cast(JsonObject, assets.get("f", {})).items():
            if not isinstance(entry, dict):
                continue
            asset = cast(JsonObject, entry)
            if asset.get("s") != 2:
                continue
            index = state.keys.get(key)
            if index is not None and deps.asset_eligible(state.records[index], asset):
                converted[index] = asset
        by_repo: dict[str, dict[int, JsonObject]] = {}
        for index, asset in converted.items():
            repo = cast(str, state.records[index].get("Repo", ""))
            by_repo.setdefault(repo, {})[index] = asset
        cache = {"all": converted, "repos": by_repo}
        deps.publish_join(state.identity, cache)
    if full_repo:
        return cache["repos"].get(full_repo, {})
    return cache["all"]


async def get_reader_pool(repo: str | None, deps: PoolDependencies) -> ReaderPool:
    # Keep refresh ownership and wait timing in the existing asset/index hooks.
    # Cold owners overlap; an existing snapshot waits for indexes before assets.
    if deps.indexes_ready():
        assets = await deps.assets()
    elif deps.asset_snapshot().get("f"):
        await deps.ensure_indexes_async()
        assets = await deps.assets()
    else:
        assets = await deps.cold_dependencies()
        # Another refresh can publish while the cold index build is in flight.
        if assets is not deps.asset_snapshot():
            assets = deps.asset_snapshot()
    full_repo = f"VoiceOfML/{repo}" if repo else None
    state = deps.state()
    original = state.repos.get(full_repo, []) if full_repo else state.indices
    converted = deps.converted(assets, full_repo)
    # The synchronous ensure/converted hook can publish a new generation too.
    state = deps.state()
    pools: dict[str | None, array[int]] = state.pools
    if state.pool_key != state.identity:
        pools = {}
        deps.publish_pools(state.identity, pools)
    if full_repo in pools:
        return pools[full_repo], converted
    if not original and not converted:
        # Do not retain arbitrary unknown repository names.
        return (), converted
    pool = dict.fromkeys(original)
    pool.update(dict.fromkeys(converted))
    result = array('I', pool)
    pools[full_repo] = result
    return result, converted