Skip to content

Commit 85ecf25

Browse files
committed
Preserve construction history across schema evolution
1 parent 44379b0 commit 85ecf25

10 files changed

Lines changed: 1254 additions & 281 deletions
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
"""Historical construction declarations, without application lifecycle resources."""
2+
3+
from __future__ import annotations
4+
5+
from abc import ABC, abstractmethod
6+
from collections.abc import Collection
7+
from dataclasses import dataclass
8+
from typing import Any, TYPE_CHECKING
9+
10+
if TYPE_CHECKING:
11+
from objectstate.object_state import ObjectState
12+
13+
14+
class StateScopeOwner(ABC):
15+
"""A declaration that authoritatively owns independently scoped states."""
16+
17+
__slots__ = ()
18+
19+
@property
20+
@abstractmethod
21+
def owned_scope_ids(self) -> tuple[str, ...]:
22+
"""Project membership from the declaration's existing canonical fields."""
23+
24+
def validate_scope_membership(
25+
self, scope: str | None, available: Collection[str]
26+
) -> None:
27+
owned = self.owned_scope_ids
28+
if len(set(owned)) != len(owned):
29+
raise ValueError(
30+
f"ObjectState owner {scope!r} declares duplicate scope membership."
31+
)
32+
for child in owned:
33+
if child not in available:
34+
raise ValueError(
35+
f"ObjectState owner {scope!r} declares missing ObjectState scope {child!r}."
36+
)
37+
38+
39+
@dataclass(frozen=True)
40+
class StateConstructionBinding(ABC):
41+
"""The actual extraction owner and independently scoped parent of a state."""
42+
43+
state_type: type[ObjectState]
44+
target: Any
45+
parent_scope: str | None
46+
exclusions: tuple[str, ...]
47+
parent_field: str | None
48+
49+
@abstractmethod
50+
def validate_lifecycle(self, state: ObjectState | None, scope: str) -> None:
51+
"""Validate application ownership before any registry mutation."""
52+
53+
@abstractmethod
54+
def attach(self, state: ObjectState) -> None:
55+
"""Install the extraction owner, retaining application lifecycle resources."""
56+
57+
def prepare(
58+
self, scope: str, state: ObjectState | None, parent: ObjectState | None
59+
) -> ObjectState:
60+
"""Extract a complete replacement schema outside the active registry."""
61+
62+
self.validate_lifecycle(state, scope)
63+
prepared = self.state_type(
64+
object_instance=self.target,
65+
scope_id=scope,
66+
parent_state=parent,
67+
exclude_params=list(self.exclusions),
68+
)
69+
prepared._parent_field_name = self.parent_field
70+
return prepared
71+
72+
def validate_scope_membership(
73+
self, prepared: ObjectState, available: Collection[str]
74+
) -> None:
75+
"""Validate the prepared raw declaration, not its saved backing target."""
76+
77+
if isinstance(self.target, StateScopeOwner):
78+
owner = prepared.to_object(sync_delegate=False)
79+
if not isinstance(owner, StateScopeOwner):
80+
raise ValueError(
81+
f"Historical scope owner changed role at {prepared.scope_id!r}."
82+
)
83+
owner.validate_scope_membership(prepared.scope_id, available)
84+
85+
86+
@dataclass(frozen=True)
87+
class DirectStateBinding(StateConstructionBinding):
88+
"""A declaration whose ObjectState can be constructed independently."""
89+
90+
def validate_lifecycle(self, state: ObjectState | None, scope: str) -> None:
91+
if state is not None and (
92+
type(state) is not self.state_type or state.has_delegate
93+
):
94+
raise ValueError(f"Incompatible direct ObjectState lifecycle at {scope!r}.")
95+
96+
def attach(self, state: ObjectState) -> None:
97+
state.object_instance = self.target
98+
state._extraction_target = self.target
99+
state._delegate_attr = None
100+
101+
102+
@dataclass(frozen=True)
103+
class DelegatedStateBinding(StateConstructionBinding):
104+
"""An editable declaration owned by an already-live application wrapper."""
105+
106+
lifecycle_type: type
107+
delegate_attribute: str
108+
109+
def validate_lifecycle(self, state: ObjectState | None, scope: str) -> None:
110+
if (
111+
state is None
112+
or type(state) is not self.state_type
113+
or type(state.object_instance) is not self.lifecycle_type
114+
or state._delegate_attr != self.delegate_attribute
115+
):
116+
raise ValueError(
117+
f"Missing or incompatible delegated lifecycle at {scope!r}."
118+
)
119+
120+
def attach(self, state: ObjectState) -> None:
121+
setattr(state.object_instance, self.delegate_attribute, self.target)
122+
state._extraction_target = self.target
123+
state._delegate_attr = self.delegate_attribute

‎src/objectstate/global_config.py‎

Lines changed: 58 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
"""
1414

1515
import threading
16+
from dataclasses import dataclass
1617
from typing import Dict, Type, Optional, Any
1718

18-
1919
# Dual thread-local storage: saved (for descendants/compiler) and live (for UI editing)
2020
_saved_global_config_contexts: Dict[Type, threading.local] = {}
2121
_live_global_config_contexts: Dict[Type, threading.local] = {}
@@ -33,6 +33,52 @@ def _validate_global_config_value(config_type: Type, config_instance: Any) -> No
3333
)
3434

3535

36+
def _assign_global_config_value(
37+
contexts: Dict[Type, threading.local], config_type: Type, value: Any
38+
) -> None:
39+
"""One storage boundary for installing or unsetting a context projection."""
40+
41+
if value is None:
42+
local = contexts.get(config_type)
43+
if local is not None and hasattr(local, "value"):
44+
del local.value
45+
return
46+
_validate_global_config_value(config_type, value)
47+
if config_type not in contexts:
48+
contexts[config_type] = threading.local()
49+
contexts[config_type].value = value
50+
51+
52+
@dataclass(frozen=True)
53+
class GlobalContextValues:
54+
"""Prepared saved/live projections, or exact local rollback context values."""
55+
56+
config_type: Type
57+
saved: Any
58+
live: Any
59+
60+
@classmethod
61+
def capture(cls, config_type: Type) -> "GlobalContextValues":
62+
return cls(
63+
config_type,
64+
get_saved_global_config(config_type),
65+
get_live_global_config(config_type),
66+
)
67+
68+
def validate(self) -> None:
69+
for value in (self.saved, self.live):
70+
if value is not None:
71+
_validate_global_config_value(self.config_type, value)
72+
73+
def apply(self) -> None:
74+
_assign_global_config_value(
75+
_saved_global_config_contexts, self.config_type, self.saved
76+
)
77+
_assign_global_config_value(
78+
_live_global_config_contexts, self.config_type, self.live
79+
)
80+
81+
3682
def set_saved_global_config(config_type: Type, config_instance: Any) -> None:
3783
"""Set SAVED global config (what descendants/compiler see).
3884
@@ -46,9 +92,9 @@ def set_saved_global_config(config_type: Type, config_instance: Any) -> None:
4692
config_instance: The SAVED config instance
4793
"""
4894
_validate_global_config_value(config_type, config_instance)
49-
if config_type not in _saved_global_config_contexts:
50-
_saved_global_config_contexts[config_type] = threading.local()
51-
_saved_global_config_contexts[config_type].value = config_instance
95+
_assign_global_config_value(
96+
_saved_global_config_contexts, config_type, config_instance
97+
)
5298

5399

54100
def set_live_global_config(config_type: Type, config_instance: Any) -> None:
@@ -63,9 +109,9 @@ def set_live_global_config(config_type: Type, config_instance: Any) -> None:
63109
config_instance: The LIVE (unsaved) config instance
64110
"""
65111
_validate_global_config_value(config_type, config_instance)
66-
if config_type not in _live_global_config_contexts:
67-
_live_global_config_contexts[config_type] = threading.local()
68-
_live_global_config_contexts[config_type].value = config_instance
112+
_assign_global_config_value(
113+
_live_global_config_contexts, config_type, config_instance
114+
)
69115

70116

71117
def get_saved_global_config(config_type: Type) -> Optional[Any]:
@@ -78,7 +124,7 @@ def get_saved_global_config(config_type: Type) -> Optional[Any]:
78124
Saved config instance or None
79125
"""
80126
context = _saved_global_config_contexts.get(config_type)
81-
return getattr(context, 'value', None) if context else None
127+
return getattr(context, "value", None) if context else None
82128

83129

84130
def get_live_global_config(config_type: Type) -> Optional[Any]:
@@ -91,7 +137,7 @@ def get_live_global_config(config_type: Type) -> Optional[Any]:
91137
Live config instance or None
92138
"""
93139
context = _live_global_config_contexts.get(config_type)
94-
return getattr(context, 'value', None) if context else None
140+
return getattr(context, "value", None) if context else None
95141

96142

97143
def set_global_config_for_editing(config_type: Type, config_instance: Any) -> None:
@@ -109,7 +155,9 @@ def set_global_config_for_editing(config_type: Type, config_instance: Any) -> No
109155
set_live_global_config(config_type, config_instance)
110156

111157

112-
def get_current_global_config(config_type: Type, use_live: bool = True) -> Optional[Any]:
158+
def get_current_global_config(
159+
config_type: Type, use_live: bool = True
160+
) -> Optional[Any]:
113161
"""Get current global config.
114162
115163
Args:
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""Explicit trusted upgrades of complete typed history documents."""
2+
3+
from abc import ABC, abstractmethod
4+
from collections.abc import Mapping
5+
from typing import Any
6+
7+
from objectstate.construction_binding import StateConstructionBinding
8+
9+
10+
class HistoryMigration(ABC):
11+
"""An application-owned proof of historical construction declarations."""
12+
13+
@abstractmethod
14+
def migrate(
15+
self,
16+
document: dict[str, Any],
17+
constructions: Mapping[str, StateConstructionBinding],
18+
) -> dict[str, Any]:
19+
"""Return version 2 or reject; current bindings alone are not history proof."""

0 commit comments

Comments
 (0)