refresh-engine 1.1.0__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/PKG-INFO +10 -7
  2. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/README.md +9 -5
  3. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/pyproject.toml +11 -11
  4. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/pyproject.toml.orig +167 -167
  5. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/__init__.py +2 -1
  6. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/engine.py +201 -260
  7. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/models.py +1 -0
  8. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/otel.py +3 -3
  9. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/scheduling.py +2 -2
  10. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/testing.py +3 -3
  11. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/LICENSE +0 -0
  12. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/__init__.py +0 -0
  13. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/concurrency.py +0 -0
  14. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/context.py +0 -0
  15. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/coordinator.py +0 -0
  16. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/execution.py +0 -0
  17. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/observation.py +0 -0
  18. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/pipeline.py +0 -0
  19. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/planning.py +0 -0
  20. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/redaction.py +0 -0
  21. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/reentrancy.py +0 -0
  22. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/states.py +0 -0
  23. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/_internal/values.py +0 -0
  24. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/contracts.py +0 -0
  25. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/errors.py +0 -0
  26. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/events.py +0 -0
  27. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/fingerprints.py +0 -0
  28. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/observability.py +0 -0
  29. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/py.typed +0 -0
  30. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/selectors.py +0 -0
  31. {refresh_engine-1.1.0 → refresh_engine-2.0.0}/src/refresh_engine/stores.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: refresh-engine
3
- Version: 1.1.0
3
+ Version: 2.0.0
4
4
  Summary: Asyncio-first, domain-neutral change detection and dependency-aware refresh orchestration for Python.
5
5
  Keywords: asyncio,change-detection,dependency-graph,fingerprint,incremental,orchestration,refresh,scheduler,synchronization
6
6
  Author: S. Muni Harish
@@ -21,7 +21,6 @@ Classifier: Typing :: Typed
21
21
  Requires-Dist: structlog>=26.1.0
22
22
  Requires-Dist: tenacity>=9.2.1
23
23
  Requires-Dist: opentelemetry-api>=1.45.2,<2 ; extra == 'otel'
24
- Requires-Dist: opentelemetry-sdk>=1.45.2,<2 ; extra == 'otel'
25
24
  Requires-Python: >=3.12
26
25
  Project-URL: Homepage, https://github.com/smuniharish/refresh-engine
27
26
  Project-URL: Documentation, https://refresh-engine.readthedocs.io
@@ -84,7 +83,8 @@ pip install refresh-engine
84
83
  ```
85
84
 
86
85
  For the optional OpenTelemetry integration, install
87
- `refresh-engine[otel]`.
86
+ `refresh-engine[otel]`. The extra adds the OpenTelemetry API; your application
87
+ provides the SDK and exporters.
88
88
 
89
89
  ## Quick start
90
90
 
@@ -99,10 +99,11 @@ from refresh_engine import (
99
99
  DiscoveryResult,
100
100
  PlanAction,
101
101
  RefreshEngine,
102
- ResourceSource,
102
+ RefreshEngineConfig,
103
103
  RefreshRequest,
104
104
  Resource,
105
105
  ResourceSnapshot,
106
+ ResourceSource,
106
107
  )
107
108
 
108
109
  CATALOG = {"apples": 120, "pears": 80}
@@ -133,13 +134,15 @@ async def update_index(
133
134
 
134
135
 
135
136
  async def main() -> None:
136
- async with RefreshEngine(InventorySource(), update_index) as engine:
137
- first = await engine.refresh()
137
+ async with RefreshEngine(
138
+ RefreshEngineConfig(source=InventorySource(), operation=update_index)
139
+ ) as engine:
140
+ first = await engine.refresh(RefreshRequest())
138
141
  print(f"{first.status}: refreshed {first.refreshed_count}", SEARCH_INDEX)
139
142
 
140
143
  CATALOG["pears"] = 75
141
144
  del CATALOG["apples"]
142
- second = await engine.refresh()
145
+ second = await engine.refresh(RefreshRequest())
143
146
  print(
144
147
  f"{second.status}: modified {second.modified_count},"
145
148
  f" deleted {second.deleted_count}",
@@ -51,7 +51,8 @@ pip install refresh-engine
51
51
  ```
52
52
 
53
53
  For the optional OpenTelemetry integration, install
54
- `refresh-engine[otel]`.
54
+ `refresh-engine[otel]`. The extra adds the OpenTelemetry API; your application
55
+ provides the SDK and exporters.
55
56
 
56
57
  ## Quick start
57
58
 
@@ -66,10 +67,11 @@ from refresh_engine import (
66
67
  DiscoveryResult,
67
68
  PlanAction,
68
69
  RefreshEngine,
69
- ResourceSource,
70
+ RefreshEngineConfig,
70
71
  RefreshRequest,
71
72
  Resource,
72
73
  ResourceSnapshot,
74
+ ResourceSource,
73
75
  )
74
76
 
75
77
  CATALOG = {"apples": 120, "pears": 80}
@@ -100,13 +102,15 @@ async def update_index(
100
102
 
101
103
 
102
104
  async def main() -> None:
103
- async with RefreshEngine(InventorySource(), update_index) as engine:
104
- first = await engine.refresh()
105
+ async with RefreshEngine(
106
+ RefreshEngineConfig(source=InventorySource(), operation=update_index)
107
+ ) as engine:
108
+ first = await engine.refresh(RefreshRequest())
105
109
  print(f"{first.status}: refreshed {first.refreshed_count}", SEARCH_INDEX)
106
110
 
107
111
  CATALOG["pears"] = 75
108
112
  del CATALOG["apples"]
109
- second = await engine.refresh()
113
+ second = await engine.refresh(RefreshRequest())
110
114
  print(
111
115
  f"{second.status}: modified {second.modified_count},"
112
116
  f" deleted {second.deleted_count}",
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["uv_build>=0.13.9,<0.14"]
2
+ requires = ["uv_build>=0.13.10,<0.14"]
3
3
  build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "refresh-engine"
7
- version = "1.1.0"
7
+ version = "2.0.0"
8
8
  description = "Asyncio-first, domain-neutral change detection and dependency-aware refresh orchestration for Python."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -44,10 +44,7 @@ dependencies = [
44
44
  name = "S. Muni Harish"
45
45
 
46
46
  [project.optional-dependencies]
47
- otel = [
48
- "opentelemetry-api>=1.45.2,<2",
49
- "opentelemetry-sdk>=1.45.2,<2",
50
- ]
47
+ otel = ["opentelemetry-api>=1.45.2,<2"]
51
48
 
52
49
  [project.urls]
53
50
  Homepage = "https://github.com/smuniharish/refresh-engine"
@@ -58,8 +55,8 @@ Changelog = "https://refresh-engine.readthedocs.io/en/latest/changelog/"
58
55
 
59
56
  [dependency-groups]
60
57
  test = [
61
- "coverage[toml]>=7.17.5",
62
- "hypothesis>=6.170.17",
58
+ "coverage[toml]>=7.18.0",
59
+ "hypothesis>=6.170.26",
63
60
  "pytest>=9.2.0",
64
61
  "pytest-asyncio>=1.5.0",
65
62
  "pytest-cov>=7.1.0",
@@ -69,9 +66,9 @@ test = [
69
66
  lint = ["ruff>=0.17.6"]
70
67
  types = ["pyrefly>=1.5.0"]
71
68
  docs = [
72
- "griffe-pydantic>=1.3.2,<2",
73
- "mkdocstrings-python>=2.0.11,<3",
74
- "zensical>=0.1.3,<0.2",
69
+ { include-group = "lint" },
70
+ "griffelib>=2.4.1,<3",
71
+ "zensical>=0.1.4,<0.2",
75
72
  ]
76
73
  examples = ["psycopg[binary,pool]>=3.3.9,<4"]
77
74
  package = ["twine>=7.0.0"]
@@ -86,6 +83,9 @@ include-group = "lint"
86
83
  [[dependency-groups.dev]]
87
84
  include-group = "types"
88
85
 
86
+ [[dependency-groups.dev]]
87
+ include-group = "docs"
88
+
89
89
  [tool.uv]
90
90
  default-groups = ["dev"]
91
91
 
@@ -1,167 +1,167 @@
1
- [build-system]
2
- requires = ["uv_build>=0.13.9,<0.14"]
3
- build-backend = "uv_build"
4
-
5
- [project]
6
- name = "refresh-engine"
7
- version = "1.1.0"
8
- description = "Asyncio-first, domain-neutral change detection and dependency-aware refresh orchestration for Python."
9
- readme = "README.md"
10
- requires-python = ">=3.12"
11
- license = "Apache-2.0"
12
- license-files = ["LICENSE"]
13
- authors = [{ name = "S. Muni Harish" }]
14
- keywords = [
15
- "asyncio",
16
- "change-detection",
17
- "dependency-graph",
18
- "fingerprint",
19
- "incremental",
20
- "orchestration",
21
- "refresh",
22
- "scheduler",
23
- "synchronization",
24
- ]
25
- classifiers = [
26
- "Development Status :: 5 - Production/Stable",
27
- "Framework :: AsyncIO",
28
- "Intended Audience :: Developers",
29
- "Operating System :: OS Independent",
30
- "Programming Language :: Python :: 3",
31
- "Programming Language :: Python :: 3 :: Only",
32
- "Programming Language :: Python :: 3.12",
33
- "Programming Language :: Python :: 3.13",
34
- "Programming Language :: Python :: 3.14",
35
- "Programming Language :: Python :: 3.15",
36
- "Topic :: Software Development :: Libraries :: Python Modules",
37
- "Typing :: Typed",
38
- ]
39
- dependencies = [
40
- "structlog>=26.1.0",
41
- "tenacity>=9.2.1",
42
- ]
43
-
44
- [project.optional-dependencies]
45
- otel = [
46
- "opentelemetry-api>=1.45.2,<2",
47
- "opentelemetry-sdk>=1.45.2,<2",
48
- ]
49
-
50
- [project.urls]
51
- Homepage = "https://github.com/smuniharish/refresh-engine"
52
- Documentation = "https://refresh-engine.readthedocs.io"
53
- Repository = "https://github.com/smuniharish/refresh-engine"
54
- Issues = "https://github.com/smuniharish/refresh-engine/issues"
55
- Changelog = "https://refresh-engine.readthedocs.io/en/latest/changelog/"
56
-
57
- [dependency-groups]
58
- test = [
59
- "coverage[toml]>=7.17.5",
60
- "hypothesis>=6.170.17",
61
- "pytest>=9.2.0",
62
- "pytest-asyncio>=1.5.0",
63
- "pytest-cov>=7.1.0",
64
- "pytest-timeout>=2.4.0",
65
- "skills-ref>=0.1.1,<1",
66
- ]
67
- lint = ["ruff>=0.17.6"]
68
- types = ["pyrefly>=1.5.0"]
69
- docs = [
70
- "griffe-pydantic>=1.3.2,<2",
71
- "mkdocstrings-python>=2.0.11,<3",
72
- "zensical>=0.1.3,<0.2",
73
- ]
74
- examples = [
75
- "psycopg[binary,pool]>=3.3.9,<4",
76
- ]
77
- package = ["twine>=7.0.0"]
78
- audit = ["pip-audit>=2.10.1"]
79
- dev = [
80
- { include-group = "test" },
81
- { include-group = "lint" },
82
- { include-group = "types" },
83
- ]
84
-
85
- [tool.uv]
86
- default-groups = ["dev"]
87
-
88
- [tool.pytest]
89
- minversion = "9.0"
90
- addopts = ["-ra", "--strict-markers", "--strict-config"]
91
- testpaths = ["tests"]
92
- xfail_strict = true
93
- filterwarnings = ["error"]
94
- timeout = "120"
95
- asyncio_mode = "auto"
96
- asyncio_default_fixture_loop_scope = "function"
97
- asyncio_default_test_loop_scope = "function"
98
-
99
- [tool.coverage.run]
100
- branch = true
101
- source_pkgs = ["refresh_engine"]
102
-
103
- [tool.coverage.report]
104
- fail_under = 100
105
- show_missing = true
106
- skip_covered = true
107
- exclude_also = [
108
- "if TYPE_CHECKING:",
109
- "^\\s*\\.\\.\\.\\s*$",
110
- ]
111
-
112
- [tool.ruff]
113
- target-version = "py312"
114
- line-length = 88
115
-
116
- [tool.ruff.format]
117
- docstring-code-format = true
118
-
119
- [tool.ruff.lint]
120
- select = [
121
- "ASYNC",
122
- "B",
123
- "C4",
124
- "D",
125
- "E",
126
- "ERA",
127
- "F",
128
- "FURB",
129
- "I",
130
- "N",
131
- "PERF",
132
- "PGH",
133
- "PIE",
134
- "PT",
135
- "RET",
136
- "RUF",
137
- "S",
138
- "SIM",
139
- "T20",
140
- "UP",
141
- "W",
142
- ]
143
-
144
- [tool.ruff.lint.pydocstyle]
145
- convention = "google"
146
-
147
- [tool.ruff.lint.per-file-ignores]
148
- "tests/**" = ["D", "S101", "S311"]
149
- "src/refresh_engine/testing.py" = ["S101"]
150
- "examples/**" = ["D", "S101", "T201"]
151
- "benchmarks/**" = ["D", "S311", "T201"]
152
- "scripts/**" = ["D", "S603", "S607", "T201"]
153
- "refresh-engine-skills/**" = ["T201"]
154
- "tests/skill/**" = ["D", "S101", "T201"]
155
-
156
- [tool.pyrefly]
157
- project-includes = [
158
- "src",
159
- "tests",
160
- "examples",
161
- "scripts",
162
- "benchmarks",
163
- "refresh-engine-skills",
164
- "tests/skill",
165
- ]
166
- search-path = ["src", ".", "examples", "scripts"]
167
- python-version = "3.12"
1
+ [build-system]
2
+ requires = ["uv_build>=0.13.10,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "refresh-engine"
7
+ version = "2.0.0"
8
+ description = "Asyncio-first, domain-neutral change detection and dependency-aware refresh orchestration for Python."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "S. Muni Harish" }]
14
+ keywords = [
15
+ "asyncio",
16
+ "change-detection",
17
+ "dependency-graph",
18
+ "fingerprint",
19
+ "incremental",
20
+ "orchestration",
21
+ "refresh",
22
+ "scheduler",
23
+ "synchronization",
24
+ ]
25
+ classifiers = [
26
+ "Development Status :: 5 - Production/Stable",
27
+ "Framework :: AsyncIO",
28
+ "Intended Audience :: Developers",
29
+ "Operating System :: OS Independent",
30
+ "Programming Language :: Python :: 3",
31
+ "Programming Language :: Python :: 3 :: Only",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Programming Language :: Python :: 3.14",
35
+ "Programming Language :: Python :: 3.15",
36
+ "Topic :: Software Development :: Libraries :: Python Modules",
37
+ "Typing :: Typed",
38
+ ]
39
+ dependencies = [
40
+ "structlog>=26.1.0",
41
+ "tenacity>=9.2.1",
42
+ ]
43
+
44
+ [project.optional-dependencies]
45
+ otel = [
46
+ "opentelemetry-api>=1.45.2,<2",
47
+ ]
48
+
49
+ [project.urls]
50
+ Homepage = "https://github.com/smuniharish/refresh-engine"
51
+ Documentation = "https://refresh-engine.readthedocs.io"
52
+ Repository = "https://github.com/smuniharish/refresh-engine"
53
+ Issues = "https://github.com/smuniharish/refresh-engine/issues"
54
+ Changelog = "https://refresh-engine.readthedocs.io/en/latest/changelog/"
55
+
56
+ [dependency-groups]
57
+ test = [
58
+ "coverage[toml]>=7.18.0",
59
+ "hypothesis>=6.170.26",
60
+ "pytest>=9.2.0",
61
+ "pytest-asyncio>=1.5.0",
62
+ "pytest-cov>=7.1.0",
63
+ "pytest-timeout>=2.4.0",
64
+ "skills-ref>=0.1.1,<1",
65
+ ]
66
+ lint = ["ruff>=0.17.6"]
67
+ types = ["pyrefly>=1.5.0"]
68
+ docs = [
69
+ { include-group = "lint" },
70
+ "griffelib>=2.4.1,<3",
71
+ "zensical>=0.1.4,<0.2",
72
+ ]
73
+ examples = [
74
+ "psycopg[binary,pool]>=3.3.9,<4",
75
+ ]
76
+ package = ["twine>=7.0.0"]
77
+ audit = ["pip-audit>=2.10.1"]
78
+ dev = [
79
+ { include-group = "test" },
80
+ { include-group = "lint" },
81
+ { include-group = "types" },
82
+ { include-group = "docs" },
83
+ ]
84
+
85
+ [tool.uv]
86
+ default-groups = ["dev"]
87
+
88
+ [tool.pytest]
89
+ minversion = "9.0"
90
+ addopts = ["-ra", "--strict-markers", "--strict-config"]
91
+ testpaths = ["tests"]
92
+ xfail_strict = true
93
+ filterwarnings = ["error"]
94
+ timeout = "120"
95
+ asyncio_mode = "auto"
96
+ asyncio_default_fixture_loop_scope = "function"
97
+ asyncio_default_test_loop_scope = "function"
98
+
99
+ [tool.coverage.run]
100
+ branch = true
101
+ source_pkgs = ["refresh_engine"]
102
+
103
+ [tool.coverage.report]
104
+ fail_under = 100
105
+ show_missing = true
106
+ skip_covered = true
107
+ exclude_also = [
108
+ "if TYPE_CHECKING:",
109
+ "^\\s*\\.\\.\\.\\s*$",
110
+ ]
111
+
112
+ [tool.ruff]
113
+ target-version = "py312"
114
+ line-length = 88
115
+
116
+ [tool.ruff.format]
117
+ docstring-code-format = true
118
+
119
+ [tool.ruff.lint]
120
+ select = [
121
+ "ASYNC",
122
+ "B",
123
+ "C4",
124
+ "D",
125
+ "E",
126
+ "ERA",
127
+ "F",
128
+ "FURB",
129
+ "I",
130
+ "N",
131
+ "PERF",
132
+ "PGH",
133
+ "PIE",
134
+ "PT",
135
+ "RET",
136
+ "RUF",
137
+ "S",
138
+ "SIM",
139
+ "T20",
140
+ "UP",
141
+ "W",
142
+ ]
143
+
144
+ [tool.ruff.lint.pydocstyle]
145
+ convention = "google"
146
+
147
+ [tool.ruff.lint.per-file-ignores]
148
+ "tests/**" = ["D", "S101", "S311"]
149
+ "src/refresh_engine/testing.py" = ["S101"]
150
+ "examples/**" = ["D", "S101", "T201"]
151
+ "benchmarks/**" = ["D", "S311", "T201"]
152
+ "scripts/**" = ["D", "S603", "S607", "T201"]
153
+ "refresh-engine-skills/**" = ["T201"]
154
+ "tests/skill/**" = ["D", "S101", "T201"]
155
+
156
+ [tool.pyrefly]
157
+ project-includes = [
158
+ "src",
159
+ "tests",
160
+ "examples",
161
+ "scripts",
162
+ "benchmarks",
163
+ "refresh-engine-skills",
164
+ "tests/skill",
165
+ ]
166
+ search-path = ["src", ".", "examples", "scripts"]
167
+ python-version = "3.12"
@@ -20,7 +20,7 @@ from refresh_engine.contracts import (
20
20
  StateStore,
21
21
  StateTransaction,
22
22
  )
23
- from refresh_engine.engine import RefreshEngine
23
+ from refresh_engine.engine import RefreshEngine, RefreshEngineConfig
24
24
  from refresh_engine.errors import (
25
25
  ConfigurationError,
26
26
  DependencyCycleError,
@@ -117,6 +117,7 @@ __all__ = [
117
117
  "PredicateSelector",
118
118
  "RefreshConfig",
119
119
  "RefreshEngine",
120
+ "RefreshEngineConfig",
120
121
  "RefreshError",
121
122
  "RefreshEvent",
122
123
  "RefreshIssue",
@@ -1,260 +1,201 @@
1
- """The refresh engine."""
2
-
3
- from __future__ import annotations
4
-
5
- from collections.abc import Iterable, Mapping
6
- from inspect import iscoroutinefunction
7
- from types import TracebackType
8
- from typing import Any, Self
9
-
10
- from refresh_engine._internal.coordinator import RefreshCoordinator
11
- from refresh_engine._internal.pipeline import RefreshPipeline
12
- from refresh_engine._internal.reentrancy import awaited_by
13
- from refresh_engine._internal.values import id_set
14
- from refresh_engine.contracts import (
15
- FingerprintStrategy,
16
- RefreshOperation,
17
- RefreshOperationLike,
18
- ResourceSelector,
19
- ResourceSource,
20
- StateStore,
21
- )
22
- from refresh_engine.events import AsyncEventPublisher, EventPublisher
23
- from refresh_engine.fingerprints import CompositeHash
24
- from refresh_engine.models import (
25
- RefreshConfig,
26
- RefreshMode,
27
- RefreshRequest,
28
- RefreshResult,
29
- TriggerSource,
30
- )
31
- from refresh_engine.stores import InMemoryStateStore
32
-
33
- __all__ = ["RefreshEngine"]
34
-
35
-
36
- class RefreshEngine:
37
- """Detect changes in a population of resources and refresh what changed.
38
-
39
- Every refresh loads the previous state, discovers resources, observes them
40
- (reading a snapshot and fingerprinting it, or reusing the previous state when a
41
- reliable cheap indicator is unchanged), classifies changes, plans operations in
42
- dependency order, runs them with bounded concurrency, and commits the state of
43
- each successful resource.
44
-
45
- An engine runs one refresh at a time; concurrent requests are handled by
46
- `config.overlap_policy`. Use the engine from a single event loop and close it
47
- when done, preferably with `async with`.
48
-
49
- The source, operation, fingerprint strategy, and state store of a refresh run
50
- in a copy of the context of the code that requested it, so context variables,
51
- such as tracing spans or bound log fields, reach them. Requests merged by the
52
- overlap policy run in the context of the first request.
53
-
54
- Args:
55
- source: Discovers resources and reads their snapshots.
56
- operation: Applies the refresh or delete side effect of one resource.
57
- fingerprint: Detects content changes; defaults to
58
- [`CompositeHash`][refresh_engine.CompositeHash].
59
- store: Persists resource state; defaults to a new
60
- [`InMemoryStateStore`][refresh_engine.InMemoryStateStore].
61
- config: Execution settings; defaults to
62
- [`RefreshConfig()`][refresh_engine.RefreshConfig].
63
- events: Publisher for lifecycle events; defaults to a new
64
- [`AsyncEventPublisher`][refresh_engine.AsyncEventPublisher].
65
-
66
- Raises:
67
- TypeError: If an argument does not implement its contract.
68
-
69
- Example:
70
- ```python
71
- async with RefreshEngine(source, operation) as engine:
72
- result = await engine.refresh()
73
- print(result.status, result.refreshed_count)
74
- ```
75
- """
76
-
77
- def __init__(
78
- self,
79
- source: ResourceSource,
80
- operation: RefreshOperationLike,
81
- *,
82
- fingerprint: FingerprintStrategy | None = None,
83
- store: StateStore | None = None,
84
- config: RefreshConfig | None = None,
85
- events: EventPublisher | None = None,
86
- ) -> None:
87
- """Create an engine."""
88
- fingerprint = CompositeHash() if fingerprint is None else fingerprint
89
- store = InMemoryStateStore() if store is None else store
90
- config = RefreshConfig() if config is None else config
91
- events = AsyncEventPublisher() if events is None else events
92
- if not isinstance(source, ResourceSource):
93
- raise TypeError("source must subclass ResourceSource")
94
- if not (
95
- isinstance(operation, RefreshOperation)
96
- or (callable(operation) and iscoroutinefunction(operation))
97
- ):
98
- raise TypeError(
99
- "operation must subclass RefreshOperation or be an async function"
100
- )
101
- if not isinstance(fingerprint, FingerprintStrategy):
102
- raise TypeError("fingerprint must subclass FingerprintStrategy")
103
- if not isinstance(store, StateStore):
104
- raise TypeError("store must subclass StateStore")
105
- if not isinstance(config, RefreshConfig):
106
- raise TypeError("config must be a RefreshConfig")
107
- if not isinstance(events, EventPublisher):
108
- raise TypeError("events must be an EventPublisher")
109
- self._source = source
110
- self._operation = operation
111
- self._fingerprint = fingerprint
112
- self._store = store
113
- self._config = config
114
- self._events = events
115
- pipeline = RefreshPipeline(
116
- source, operation, fingerprint, store, config, events
117
- )
118
- self._coordinator = RefreshCoordinator(
119
- pipeline.run, pipeline.finish_unrun, config.overlap_policy
120
- )
121
-
122
- @property
123
- def source(self) -> ResourceSource:
124
- """The resource source."""
125
- return self._source
126
-
127
- @property
128
- def operation(self) -> RefreshOperationLike:
129
- """The refresh operation."""
130
- return self._operation
131
-
132
- @property
133
- def fingerprint(self) -> FingerprintStrategy:
134
- """The fingerprint strategy."""
135
- return self._fingerprint
136
-
137
- @property
138
- def store(self) -> StateStore:
139
- """The state store."""
140
- return self._store
141
-
142
- @property
143
- def config(self) -> RefreshConfig:
144
- """The execution settings."""
145
- return self._config
146
-
147
- @property
148
- def events(self) -> EventPublisher:
149
- """The lifecycle event publisher."""
150
- return self._events
151
-
152
- @property
153
- def closed(self) -> bool:
154
- """Whether the engine rejects new requests."""
155
- return self._coordinator.closed
156
-
157
- async def refresh(
158
- self,
159
- *,
160
- mode: RefreshMode | None = None,
161
- resource_ids: str | Iterable[str] = (),
162
- selector: ResourceSelector | None = None,
163
- trigger: TriggerSource = TriggerSource.MANUAL,
164
- metadata: Mapping[str, Any] | None = None,
165
- correlation_id: str | None = None,
166
- ) -> RefreshResult:
167
- """Run a refresh and return its result.
168
-
169
- Failures of discovery, snapshots, operations, and the state store are
170
- reported in the result instead of being raised.
171
-
172
- Args:
173
- mode: Which resources to refresh. Defaults to `TARGETED` when
174
- `resource_ids` or `selector` is given, otherwise `INCREMENTAL`.
175
- resource_ids: IDs to refresh in `TARGETED` mode. A single string is
176
- treated as one ID.
177
- selector: Selector evaluated against discovered resources in
178
- `TARGETED` mode.
179
- trigger: What initiated the refresh.
180
- metadata: Application metadata attached to the request.
181
- correlation_id: Identifier propagated to every lifecycle event.
182
-
183
- Returns:
184
- The refresh result.
185
-
186
- Raises:
187
- ConfigurationError: If the arguments are inconsistent.
188
- EngineClosedError: If the engine is closing or closed.
189
- RuntimeError: If awaited directly by the source, operation, fingerprint
190
- strategy, or state store of one of this engine's refreshes, which
191
- would wait for itself.
192
- """
193
- ids = id_set(resource_ids, "resource_ids")
194
- if mode is None:
195
- mode = (
196
- RefreshMode.TARGETED
197
- if ids or selector is not None
198
- else RefreshMode.INCREMENTAL
199
- )
200
- request = RefreshRequest(
201
- mode=mode,
202
- resource_ids=ids,
203
- selector=selector,
204
- trigger=trigger,
205
- metadata=metadata or {},
206
- correlation_id=correlation_id,
207
- )
208
- return await self._coordinator.submit(request)
209
-
210
- async def submit(self, request: RefreshRequest) -> RefreshResult:
211
- """Run a prepared request and return its result.
212
-
213
- Args:
214
- request: The request to run.
215
-
216
- Returns:
217
- The refresh result.
218
-
219
- Raises:
220
- EngineClosedError: If the engine is closing or closed.
221
- RuntimeError: If awaited directly by the source, operation, fingerprint
222
- strategy, or state store of one of this engine's refreshes, which
223
- would wait for itself.
224
- TypeError: If `request` is not a `RefreshRequest`.
225
- """
226
- if not isinstance(request, RefreshRequest):
227
- raise TypeError("request must be a RefreshRequest")
228
- return await self._coordinator.submit(request)
229
-
230
- async def close(self, *, cancel: bool = False, wait: bool = True) -> None:
231
- """Stop accepting requests, finish accepted ones, and deliver pending events.
232
-
233
- Closing twice is safe.
234
-
235
- Args:
236
- cancel: Cancel the running and queued refreshes instead of letting them
237
- finish; their callers receive `CANCELLED` results.
238
- wait: Wait until the accepted refreshes have finished and their events
239
- have been delivered. Pass `False` to close from code that a refresh
240
- or an event handler waits for. Awaited directly by the source,
241
- operation, fingerprint strategy, or state store of one of this
242
- engine's refreshes, `close` never waits.
243
- """
244
- waiting = wait and not awaited_by(self._coordinator)
245
- await self._coordinator.close(cancel=cancel, wait=waiting)
246
- if waiting:
247
- await self._events.drain()
248
-
249
- async def __aenter__(self) -> Self:
250
- """Return the engine."""
251
- return self
252
-
253
- async def __aexit__(
254
- self,
255
- exc_type: type[BaseException] | None,
256
- exc: BaseException | None,
257
- traceback: TracebackType | None,
258
- ) -> None:
259
- """Close the engine, cancelling active work if the block raised."""
260
- await self.close(cancel=exc_type is not None)
1
+ """The refresh engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from inspect import iscoroutinefunction
7
+ from types import TracebackType
8
+ from typing import Self
9
+
10
+ from refresh_engine._internal.coordinator import RefreshCoordinator
11
+ from refresh_engine._internal.pipeline import RefreshPipeline
12
+ from refresh_engine._internal.reentrancy import awaited_by
13
+ from refresh_engine.contracts import (
14
+ FingerprintStrategy,
15
+ RefreshOperation,
16
+ RefreshOperationLike,
17
+ ResourceSource,
18
+ StateStore,
19
+ )
20
+ from refresh_engine.events import AsyncEventPublisher, EventPublisher
21
+ from refresh_engine.fingerprints import CompositeHash
22
+ from refresh_engine.models import RefreshConfig, RefreshRequest, RefreshResult
23
+ from refresh_engine.stores import InMemoryStateStore
24
+
25
+ __all__ = ["RefreshEngine", "RefreshEngineConfig"]
26
+
27
+
28
+ @dataclass(frozen=True, slots=True, kw_only=True, eq=False)
29
+ class RefreshEngineConfig:
30
+ """Everything a [`RefreshEngine`][refresh_engine.RefreshEngine] is built from.
31
+
32
+ The configuration holds the engine's dependencies and its execution settings.
33
+ It is immutable and validated on construction. Defaults are created per
34
+ configuration, so engines built from different configurations never share a
35
+ store or publisher unless they are given the same one.
36
+
37
+ Attributes:
38
+ source: Discovers resources and reads their snapshots.
39
+ operation: Applies the refresh or delete side effect of one resource.
40
+ fingerprint: Detects content changes; defaults to
41
+ [`CompositeHash`][refresh_engine.CompositeHash].
42
+ store: Persists resource state; defaults to a new
43
+ [`InMemoryStateStore`][refresh_engine.InMemoryStateStore].
44
+ config: Execution settings; defaults to
45
+ [`RefreshConfig()`][refresh_engine.RefreshConfig].
46
+ events: Publisher for lifecycle events; defaults to a new
47
+ [`AsyncEventPublisher`][refresh_engine.AsyncEventPublisher].
48
+
49
+ Raises:
50
+ TypeError: If a value does not implement its contract.
51
+
52
+ Example:
53
+ ```python
54
+ config = RefreshEngineConfig(source=source, operation=operation)
55
+ ```
56
+ """
57
+
58
+ source: ResourceSource
59
+ operation: RefreshOperationLike
60
+ fingerprint: FingerprintStrategy = field(default_factory=CompositeHash)
61
+ store: StateStore = field(default_factory=InMemoryStateStore)
62
+ config: RefreshConfig = field(default_factory=RefreshConfig)
63
+ events: EventPublisher = field(default_factory=AsyncEventPublisher)
64
+
65
+ def __post_init__(self) -> None:
66
+ """Check that every value implements its contract."""
67
+ if not isinstance(self.source, ResourceSource):
68
+ raise TypeError("source must subclass ResourceSource")
69
+ operation = self.operation
70
+ if not (
71
+ isinstance(operation, RefreshOperation)
72
+ or (callable(operation) and iscoroutinefunction(operation))
73
+ ):
74
+ raise TypeError(
75
+ "operation must subclass RefreshOperation or be an async function"
76
+ )
77
+ if not isinstance(self.fingerprint, FingerprintStrategy):
78
+ raise TypeError("fingerprint must subclass FingerprintStrategy")
79
+ if not isinstance(self.store, StateStore):
80
+ raise TypeError("store must subclass StateStore")
81
+ if not isinstance(self.config, RefreshConfig):
82
+ raise TypeError("config must be a RefreshConfig")
83
+ if not isinstance(self.events, EventPublisher):
84
+ raise TypeError("events must be an EventPublisher")
85
+
86
+
87
+ class RefreshEngine:
88
+ """Detect changes in a population of resources and refresh what changed.
89
+
90
+ Every refresh loads the previous state, discovers resources, observes them
91
+ (reading a snapshot and fingerprinting it, or reusing the previous state when a
92
+ reliable cheap indicator is unchanged), classifies changes, plans operations in
93
+ dependency order, runs them with bounded concurrency, and commits the state of
94
+ each successful resource.
95
+
96
+ An engine runs one refresh at a time; concurrent requests are handled by the
97
+ overlap policy of its [`RefreshConfig`][refresh_engine.RefreshConfig]. Use the
98
+ engine from a single event loop and close it when done, preferably with
99
+ `async with`.
100
+
101
+ The source, operation, fingerprint strategy, and state store of a refresh run
102
+ in a copy of the context of the code that requested it, so context variables,
103
+ such as tracing spans or bound log fields, reach them. Requests merged by the
104
+ overlap policy run in the context of the first request.
105
+
106
+ Args:
107
+ config: The engine's dependencies and execution settings.
108
+
109
+ Raises:
110
+ TypeError: If `config` is not a `RefreshEngineConfig`.
111
+
112
+ Example:
113
+ ```python
114
+ config = RefreshEngineConfig(source=source, operation=operation)
115
+ async with RefreshEngine(config) as engine:
116
+ result = await engine.refresh(RefreshRequest())
117
+ print(result.status, result.refreshed_count)
118
+ ```
119
+ """
120
+
121
+ def __init__(self, config: RefreshEngineConfig, /) -> None:
122
+ """Create an engine."""
123
+ if not isinstance(config, RefreshEngineConfig):
124
+ raise TypeError("config must be a RefreshEngineConfig")
125
+ self._config = config
126
+ pipeline = RefreshPipeline(
127
+ config.source,
128
+ config.operation,
129
+ config.fingerprint,
130
+ config.store,
131
+ config.config,
132
+ config.events,
133
+ )
134
+ self._coordinator = RefreshCoordinator(
135
+ pipeline.run, pipeline.finish_unrun, config.config.overlap_policy
136
+ )
137
+
138
+ @property
139
+ def config(self) -> RefreshEngineConfig:
140
+ """The configuration the engine was built from."""
141
+ return self._config
142
+
143
+ @property
144
+ def closed(self) -> bool:
145
+ """Whether the engine rejects new requests."""
146
+ return self._coordinator.closed
147
+
148
+ async def refresh(self, request: RefreshRequest, /) -> RefreshResult:
149
+ """Run `request` and return its result.
150
+
151
+ Failures of discovery, snapshots, operations, and the state store are
152
+ reported in the result instead of being raised.
153
+
154
+ Args:
155
+ request: What to refresh and why.
156
+
157
+ Returns:
158
+ The refresh result.
159
+
160
+ Raises:
161
+ EngineClosedError: If the engine is closing or closed.
162
+ RuntimeError: If awaited directly by the source, operation, fingerprint
163
+ strategy, or state store of one of this engine's refreshes, which
164
+ would wait for itself.
165
+ TypeError: If `request` is not a `RefreshRequest`.
166
+ """
167
+ if not isinstance(request, RefreshRequest):
168
+ raise TypeError("request must be a RefreshRequest")
169
+ return await self._coordinator.submit(request)
170
+
171
+ async def close(self, *, cancel: bool = False, wait: bool = True) -> None:
172
+ """Stop accepting requests, finish accepted ones, and deliver pending events.
173
+
174
+ Closing twice is safe.
175
+
176
+ Args:
177
+ cancel: Cancel the running and queued refreshes instead of letting them
178
+ finish; their callers receive `CANCELLED` results.
179
+ wait: Wait until the accepted refreshes have finished and their events
180
+ have been delivered. Pass `False` to close from code that a refresh
181
+ or an event handler waits for. Awaited directly by the source,
182
+ operation, fingerprint strategy, or state store of one of this
183
+ engine's refreshes, `close` never waits.
184
+ """
185
+ waiting = wait and not awaited_by(self._coordinator)
186
+ await self._coordinator.close(cancel=cancel, wait=waiting)
187
+ if waiting:
188
+ await self._config.events.drain()
189
+
190
+ async def __aenter__(self) -> Self:
191
+ """Return the engine."""
192
+ return self
193
+
194
+ async def __aexit__(
195
+ self,
196
+ exc_type: type[BaseException] | None,
197
+ exc: BaseException | None,
198
+ traceback: TracebackType | None,
199
+ ) -> None:
200
+ """Close the engine, cancelling active work if the block raised."""
201
+ await self.close(cancel=exc_type is not None)
@@ -362,6 +362,7 @@ class ResourceState:
362
362
  class RefreshRequest:
363
363
  """A normalized request to refresh resources.
364
364
 
365
+ The single input of [`RefreshEngine.refresh`][refresh_engine.RefreshEngine.refresh].
365
366
  `TARGETED` requests select resources with `resource_ids`, `selector`, or both;
366
367
  the other modes select resources by change and accept neither.
367
368
 
@@ -1,6 +1,6 @@
1
1
  """OpenTelemetry metrics and tracing adapters.
2
2
 
3
- This module requires the ``otel`` extra. It uses only the supplied meter and
3
+ This module requires the `otel` extra. It uses only the supplied meter and
4
4
  tracer; provider configuration and shutdown remain application-owned.
5
5
  """
6
6
 
@@ -67,7 +67,7 @@ class OpenTelemetryEventHandler(EventHandler):
67
67
 
68
68
  Only bounded, non-identifying attributes are recorded by default; spans carry
69
69
  the generated refresh ID so related spans can be correlated. Set
70
- ``record_identifiers=True`` to also record resource and correlation IDs on
70
+ `record_identifiers=True` to also record resource and correlation IDs on
71
71
  spans, which may contain application data. Refresh metadata and error
72
72
  messages are never recorded. Provider and exporter lifecycle remain owned by
73
73
  the application.
@@ -75,7 +75,7 @@ class OpenTelemetryEventHandler(EventHandler):
75
75
  A terminal refresh event ends the refresh span and every resource span of
76
76
  that refresh that is still open, for example after a cancellation or an
77
77
  overall timeout interrupted the operation; those resource spans get an error
78
- status and the attribute ``refresh_engine.resource.interrupted``. Resource
78
+ status and the attribute `refresh_engine.resource.interrupted`. Resource
79
79
  spans are only started while their refresh span is open. The default
80
80
  [`AsyncEventPublisher`][refresh_engine.AsyncEventPublisher] always delivers
81
81
  the event that closes a lifecycle whose start it delivered, even when its
@@ -55,7 +55,7 @@ class AsyncScheduler:
55
55
 
56
56
  Args:
57
57
  callback: Zero-argument function returning an awaitable, typically
58
- `lambda: engine.refresh(trigger=TriggerSource.SCHEDULED)`.
58
+ `lambda: engine.refresh(RefreshRequest(trigger=TriggerSource.SCHEDULED))`.
59
59
  interval: Seconds between scheduled runs.
60
60
  events: Publisher for scheduler events.
61
61
  run_immediately: Run the callback as soon as the scheduler starts instead of
@@ -68,7 +68,7 @@ class AsyncScheduler:
68
68
  Example:
69
69
  ```python
70
70
  scheduler = AsyncScheduler(
71
- lambda: engine.refresh(trigger=TriggerSource.SCHEDULED),
71
+ lambda: engine.refresh(RefreshRequest(trigger=TriggerSource.SCHEDULED)),
72
72
  interval=300,
73
73
  run_immediately=True,
74
74
  )
@@ -14,9 +14,9 @@ __all__ = ["StateStoreContract"]
14
14
  class StateStoreContract(ABC):
15
15
  """Async test suite for a custom state store.
16
16
 
17
- Subclass this in a test module and implement :meth:`make_store`. Pytest
18
- collects the inherited ``test_*`` methods when the subclass name starts with
19
- ``Test``.
17
+ Subclass this in a test module and implement `make_store()`. Pytest
18
+ collects the inherited `test_*` methods when the subclass name starts with
19
+ `Test`.
20
20
  """
21
21
 
22
22
  @abstractmethod
File without changes