File size: 7,247 Bytes
9f6a4bd
e99df76
691dc7c
abe1c43
2e7b8ca
8e438ab
abe1c43
f7872b8
abe1c43
 
8e438ab
abe1c43
 
 
 
8e438ab
 
 
 
 
 
 
 
 
 
 
f7872b8
8e438ab
abe1c43
8e438ab
abe1c43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e438ab
 
 
abe1c43
8e438ab
 
f7872b8
 
8e438ab
 
 
 
 
 
 
 
 
 
 
2e7b8ca
8e438ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abe1c43
 
f7872b8
 
 
 
 
8e438ab
f7872b8
 
 
 
 
 
 
 
 
8e438ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abe1c43
 
 
 
8e438ab
abe1c43
 
 
8e438ab
 
abe1c43
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
abe1c43
691dc7c
abe1c43
 
 
 
 
 
 
 
 
 
f7872b8
 
 
 
 
 
abe1c43
 
 
 
8e438ab
 
 
abe1c43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
from __future__ import annotations
"""Canonical managed-config loading, precedence, provenance, and caching."""

import os
from collections.abc import Generator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from enum import StrEnum
from functools import lru_cache
from pathlib import Path
from types import MappingProxyType

from free_claude_code.core.interprocess_lock import InterprocessFileLock

from .env_files import (
    ANTHROPIC_AUTH_TOKEN_ENV,
    FCC_CONFIG_SCHEMA_ENV,
    dotenv_values_from_file,
)
from .env_migrations import (
    CONFIG_SCHEMA_VERSION,
    atomic_write_managed_config,
    consolidate_managed_config,
    settings_env_keys,
)
from .errors import ConfigConflictError
from .model_refs import normalize_retired_model_settings
from .paths import config_lock_path, managed_env_path
from .provider_proxies import invalid_provider_proxy_keys
from .settings import Settings


class ConfigSource(StrEnum):
    """Live owner of one effective setting value."""

    DEFAULT = "default"
    MANAGED = "managed_env"
    PROCESS = "process"


@dataclass(frozen=True, slots=True)
class SettingsSnapshot:
    """One validated settings model and its effective field provenance."""

    settings: Settings
    sources: Mapping[str, ConfigSource]


@dataclass(frozen=True, slots=True)
class ManagedConfigSnapshot:
    """One disk/environment capture and its validated effective settings."""

    settings: Settings
    sources: Mapping[str, ConfigSource]
    managed: Mapping[str, str] = dataclass_field(repr=False)
    process: Mapping[str, str] = dataclass_field(repr=False)
    path: Path


class ManagedConfigStore:
    """Own initialization and coordinate fresh reads with atomic writes."""

    def __init__(self) -> None:
        self.path = managed_env_path()
        self._lock_path = config_lock_path()

    @contextmanager
    def _storage_lock(self) -> Generator[None]:
        lock = InterprocessFileLock(self._lock_path)
        if not lock.acquire(wait=True, timeout=10.0):
            raise TimeoutError(
                f"Could not acquire managed-config lock: {self._lock_path}"
            )
        try:
            yield
        finally:
            lock.release()

    def initialize(self, env: Mapping[str, str] | None = None) -> None:
        with self._storage_lock():
            consolidate_managed_config(dict(os.environ if env is None else env))

    def _read_managed(self) -> dict[str, str]:
        if not self.path.is_file():
            raise ValueError(
                "Managed configuration is missing; initialize it before reading."
            )
        managed = dotenv_values_from_file(self.path)
        schema = managed.get(FCC_CONFIG_SCHEMA_ENV)
        if schema != CONFIG_SCHEMA_VERSION:
            raise ValueError(
                f"Managed config {self.path} uses unsupported schema {schema!r}; "
                f"initialize with a compatible FCC version (supports {CONFIG_SCHEMA_VERSION})."
            )
        return managed

    def read(self, env: Mapping[str, str] | None = None) -> ManagedConfigSnapshot:
        process = dict(os.environ if env is None else env)
        # Windows readers deny replacement while their file handles remain open.
        with self._storage_lock():
            managed = self._read_managed()
        snapshot = compose_settings_snapshot(managed, process)
        return ManagedConfigSnapshot(
            snapshot.settings,
            snapshot.sources,
            MappingProxyType(managed),
            MappingProxyType(process),
            self.path,
        )

    def commit(
        self,
        values: Mapping[str, str],
        expected: ManagedConfigSnapshot | None = None,
    ) -> None:
        with self._storage_lock():
            managed = self._read_managed()
            if expected is not None and (
                managed != expected.managed
                or _process_overrides(os.environ)
                != _process_overrides(expected.process)
            ):
                raise ConfigConflictError(
                    "Configuration changed while saving. Reopen the modal before saving again."
                )
            atomic_write_managed_config(values, path=self.path)

    def repair_invalid_provider_proxies(
        self,
        env: Mapping[str, str] | None = None,
    ) -> tuple[str, ...]:
        process = dict(os.environ if env is None else env)
        if not self.path.is_file():
            return ()
        with self._storage_lock():
            if not self.path.is_file():
                return ()
            managed = self._read_managed()
            removed = tuple(
                key
                for key in invalid_provider_proxy_keys(managed)
                if key not in process
            )
            if removed:
                for key in removed:
                    managed.pop(key)
                atomic_write_managed_config(managed, path=self.path)
            return removed


def compose_settings_snapshot(
    managed: Mapping[str, str],
    env: Mapping[str, str],
) -> SettingsSnapshot:
    """Validate prospective managed values with live process precedence."""

    process = normalize_retired_model_settings(env, preserve_empty_overrides=True)
    managed = normalize_retired_model_settings(managed, preserve_empty_overrides=False)
    aliases = _settings_aliases()
    recognized = settings_env_keys()
    values: dict[str, str] = {
        key: value for key, value in managed.items() if key in recognized
    }
    sources = dict.fromkeys(Settings.model_fields, ConfigSource.DEFAULT)
    for key in values:
        if name := aliases.get(key):
            sources[name] = ConfigSource.MANAGED

    for key in recognized:
        if key not in process:
            continue
        # Servers and independently opened clients share the managed token/default.
        if key == ANTHROPIC_AUTH_TOKEN_ENV:
            continue
        values[key] = process[key]
        if name := aliases.get(key):
            sources[name] = ConfigSource.PROCESS

    settings = Settings.model_validate(values)
    return SettingsSnapshot(
        settings=settings,
        sources=MappingProxyType(sources),
    )


def _process_overrides(env: Mapping[str, str]) -> dict[str, str]:
    normalized = normalize_retired_model_settings(env, preserve_empty_overrides=True)
    keys = settings_env_keys() - {ANTHROPIC_AUTH_TOKEN_ENV}
    return {key: normalized[key] for key in keys & normalized.keys()}


@lru_cache
def get_settings() -> Settings:
    """Return the process-wide cached settings model."""

    store = ManagedConfigStore()
    store.initialize()
    return store.read().settings


def clear_settings_cache() -> None:
    """Discard the runtime Settings cache after a committed configuration change."""

    get_settings.cache_clear()


def _settings_aliases() -> dict[str, str]:
    aliases: dict[str, str] = {}
    for name, field in Settings.model_fields.items():
        alias = field.validation_alias
        if not isinstance(alias, str):
            raise AssertionError(f"Settings field {name!r} needs one string alias")
        aliases[alias] = name
    return aliases