python-ddd-framework 0.8.0__py3-none-any.whl → 0.9.0__py3-none-any.whl

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 (27) hide show
  1. python_ddd_framework/__init__.py +0 -2
  2. python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/README.md +6 -0
  3. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/AGENTS.md +1 -0
  4. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/README.md +6 -0
  5. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/src/host/module.py.jinja +0 -4
  6. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/architecture.md +6 -0
  7. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/development.md +62 -2
  8. python_ddd_framework/settings/__init__.py +1 -6
  9. python_ddd_framework/settings/application.py +4 -9
  10. python_ddd_framework/settings/catalog.py +4 -59
  11. python_ddd_framework/settings/management.py +3 -13
  12. python_ddd_framework/settings/manager.py +9 -33
  13. python_ddd_framework/settings/module.py +3 -9
  14. python_ddd_framework/settings/values.py +0 -8
  15. {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.9.0.dist-info}/METADATA +19 -3
  16. {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.9.0.dist-info}/RECORD +20 -27
  17. python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/setting_handlers/__init__.py.jinja +0 -1
  18. python_ddd_framework/settings/changes.py +0 -14
  19. python_ddd_framework/settings/declarations.py +0 -18
  20. python_ddd_framework/settings/handlers.py +0 -43
  21. python_ddd_framework/settings/notifications.py +0 -41
  22. python_ddd_framework/settings/refresh.py +0 -140
  23. python_ddd_framework/settings/refresh_module.py +0 -52
  24. {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.9.0.dist-info}/WHEEL +0 -0
  25. {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.9.0.dist-info}/entry_points.txt +0 -0
  26. {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.9.0.dist-info}/licenses/LICENSE +0 -0
  27. {python_ddd_framework-0.8.0.dist-info → python_ddd_framework-0.9.0.dist-info}/licenses/src/python_ddd_framework/background_jobs/pgqueuer/UPSTREAM_LICENSE.txt +0 -0
@@ -284,7 +284,6 @@ from .settings import (
284
284
  SettingManager,
285
285
  SettingProvider,
286
286
  )
287
- from .settings.declarations import SettingHandlers
288
287
  from .settings.module import SettingsModule
289
288
  from .unit_of_work import (
290
289
  UnitOfWork,
@@ -528,7 +527,6 @@ __all__ = (
528
527
  "SettingDefinitionContext",
529
528
  "SettingDefinitionError",
530
529
  "SettingDefinitionProvider",
531
- "SettingHandlers",
532
530
  "SettingManagementAccess",
533
531
  "SettingManager",
534
532
  "SettingProvider",
@@ -32,6 +32,12 @@ All responsibility directories and package markers are retained for navigation.
32
32
  5. Conventional HTTP exposure can discover the new public service contracts. Add manual routers only where the transport requires them; keep use-case rules out of HTTP. Register workers, jobs, hosted services, schedules, or event handlers explicitly when required.
33
33
  6. Update this responsibility record and run the smallest relevant existing checks. New tests and infrastructure validation require the task's authorization; neither an empty test directory nor successful composition proves business correctness.
34
34
 
35
+ ## Global settings
36
+
37
+ When a use case requires a global setting, place its `SettingDefinition` and synchronous definition provider under `domain/settings`, add SettingsModule to the Domain Module dependencies, and include the package in discovery. Callers import the same definition and inject SettingProvider; authorized writes use SettingManager with the version read by the caller. Provider selection and database setup belong to the Host.
38
+
39
+ Follow the application's [Global settings recipe](../../../../docs/development.md#global-settings) for configuration fallback, management permissions, and update/reset requests. Record this module's actual setting names, business use, and effective timing here when implemented. The skeleton has no business settings or observers; reset clears an override, and the framework does not apply values to running components.
40
+
35
41
  ## Persistence and verification
36
42
 
37
43
  An empty skeleton retains model and migration registration but has no business tables or revisions. Migration commands still use the configured database; an empty registered Base is different from a module with no model registration. Add actual models before generating a business revision, and review it before applying:
@@ -23,6 +23,7 @@ Use the [official CLI entry points](docs/development.md#cli-operations) for oper
23
23
  ## Preserve ownership and contracts
24
24
 
25
25
  - The Host composes modules, selects providers, and supplies configuration. Keep business state and rules in their owning modules.
26
+ - Global Settings definitions belong to their Domain Module; services own when values are read and applied. Follow the project's [Settings contract](docs/architecture.md#global-settings-ownership) and [usage recipe](docs/development.md#global-settings), preserving source, authorization, and version rules. Do not assume a component-refresh or notification service exists.
26
27
  - Domain and application contracts stay independent of Host, HTTP, and persistence implementations. Cross-module calls use explicitly declared dependencies and public contracts; do not access another module's implementation, ORM models, or tables directly.
27
28
  - Use framework application services, repositories, Options, permissions, units of work, events, jobs, and lifecycle hooks before adding custom infrastructure. Do not introduce a parallel DI container, service locator, transaction manager, or wrapper without a missing business capability.
28
29
  - Keep public contracts, mutable state, orchestration, and external I/O under clear owners. Split for independent responsibilities, not a fixed line count. Avoid generic `common`, `utils`, or `helpers` collections and speculative abstractions.
@@ -87,6 +87,12 @@ pddd inspect --environment development
87
87
 
88
88
  Inspection composes and closes a new Application without starting it. It does not query an existing process, and its input snapshot is not the final Options view. Configuration, workers, jobs, real-time communication, and logging are covered in the [development guide](docs/development.md).
89
89
 
90
+ ## Use global settings
91
+
92
+ The Host includes Settings persistence and management HTTP. After database setup, define each required setting in its owning module and grant management read/write permissions to the intended identity. Follow the self-contained [Global settings recipe](docs/development.md#global-settings) for definition discovery, YAML/environment fallback, service injection, and HTTP read/update/reset.
93
+
94
+ Settings stores global values; business code decides when they take effect. Reset clears a runtime override and resumes configuration/default fallback. Source restrictions, visibility, authorization, and version checks remain enforced. No business settings or automatic component-refresh workflow are generated.
95
+
90
96
  ## Test and package
91
97
 
92
98
  ```sh
@@ -21,8 +21,6 @@ from python_ddd_framework.observability.logging import StructuredLoggingModule
21
21
  from python_ddd_framework.observability.tracing import TracingModule
22
22
  from python_ddd_framework.redis import RedisDistributedLockModule, RedisModule
23
23
  from python_ddd_framework.redis.notifications import RedisNotificationsModule
24
- from python_ddd_framework.settings.notifications import SettingsNotificationsModule
25
- from python_ddd_framework.settings.refresh_module import SettingsRefreshModule
26
24
  from python_ddd_framework.settings.sqlalchemy import SqlAlchemyRuntimeSettingsModule
27
25
 
28
26
 
@@ -36,8 +34,6 @@ class {{ cookiecutter.class_prefix }}HostModule(AppModule):
36
34
  RedisModule,
37
35
  RedisDistributedLockModule,
38
36
  RedisNotificationsModule,
39
- SettingsNotificationsModule,
40
- SettingsRefreshModule,
41
37
  PgQueuerBackgroundJobsModule,
42
38
  BackgroundManagementHttpApiModule,
43
39
  StructuredLoggingModule,
@@ -83,6 +83,12 @@ These constraints apply when a capability models aggregates. The module README o
83
83
  | Cross-aggregate consistency | Before implementing a write spanning aggregates, identify the participating owners, what commits atomically, and any later effects. Record concurrency, failure-after-commit, duplicate/retry, and idempotency behavior. A local UoW may coordinate multiple aggregates when that is the confirmed requirement; do not impose one aggregate per transaction mechanically. Cross-module collaboration still uses public contracts, and local events do not promise durable distributed delivery. |
84
84
  | Business evidence | For each changed invariant, the module README must identify its rule owner, business operation, and a concrete rejection example, linking the relevant source and verification. Record unverified cases and open decisions explicitly. Directory placement, type checks, and passing unrelated tests do not by themselves prove a business rule. |
85
85
 
86
+ ## Global settings ownership
87
+
88
+ Settings owns global definitions, reads, conditional writes, and clearing overrides. Domain Modules contribute definitions under `domain/settings`; the Host selects persistence and management HTTP. Business services decide when to read and apply values. Source precedence is runtime override, Host configuration, then definition default, filtered by the definition's allowed sources.
89
+
90
+ Management visibility and permissions govern the generic management service. Internal business services own their authorization; all writes still enforce definition ownership, value validation, and version checks. Settings commits independently of an outer business UoW, and reset retains a fresh version record. It does not own component refresh, notifications, reconciliation, retries, or application status. Follow the [usage recipe](development.md#global-settings) for concrete declarations and calls.
91
+
86
92
  ## Calls, scopes, and transactions
87
93
 
88
94
  A managed service call passes through authorization, validation, ACTION scope, unit-of-work handling, and the final implementation. HTTP and direct service invocation share this pipeline. Inject the public service contract; do not construct implementations to bypass it. A self-call is an ordinary Python call and does not re-enter the pipeline.
@@ -128,7 +128,7 @@ For `basic`, keep public interfaces in `contracts/` and implementations in `serv
128
128
  | `domain_shared` | `constants`, `enums`, `errors`, `permissions`, `messages`, `value_objects` |
129
129
  | `domain` | `entities`, `value_objects`, `services`, `repositories`, `events`, `settings`, `seeding` |
130
130
  | `application_contracts` | `services`, `integration_services`, `inputs`, `views` |
131
- | `application` | `services`, `integration_services`, `background_jobs`, `background_workers`, `hosted_services`, `event_handlers`, `interceptors`, `caching`, `options`, `setting_handlers` |
131
+ | `application` | `services`, `integration_services`, `background_jobs`, `background_workers`, `hosted_services`, `event_handlers`, `interceptors`, `caching`, `options` |
132
132
  | `sqlalchemy` | `models`, `repositories`, `migrations` |
133
133
  | `http_api` | `routers`, `filters`, `websockets`, `models` |
134
134
 
@@ -238,7 +238,67 @@ orders:
238
238
 
239
239
  The corresponding environment key is `PDDD_ORDERS__ALLOW_BACKGROUND_APPROVAL`. `PDDD_HTTP__API_PREFIX` changes the business API prefix. `{{ cookiecutter.host_environment_variable }}` selects the Host environment and is separate from business configuration. Values that affect composition require the framework's pre-configuration phase; do not read unbound Options during construction.
240
240
 
241
- Use runtime settings when a value must be changed while the application is running. Add definitions through a scanned `SettingDefinitionProvider`, read them through `SettingProvider`, and use `SettingManager` or the management API for conditional updates/reset with the queried version token. Application services can use `self.setting_provider` during managed invocation, not during construction. Setting definitions belong under `domain/settings/`; declare SettingsModule on the owner when introducing them.
241
+ ### Global settings
242
+
243
+ Settings defines, reads, writes, and clears global runtime overrides. The following is an illustrative recipe, not a generated business feature. Add a definition and its provider under the owning module's `domain/settings/worker_settings.py` only when the setting is required:
244
+
245
+ ```python
246
+ from python_ddd_framework.settings import (
247
+ SettingDefinition,
248
+ SettingDefinitionContext,
249
+ SettingDefinitionProvider,
250
+ )
251
+
252
+ WORKER_LIMIT = SettingDefinition("worker.limit", int, default=10)
253
+
254
+
255
+ class WorkerSettingDefinitionProvider(SettingDefinitionProvider):
256
+ def define(self, context: SettingDefinitionContext) -> None:
257
+ context.add(WORKER_LIMIT)
258
+ ```
259
+
260
+ Add `SettingsModule` from `python_ddd_framework` to the existing Domain Module's dependencies, and include its package in `scan_packages`; retain the other dependencies and lifecycle hooks. Import this same definition in callers instead of constructing another object with the same name. Store credentials in Host configuration, not Settings.
261
+
262
+ By default, values resolve from runtime override, Host configuration, then definition default. An optional Host value in `backend/app.development.yaml` looks like this:
263
+
264
+ ```yaml
265
+ settings:
266
+ worker:
267
+ limit: 12
268
+ ```
269
+
270
+ The default environment key is `PDDD_SETTINGS__WORKER__LIMIT`. Without an override the value is 12, or 10 if that configuration is absent. Writing 20 makes it the override; reset resumes the configured 12. Configuration is frozen at startup: restart the Host after changing YAML/environment inputs. Reset does not reload files, and writing the default value still creates an override.
271
+
272
+ Inject `SettingProvider` for reads and `SettingManager` into an authorized service for writes. In an existing async service method, with `reader` and `manager` already injected:
273
+
274
+ ```python
275
+ limit = await reader.get(WORKER_LIMIT)
276
+ current = await reader.snapshot(WORKER_LIMIT)
277
+ saved = await manager.update(WORKER_LIMIT, 20, expected_version=current.version)
278
+ # saved is SettingSnapshot[int]: name, value, source, version.
279
+ reset = await manager.reset(WORKER_LIMIT, expected_version=saved.version)
280
+ ```
281
+
282
+ This demonstrates an immediate write/reset sequence. Interactive editing must retain the version the operator actually read, rather than fetch a fresh token just before saving. A conflict requires re-reading and a caller decision, not an automatic retry. Application services can also use `self.setting_provider` during managed invocation, not construction. Storage errors propagate; if no allowed source has a value, `snapshot` reports UNSET and `get` fails.
283
+
284
+ The generated Host selects `SqlAlchemyRuntimeSettingsModule` and `SettingsManagementHttpApiModule`. A custom Host must select them when it needs persistent overrides and management HTTP. Configure its database and run `pddd db upgrade --module settings` as part of database setup; startup does not migrate. Without a store binding, reads can use configuration/defaults but Manager is not registered.
285
+
286
+ With the default API prefix, use these operations after authenticating and granting the management permissions:
287
+
288
+ | Operation | Request |
289
+ | --- | --- |
290
+ | List visible settings | `GET /api/settings` |
291
+ | Read a setting and its version | `GET /api/settings/worker.limit` |
292
+ | Save an override | `PUT /api/settings/worker.limit`, body `{"value": 20, "expected_version": "<version from read>"}` |
293
+ | Clear an override | `POST /api/settings/worker.limit/reset`, body `{"expected_version": "<latest version>"}` |
294
+
295
+ Pass JSON null for `expected_version` only when the read returned null. Reads and writes return `name`, `value`, `source`, and `version`; reset retains a new version token. HTTP 409 means a version conflict. Writes commit independently of the caller's business transaction, and a successful response confirms persistence only.
296
+
297
+ Definitions may restrict `allowed_sources` without changing their fixed order. Excluding CONFIGURATION rejects matching Host inputs, so remove the YAML/environment setting too. `management_access` defaults to READ_WRITE; READ_ONLY rejects generic writes/reset, while HIDDEN omits the setting from lists and returns not found for individual management operations. Reads require `settings.read`; writes/reset require both `settings.read` and `settings.write`. Optional `read_permission`/`write_permission` values add per-setting requirements: declare those permissions under `domain_shared/permissions`, scan their PermissionDefinitionProvider, and depend on AuthorizationModule. Declaring a permission does not grant it. Internal services own their authorization; Manager still enforces ownership, sources, types, and versions.
298
+
299
+ Business code decides when to read and apply values. Settings provides no component refresh, change notification, reconciliation, retry, or application status. Generic Notifications and HostedService remain independent capabilities.
300
+
301
+ ### Inspect configuration
242
302
 
243
303
  Inspect configuration sources and service registrations with:
244
304
 
@@ -4,28 +4,23 @@ from .catalog import SettingCatalog
4
4
  from .contracts import SettingDefinition, SettingManagementAccess
5
5
  from .definitions import SettingDefinitionContext, SettingDefinitionProvider
6
6
  from .errors import RuntimeSettingError, SettingDefinitionError
7
- from .handlers import SettingApplicationStatus, SettingHandler, SettingHandlerDefinition
8
7
  from .manager import SettingManager
9
8
  from .provider import SettingProvider
10
9
  from .store import RuntimeSettingStore
11
- from .values import SettingSnapshot, SettingValueSource, SettingWriteOutcome, StoredSetting
10
+ from .values import SettingSnapshot, SettingValueSource, StoredSetting
12
11
 
13
12
  __all__ = (
14
13
  "RuntimeSettingError",
15
14
  "RuntimeSettingStore",
16
- "SettingApplicationStatus",
17
15
  "SettingCatalog",
18
16
  "SettingDefinition",
19
17
  "SettingDefinitionContext",
20
18
  "SettingDefinitionError",
21
19
  "SettingDefinitionProvider",
22
- "SettingHandler",
23
- "SettingHandlerDefinition",
24
20
  "SettingManagementAccess",
25
21
  "SettingManager",
26
22
  "SettingProvider",
27
23
  "SettingSnapshot",
28
24
  "SettingValueSource",
29
- "SettingWriteOutcome",
30
25
  "StoredSetting",
31
26
  )
@@ -24,7 +24,6 @@ from .management import (
24
24
  ResetSettingCommand,
25
25
  SettingsManagementApplicationService,
26
26
  SettingView,
27
- SettingWriteResult,
28
27
  UpdateSettingCommand,
29
28
  )
30
29
  from .manager import SettingManager
@@ -68,7 +67,7 @@ class _SettingsManagementApplicationService(ApplicationService):
68
67
  return _view(definition, await self.setting_provider.snapshot(definition))
69
68
 
70
69
  @authorize(SETTINGS_READ, SETTINGS_WRITE)
71
- async def update(self, name: str, command: UpdateSettingCommand) -> SettingWriteResult:
70
+ async def update(self, name: str, command: UpdateSettingCommand) -> SettingView:
72
71
  definition = self._definition(name)
73
72
  await self._check_write(definition)
74
73
  try:
@@ -79,18 +78,14 @@ class _SettingsManagementApplicationService(ApplicationService):
79
78
  saved = await self._settings.update(
80
79
  definition, value, expected_version=command.expected_version
81
80
  )
82
- return SettingWriteResult(
83
- setting=_view(definition, saved.snapshot), notification=saved.notification
84
- )
81
+ return _view(definition, saved)
85
82
 
86
83
  @authorize(SETTINGS_READ, SETTINGS_WRITE)
87
- async def reset(self, name: str, command: ResetSettingCommand) -> SettingWriteResult:
84
+ async def reset(self, name: str, command: ResetSettingCommand) -> SettingView:
88
85
  definition = self._definition(name)
89
86
  await self._check_write(definition)
90
87
  saved = await self._settings.reset(definition, expected_version=command.expected_version)
91
- return SettingWriteResult(
92
- setting=_view(definition, saved.snapshot), notification=saved.notification
93
- )
88
+ return _view(definition, saved)
94
89
 
95
90
  def _definition(self, name: str) -> SettingDefinition[Any]:
96
91
  definition = self._catalog.get(name)
@@ -4,28 +4,21 @@ from __future__ import annotations
4
4
 
5
5
  from collections.abc import Iterator, Mapping
6
6
  from types import MappingProxyType
7
- from typing import TYPE_CHECKING, Any
7
+ from typing import Any
8
8
 
9
9
  from ..diagnostics import SourceLocation
10
- from ..modularity import ModuleRegistry
11
10
  from ..modularity.discovery import _DiscoveredType
12
11
  from .contracts import SettingDefinition
13
- from .declarations import SettingHandlers
14
12
  from .definition_discovery import _collect_setting_definitions
15
13
  from .errors import SettingDefinitionError
16
- from .handlers import SettingHandlerDefinition
17
-
18
- if TYPE_CHECKING:
19
- from ..services.contribution import ServiceContributionRegistry
20
14
 
21
15
 
22
16
  class SettingCatalog:
23
- __slots__ = ("_definitions", "_handlers", "_sources")
17
+ __slots__ = ("_definitions", "_sources")
24
18
 
25
19
  def __init__(
26
20
  self,
27
21
  definitions: tuple[SettingDefinition[Any], ...],
28
- handlers: tuple[SettingHandlerDefinition[Any], ...] = (),
29
22
  *,
30
23
  sources: Mapping[str, SourceLocation] | None = None,
31
24
  ) -> None:
@@ -45,26 +38,12 @@ class SettingCatalog:
45
38
  self._definitions: Mapping[str, SettingDefinition[Any]] = MappingProxyType(
46
39
  dict(sorted(indexed.items()))
47
40
  )
48
- seen: set[tuple[str, type[object]]] = set()
49
- for handler in handlers:
50
- if not isinstance(handler, SettingHandlerDefinition):
51
- raise SettingDefinitionError(setting="handler", reason="invalid handler definition")
52
- self.require_owned(handler.setting)
53
- key = (handler.setting.name, handler.handler_type)
54
- if key in seen:
55
- raise SettingDefinitionError(setting=key[0], reason="handler is declared twice")
56
- seen.add(key)
57
- self._handlers = handlers
58
41
  self._sources = MappingProxyType(dict(sources or {}))
59
42
 
60
43
  @property
61
44
  def sources(self) -> Mapping[str, SourceLocation]:
62
45
  return self._sources
63
46
 
64
- @property
65
- def handlers(self) -> tuple[SettingHandlerDefinition[Any], ...]:
66
- return self._handlers
67
-
68
47
  @property
69
48
  def definitions(self) -> tuple[SettingDefinition[Any], ...]:
70
49
  return tuple(self._definitions.values())
@@ -83,40 +62,6 @@ class SettingCatalog:
83
62
  )
84
63
 
85
64
 
86
- def _build_setting_catalog(
87
- registry: ModuleRegistry, discoveries: tuple[_DiscoveredType, ...]
88
- ) -> SettingCatalog:
65
+ def _build_setting_catalog(discoveries: tuple[_DiscoveredType, ...]) -> SettingCatalog:
89
66
  definitions, sources = _collect_setting_definitions(discoveries)
90
- handlers: list[SettingHandlerDefinition[Any]] = []
91
- for descriptor, declaration in registry.declarations(SettingHandlers):
92
- declared_handlers = declaration.definitions
93
- if not isinstance(declared_handlers, tuple):
94
- raise SettingDefinitionError(
95
- setting=str(descriptor.key), reason="setting_handler_definitions must be a tuple"
96
- )
97
- handlers.extend(declared_handlers)
98
- return SettingCatalog(definitions, tuple(handlers), sources=sources)
99
-
100
-
101
- def _contribute_setting_handler_defaults(
102
- registry: ModuleRegistry,
103
- contributions: ServiceContributionRegistry,
104
- ) -> None:
105
- from dishka import Provider, Scope
106
-
107
- # 声明只拥有 handler 与 setting 的关系;实例和依赖仍交给原生 Dishka APP binding。
108
- registered: set[type[object]] = set()
109
- for descriptor, declaration in registry.declarations(SettingHandlers):
110
- for definition in declaration.definitions:
111
- handler_type = definition.handler_type
112
- if handler_type in registered:
113
- continue
114
- registered.add(handler_type)
115
- provider = Provider()
116
- provider.provide(handler_type, scope=Scope.APP)
117
- contributions._add_framework_default(
118
- provider=provider,
119
- owner=descriptor.key,
120
- source=descriptor.declaration_source,
121
- reason=f"Settings handler default for {definition.setting.name}",
122
- )
67
+ return SettingCatalog(definitions, sources=sources)
@@ -2,14 +2,13 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Literal, Protocol
5
+ from typing import Protocol
6
6
  from uuid import UUID
7
7
 
8
8
  from pydantic import BaseModel, ConfigDict, JsonValue
9
9
 
10
10
  from ..application_services import ApplicationServiceContract
11
11
  from ..authorization import PermissionName
12
- from ..notifications import NotificationPublishStatus
13
12
  from .values import SettingValueSource
14
13
 
15
14
  SETTINGS_READ = PermissionName("settings.read")
@@ -36,15 +35,6 @@ class SettingView(BaseModel):
36
35
  value: JsonValue
37
36
  source: SettingValueSource
38
37
  version: UUID | None
39
- effect: str = "New operations read the saved value; running components apply it separately."
40
-
41
-
42
- class SettingWriteResult(BaseModel):
43
- model_config = ConfigDict(frozen=True)
44
-
45
- saved: Literal[True] = True
46
- setting: SettingView
47
- notification: NotificationPublishStatus
48
38
 
49
39
 
50
40
  class SettingsManagementApplicationService(ApplicationServiceContract, Protocol):
@@ -52,6 +42,6 @@ class SettingsManagementApplicationService(ApplicationServiceContract, Protocol)
52
42
 
53
43
  async def get(self, name: str) -> SettingView: ...
54
44
 
55
- async def update(self, name: str, command: UpdateSettingCommand) -> SettingWriteResult: ...
45
+ async def update(self, name: str, command: UpdateSettingCommand) -> SettingView: ...
56
46
 
57
- async def reset(self, name: str, command: ResetSettingCommand) -> SettingWriteResult: ...
47
+ async def reset(self, name: str, command: ResetSettingCommand) -> SettingView: ...
@@ -1,32 +1,25 @@
1
- """条件写入与提交后通知的 owner;读取解析由 SettingProvider 负责。"""
1
+ """条件写入的 owner;读取解析由 SettingProvider 负责,生效时机归业务。"""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import logging
6
- from typing import TYPE_CHECKING, Any, TypeVar, cast
5
+ from typing import Any, TypeVar, cast
7
6
  from uuid import UUID
8
7
 
9
8
  from pydantic import ValidationError
10
9
  from pydantic_core import PydanticSerializationError
11
10
 
12
- from ..notifications import NotificationPayloadError, NotificationPublishStatus, Notifications
13
11
  from .catalog import SettingCatalog
14
- from .changes import SETTINGS_CHANGED, SettingChanged
15
12
  from .contracts import SettingDefinition
16
13
  from .errors import RuntimeSettingError
17
14
  from .provider import SettingProvider
18
15
  from .store import RuntimeSettingStore
19
- from .values import SettingSnapshot, SettingValueSource, SettingWriteOutcome, StoredSetting
20
-
21
- if TYPE_CHECKING:
22
- from .refresh import SettingsRefreshRuntime
16
+ from .values import SettingSnapshot, SettingValueSource, StoredSetting
23
17
 
24
18
  _T = TypeVar("_T")
25
- _LOGGER = logging.getLogger(__name__)
26
19
 
27
20
 
28
21
  class SettingManager:
29
- __slots__ = ("_catalog", "_notifications", "_provider", "_refresh", "_store")
22
+ __slots__ = ("_catalog", "_provider", "_store")
30
23
 
31
24
  def __init__(
32
25
  self, catalog: SettingCatalog, provider: SettingProvider, store: RuntimeSettingStore
@@ -34,13 +27,11 @@ class SettingManager:
34
27
  self._catalog = catalog
35
28
  self._provider = provider
36
29
  self._store = store
37
- self._refresh: SettingsRefreshRuntime | None = None
38
- self._notifications: Notifications | None = None
39
30
 
40
31
  async def set_global(self, definition: SettingDefinition[_T], value: _T) -> _T:
41
32
  current = await self._provider.snapshot(definition)
42
33
  saved = await self.update(definition, value, expected_version=current.version)
43
- return cast(_T, saved.snapshot.value)
34
+ return cast(_T, saved.value)
44
35
 
45
36
  async def reset_global(self, definition: SettingDefinition[Any]) -> None:
46
37
  current = await self._provider.snapshot(definition)
@@ -48,7 +39,7 @@ class SettingManager:
48
39
 
49
40
  async def update(
50
41
  self, definition: SettingDefinition[_T], value: _T, *, expected_version: UUID | None
51
- ) -> SettingWriteOutcome[_T]:
42
+ ) -> SettingSnapshot[_T]:
52
43
  self._require_write(definition, operation="set")
53
44
  try:
54
45
  validated, serialized = definition._dump_json(value)
@@ -60,20 +51,18 @@ class SettingManager:
60
51
  definition.name, serialized, expected_version=expected_version
61
52
  )
62
53
  # 返回本次已经提交的值,不在提交后重读,避免把另一次并发写入误报为本次结果。
63
- snapshot = SettingSnapshot(
54
+ return SettingSnapshot(
64
55
  definition.name, validated, SettingValueSource.RUNTIME, saved.version
65
56
  )
66
- return SettingWriteOutcome(snapshot, await self._committed(definition.name))
67
57
 
68
58
  async def reset(
69
59
  self, definition: SettingDefinition[_T], *, expected_version: UUID | None
70
- ) -> SettingWriteOutcome[_T]:
60
+ ) -> SettingSnapshot[_T]:
71
61
  self._require_write(definition, operation="reset")
72
62
  # 默认值先校验,不能在物理删除已经提交之后再抛出配置校验失败。
73
63
  fallback = self._provider._resolve(definition, StoredSetting(None, expected_version))
74
64
  saved = await self._store.write(definition.name, None, expected_version=expected_version)
75
- snapshot = SettingSnapshot(definition.name, fallback.value, fallback.source, saved.version)
76
- return SettingWriteOutcome(snapshot, await self._committed(definition.name))
65
+ return SettingSnapshot(definition.name, fallback.value, fallback.source, saved.version)
77
66
 
78
67
  def _require_write(self, definition: SettingDefinition[Any], *, operation: str) -> None:
79
68
  self._catalog.require_owned(definition)
@@ -81,16 +70,3 @@ class SettingManager:
81
70
  raise RuntimeSettingError(
82
71
  setting=definition.name, operation=operation, error_type="SourceNotAllowed"
83
72
  )
84
-
85
- async def _committed(self, name: str) -> NotificationPublishStatus:
86
- # 本地刷新先入队;Redis 降级不会撤销短事务已经提交的结果。
87
- if self._refresh is not None:
88
- self._refresh.request_refresh(name)
89
- if self._notifications is None:
90
- return NotificationPublishStatus.NOT_CONFIGURED
91
- try:
92
- return await self._notifications.publish(SETTINGS_CHANGED, SettingChanged(name=name))
93
- except NotificationPayloadError:
94
- # 发布大小/编码限制是独立结果;不能把已提交的写入重新表现为保存失败。
95
- _LOGGER.warning("Committed setting notification rejected for %s", name)
96
- return NotificationPublishStatus.REJECTED
@@ -8,11 +8,10 @@ from ..modularity import AppModule, ModuleRef
8
8
  from ..services.composition import (
9
9
  ServiceBindingContext,
10
10
  ServiceComposition,
11
- ServiceDiscoveryContext,
12
11
  )
13
12
  from ..services.registration import RegistrationDecision, RegistrationKind
14
13
  from .binding import _provide_settings
15
- from .catalog import SettingCatalog, _build_setting_catalog, _contribute_setting_handler_defaults
14
+ from .catalog import SettingCatalog, _build_setting_catalog
16
15
  from .errors import SettingDefinitionError
17
16
  from .store import RuntimeSettingStore
18
17
 
@@ -21,15 +20,10 @@ class SettingsModule(AppModule):
21
20
  catalog: SettingCatalog
22
21
 
23
22
  def configure(self, context: ConfigureContext) -> None:
24
- self.catalog = _build_setting_catalog(context.modules, context.discoveries)
23
+ self.catalog = _build_setting_catalog(context.discoveries)
25
24
  if self.catalog.definitions:
26
25
  context.configure.section("settings")
27
- context.services.add_composition(
28
- ServiceComposition(discover=self._discover, bind=self._bind)
29
- )
30
-
31
- def _discover(self, context: ServiceDiscoveryContext) -> None:
32
- _contribute_setting_handler_defaults(context.modules, context.services)
26
+ context.services.add_composition(ServiceComposition(bind=self._bind))
33
27
 
34
28
  def _bind(self, context: ServiceBindingContext) -> None:
35
29
  provider = Provider()
@@ -7,8 +7,6 @@ from enum import Enum
7
7
  from typing import Generic, TypeVar
8
8
  from uuid import UUID
9
9
 
10
- from ..notifications import NotificationPublishStatus
11
-
12
10
  _T = TypeVar("_T")
13
11
 
14
12
 
@@ -31,9 +29,3 @@ class SettingSnapshot(Generic[_T]):
31
29
  value: _T | None
32
30
  source: SettingValueSource
33
31
  version: UUID | None
34
-
35
-
36
- @dataclass(frozen=True, slots=True)
37
- class SettingWriteOutcome(Generic[_T]):
38
- snapshot: SettingSnapshot[_T]
39
- notification: NotificationPublishStatus
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-ddd-framework
3
- Version: 0.8.0
3
+ Version: 0.9.0
4
4
  Summary: Modular DDD application framework with project CLI and bundled templates
5
5
  License-Expression: LicenseRef-Proprietary
6
6
  License-File: LICENSE
@@ -64,7 +64,7 @@ Python DDD Framework combines a module system with FastAPI, Dishka, Pydantic, SQ
64
64
  | HTTP APIs | Expose selected application services through FastAPI, or write explicit routers. Use OpenAPI, filters, file uploads, downloads, and streaming responses. |
65
65
  | Persistence and events | Use async SQLAlchemy repositories, explicit transaction boundaries, module-owned Alembic migrations, seed contributors, and local events before or after commit. |
66
66
  | Identity and permissions | Add JWT authentication, refresh sessions, users and roles, permission definitions, and authorization on service methods. |
67
- | Cache, settings, and locks | Use typed Redis caching, runtime settings with conditional updates and reset, settings refresh notifications, and explicit Redis-backed business locks. |
67
+ | Cache, settings, and locks | Use typed Redis caching, global runtime settings with conditional updates and reset, and explicit Redis-backed business locks. |
68
68
  | Background execution | Enqueue durable PostgreSQL jobs with typed payloads, schedule recurring work, run periodic workers, and select in-process or managed subprocess execution. |
69
69
  | Real-time communication | Add authenticated WebSocket connections, typed messages, and targeted notifications to connected clients. |
70
70
  | Hosting and observability | Manage long-lived integrations with `HostedService`, coordinate shutdown, and use structured logging, correlation, OpenTelemetry tracing, and lifecycle health endpoints. |
@@ -273,6 +273,12 @@ Edit `backend/app.development.yaml` for local connections, identity settings, lo
273
273
 
274
274
  Generated credentials are for local development. Production configuration is supplied separately in `app.production.yaml`. See [configuration](https://github.com/componet-architecture/python-ddd-framework/blob/main/docs/development.md#定义-module-与配置) and [background and logging configuration](https://github.com/componet-architecture/python-ddd-framework/blob/main/docs/development.md#settings后台与日志).
275
275
 
276
+ ### Use global settings
277
+
278
+ Declare a typed `SettingDefinition` and its scanned provider under the owning module's `domain/settings/`, then add `SettingsModule` to that module's dependencies. Inject `SettingProvider` to read values and `SettingManager` for conditional writes/reset. The generated Host already selects Settings persistence and management HTTP; apply its Settings migration before using the store for reads or writes.
279
+
280
+ Values resolve from runtime override, Host configuration, then definition default. Reset clears an override and resumes fallback. Management provides list/read/update/reset with visibility, permissions, and version checks; business code decides when to use the value. Follow the [complete project recipe](docs/development.md#settings-策略与使用) or the generated project's **Global settings** guide for declarations, configuration, permissions, and request bodies. The minimal contract starts with 0.9.0; see [migration notes](#minimal-settings-migration-090).
281
+
276
282
  ### Run application tests
277
283
 
278
284
  After completing local database setup, run from `backend/`:
@@ -314,6 +320,16 @@ New `ddd` modules contain the full responsibility directories and necessary comp
314
320
 
315
321
  See the [migration guide](docs/development.md#数据库聚合与迁移) and [verification record](docs/status.md#http-回收与迁移来源判定未发布).
316
322
 
323
+ ## Minimal Settings migration (0.9.0)
324
+
325
+ Settings now owns only global definitions, reads, writes, and clearing overrides. Modules own definitions, the Host selects storage, and business code decides when and how to use the values. Source order, source restrictions, management permissions, typed JSON, independent transactions, UUID concurrency tokens, and reset version records remain unchanged. No dependency, database schema, or migration change is required.
326
+
327
+ - Remove `SettingsRefreshModule`, `SettingsNotificationsModule`, `SettingHandlers`, `SettingHandlerDefinition`, and Settings refresh options from Host/module wiring. Remove settings observers and the dedicated `application/setting_handlers` directory. Read through `SettingProvider` where the business needs the value; the framework no longer coordinates application, polling, reconnect compensation, retries, or application status. Generic Notifications and HostedService remain available independently.
328
+ - `SettingManager.update/reset` returns `SettingSnapshot[T]` directly: replace `result.snapshot.value/version` with `result.value/version`. `SettingWriteOutcome`, notification feedback, and handler/application status exports are removed.
329
+ - HTTP update/reset returns the same `SettingView` shape as a read: `name`, `value`, `source`, and `version`. Replace `response.setting` with `response`; remove `saved`, `notification`, and `effect` handling. `SettingWriteResult` is removed. Success confirms persistence only, and stale versions still produce a conflict.
330
+
331
+ Current rules and examples are in the [Settings contract](docs/architecture.md#typed-cache-与-settings) and [usage guide](docs/development.md#settings-策略与使用). Validation and remaining limits are recorded in [status](docs/status.md#settings-最小化未发布).
332
+
317
333
  ## Settings policies (0.8.0)
318
334
 
319
335
  `SettingDefinition` now accepts `allowed_sources`, `management_access`, `read_permission`, and `write_permission`. Existing definitions retain their source order and management visibility. Generic update/reset now also require `settings.read`, in addition to `settings.write` and any declared per-setting permissions, because their responses contain the saved setting snapshot. Update roles that previously held only write permission.
@@ -351,7 +367,7 @@ Runnable examples: [HTTP generators](docs/development.md#http-生成器与持续
351
367
  Capability composition now uses the same `AppModule` model as customer modules. Existing applications must migrate their declarations together; there is no compatibility path.
352
368
 
353
369
  - Declare capability dependencies on the Module that uses them. Selecting a sibling provider in Host does not supply a missing business-module dependency. `ApplicationServicesModule` supplies the usual application-service capabilities; additional capabilities are explicit dependencies.
354
- - Wrap capability declarations with `NotificationDefinitions`, `HostedServices`, `BackgroundWorkers`, `BackgroundSchedules`, or `SettingHandlers` from their owning packages. Use native service registration for providers and `ServiceComposition` for capability discovery and final binding. Keep provider selection in Host.
370
+ - Wrap capability declarations with `NotificationDefinitions`, `HostedServices`, `BackgroundWorkers`, or `BackgroundSchedules` from their owning packages. Use native service registration for providers and `ServiceComposition` for capability discovery and final binding. Keep provider selection in Host.
355
371
  - Replace Application invocation methods with `invoke(application, Service.method, ...)`, `invoke_as(application, user, ...)`, `call(application, function, ...)`, and `call_as(application, user, ...)`. Register interception with `add_interceptor(context, ...)` and events with `subscribe_local_event(context, ...)`. Import these functions from `python_ddd_framework`.
356
372
  - Read capability catalogs from their Module instance through `application.modules.instance(ModuleType)` or the catalog's DI binding. Generic service diagnostics remain in `application.service_catalog`; readiness is `application.is_ready`.
357
373
  - `DataSeedContributor`, `DataSeeder`, and `DataSeedError` belong to `python_ddd_framework.seeding` and remain available from the root package. Domain Modules with contributors depend on `DataSeedingModule`; remove `@application_service` from contributors. Seed is no longer an ApplicationService or part of its catalog. Explicit seed commands retain contributor ordering, per-item UoW, module dependency selection, failure reporting, and cleanup.
@@ -1,4 +1,4 @@
1
- python_ddd_framework/__init__.py,sha256=P4vRQIXbhDQk8zp_5_ToXK2lRJdPLUvAZ8iC-t6bg7U,15476
1
+ python_ddd_framework/__init__.py,sha256=TuNv1DOY2PLAvwzWzj_j0zSoJmofjjkdOQdqY18SDwI,15402
2
2
  python_ddd_framework/application/__init__.py,sha256=RPe_lkegIRim7GcBnXyevOg5KM7bfUIO9YGsqcA0lXk,184
3
3
  python_ddd_framework/application/build_spec.py,sha256=Udj1JIgP2oBMCUezmzWzOdjFYBCEE8OxwHSEaDqrMMo,1030
4
4
  python_ddd_framework/application/builder.py,sha256=d0vc1D5HvG_aJI5lPQydr-ha0OTNviWlplxlyP99qDs,8080
@@ -107,7 +107,7 @@ python_ddd_framework/developer_kit/templates/basic/{{cookiecutter.module_name}}/
107
107
  python_ddd_framework/developer_kit/templates/basic/{{cookiecutter.module_name}}/services/__init__.py.jinja,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
108
108
  python_ddd_framework/developer_kit/templates/basic/{{cookiecutter.module_name}}/services/default_conversion_service.py.jinja,sha256=YIYXqDycBVoUlLCwwUZ2tcyUk2fKSu-20mI00u5QUhc,342
109
109
  python_ddd_framework/developer_kit/templates/module/cookiecutter.json,sha256=edD_zSqmFuOKvMZyxmFFabAavBQJk0tbGO4YrnsgZN0,60
110
- python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/README.md,sha256=bojfHi_8PIPSeJheOdS6hSIaG2LrXDwmqymnwm0ZPDs,5674
110
+ python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/README.md,sha256=nbPgBhWynTZaK6vojFyxf2ARSYAzw6xCsNzAqUtulNo,6537
111
111
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/__init__.py.jinja,sha256=byPOI4PKtQDi5IQa9tzZZEVYy5zGx9PJdBzPrgcxm64,89
112
112
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/__init__.py.jinja,sha256=pm9_TqjN20deRELpopxK412O3mra0OZ6QdesPdcsaRU,90
113
113
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/background_jobs/__init__.py.jinja,sha256=Kbig4VsdpmVUDHx5SLPf7ZZM6S5ftVmzBxBAJIjwvng,40
@@ -120,7 +120,6 @@ python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}
120
120
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/module.py.jinja,sha256=qGmq1ggBmxGY2B8H8gB8tEY-uxMuWpyr60l0ZAouho8,1950
121
121
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/options/__init__.py.jinja,sha256=Kbig4VsdpmVUDHx5SLPf7ZZM6S5ftVmzBxBAJIjwvng,40
122
122
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/services/__init__.py.jinja,sha256=Kbig4VsdpmVUDHx5SLPf7ZZM6S5ftVmzBxBAJIjwvng,40
123
- python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application/setting_handlers/__init__.py.jinja,sha256=Kbig4VsdpmVUDHx5SLPf7ZZM6S5ftVmzBxBAJIjwvng,40
124
123
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application_contracts/__init__.py.jinja,sha256=grSDmU4IKdRYZsqi56aEVvsgx92AYF2k3jlDzANqra4,51
125
124
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application_contracts/inputs/__init__.py.jinja,sha256=Kbig4VsdpmVUDHx5SLPf7ZZM6S5ftVmzBxBAJIjwvng,40
126
125
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/application_contracts/integration_services/__init__.py.jinja,sha256=Kbig4VsdpmVUDHx5SLPf7ZZM6S5ftVmzBxBAJIjwvng,40
@@ -158,8 +157,8 @@ python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}
158
157
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/sqlalchemy/repositories/__init__.py.jinja,sha256=VdqphDwvoB9nhl5Q9vHpSnmMWwDUlDp_YckRkionwWw,46
159
158
  python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/tests/__init__.py.jinja,sha256=Kbig4VsdpmVUDHx5SLPf7ZZM6S5ftVmzBxBAJIjwvng,40
160
159
  python_ddd_framework/developer_kit/templates/project/cookiecutter.json,sha256=vmN799k9eRHAEGeYt8uUjPsusbblvgpNIsXVOsXUno4,314
161
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/AGENTS.md,sha256=u4fnjZJgqmIGf2CI9yYNRsfDLFktvGvuOVm2M-DQmKs,13059
162
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/README.md,sha256=i65NyuY-MXu1eZ3M_Ob5hFpcqCSd8hzc3iYr3Cn27g4,11146
160
+ python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/AGENTS.md,sha256=MVG6FbJckCZYwq-V33AZpH7RCvcv2tKaaN5VcaIzJ6M,13432
161
+ python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/README.md,sha256=y_Xg7rKtj6I8U2ChoLj57C5jz75gk2BdqD8F-ZH8IfI,11874
163
162
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/.dockerignore,sha256=TG053vIzikxG8h53vCcU_s5wcr7p4GEKwsedbrRrSOo,71
164
163
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/.gitignore,sha256=OF6nwgb-RiP8EAXc5osbk3bsOEYkk0JaV99v3FcglTU,66
165
164
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/.python-version,sha256=lN0hZ-3c-Wk_uFRrQasUfy9YJrXrdvSzYKhuHeXIXbY,34
@@ -170,11 +169,11 @@ python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name
170
169
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/pyproject.toml.jinja,sha256=zZ-kDjgfOYo4g35VLoctEEoyvlZm9fEB2ddHW30JzUs,932
171
170
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/src/host/__init__.py.jinja,sha256=RfLT7dqPnSotCDorSp6Taz9jBYOmepu6De_wZNelWZ8,74
172
171
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/src/host/main.py.jinja,sha256=SPxJ86SW1dx-BuoWITWifq-6NseoxnVMLTufcFFsxF4,1996
173
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/src/host/module.py.jinja,sha256=6j63muRR7tQmYIFso-egk8L5_Zw57I61ijWR8SDpw5U,3235
172
+ python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/src/host/module.py.jinja,sha256=qpM0L69ek8-SXQpJoZ-NkPyfGGIGTRrB1xtrmzpxZF8,3004
174
173
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/tests/conftest.py.jinja,sha256=I_SlSxioBsCFNJLM52iM-neYBJR71qOUn7C4dI9t-7I,149
175
174
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/tests/host/test_http.py.jinja,sha256=pmiz6k0oWWrPeW_rVG2Ynibg4j3yuKvgvYFc0K7J_no,2766
176
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/architecture.md,sha256=qU6lE4iwhTUDCY3OvtSgNYw99k8JGaOsyrmdaFt_Py4,26920
177
- python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/development.md,sha256=hEn_ucr8NmZnEp80TyAYB1IoLMWUoh9Hk8wCBzCizDM,53182
175
+ python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/architecture.md,sha256=VINiboJya5Ae6wn0UL7pHK-IXX7OIKfI0jbWaOL0F9U,27842
176
+ python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/development.md,sha256=V44TFV5BU5dhCautVc8D41h2-QhKgyCk69X3d-dWZgk,57556
178
177
  python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/scripts/.gitkeep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
179
178
  python_ddd_framework/developer_kit/wiring.py,sha256=80ZhxpGXK6NP3b_BTTc1kt3oIU21MU70cT9kgm8ZgAE,7835
180
179
  python_ddd_framework/diagnostics/__init__.py,sha256=HdgzjQqMJ_SUGKJc5EcQ5PL1rM4GcTeem-L0q1r7vjQ,455
@@ -390,25 +389,19 @@ python_ddd_framework/services/registration.py,sha256=AsvhVv_szq8TcaXdUMvOY6fNNp8
390
389
  python_ddd_framework/services/relocation.py,sha256=oMel_8RPFtPHDE9KrUepzx1nJpiug0EaNK7RWEKZFC0,3763
391
390
  python_ddd_framework/services/repository.py,sha256=jjjCmpcz4deAZmDNSM44WlDmh9msFO53qN116CHdBSM,1686
392
391
  python_ddd_framework/services/runtime.py,sha256=57G5jNjOiexpSqTCogdI18u5xeEK2YglztNqDtFcsZI,9300
393
- python_ddd_framework/settings/__init__.py,sha256=j9byBRTyegmIEK1KD6Q3UkHurPCnMUYJdnlhXTWL_wo,1090
394
- python_ddd_framework/settings/application.py,sha256=3hAlheeHcwSIS_1bFQmv7qjsAMIk7JYq9LnQLITfOWk,5666
392
+ python_ddd_framework/settings/__init__.py,sha256=EYm9Ek57X2o1edniVeKn150uKFgSrHF7onKUncGRQnc,867
393
+ python_ddd_framework/settings/application.py,sha256=QMouHpNJUxkmkQ3kRHSxtZ4ssDAsRZitYWiWADuGCH4,5444
395
394
  python_ddd_framework/settings/binding.py,sha256=_wDIsKe-p6WuKaQB9NvhbxCm9aYbiN95m7erJS35T8Y,1621
396
- python_ddd_framework/settings/catalog.py,sha256=fqVeFr3DuJWrNUfIuIwfivVhuCobQpWe32EmRieuUVE,4880
397
- python_ddd_framework/settings/changes.py,sha256=zpHhCJY83s-KIs7NkjQAmIxzY7cJfT8FD4A08gF9NfE,367
395
+ python_ddd_framework/settings/catalog.py,sha256=IkfZTd2PGUOMTyW7koQEdIXqPdiiPYlNmoTyfxPF4P0,2452
398
396
  python_ddd_framework/settings/contracts.py,sha256=v_Wn7kr3_JQYH-rXeusR_YWvtwR3RT_KxQqnvVD7uZI,6899
399
- python_ddd_framework/settings/declarations.py,sha256=FeFrgw6fAdjX6bGaajjnO2tsrfxEvKW6sZrRfTAxCEs,526
400
397
  python_ddd_framework/settings/definition_discovery.py,sha256=zHN3-coqzdEb--mecv00v7ifWzzCfJRZ-BrFcdVx4u4,3002
401
398
  python_ddd_framework/settings/definitions.py,sha256=hkWO0dqOoBmd7pKv-cUsCZaEU0AeUEULVLW1Rl8uwdQ,1687
402
399
  python_ddd_framework/settings/errors.py,sha256=ZcU1nMB44_Rq9Wl5bw83s3Y066LxSLrFqOW_gG6ViS4,836
403
- python_ddd_framework/settings/handlers.py,sha256=A0GWDKRXASlCoWm_Wduul0thAv4xW4SG305KXd6wY-4,1369
404
- python_ddd_framework/settings/management.py,sha256=dJhyZYfNA5Qsup9yt2dKOrIwGq3OnNkDxskJniBV3BI,1656
405
- python_ddd_framework/settings/manager.py,sha256=5pWLFB7EHMUsqnz-Gy615A2Sxv0HsKIEQtgmm0zl70A,4561
406
- python_ddd_framework/settings/module.py,sha256=KQydGp507MUlcykRWVUa36r5-_--BRJn88QLirxotAI,3340
407
- python_ddd_framework/settings/notifications.py,sha256=tVSXjhhJWhkMcOakSmeOfXT1X02Hcx2xRU8Whr8rSig,1700
400
+ python_ddd_framework/settings/management.py,sha256=sfibyZzhrsYg8FwPZCz_mDw6UEBtnP9HJaVu2O8PMmc,1298
401
+ python_ddd_framework/settings/manager.py,sha256=0jc7dQxGgKY-vc3rzVrPevHPZ6BY7y4APaxGd74kKlk,3164
402
+ python_ddd_framework/settings/module.py,sha256=jnCyeiFAnQB2q3Zeyx-HN9xmHbpGouUrfB3K3gJ8ekE,3061
408
403
  python_ddd_framework/settings/permissions.py,sha256=2nPyZOZ9G-4mSCIqwNI0C9WUBhP0ZwqNjljP3XZD3PE,553
409
404
  python_ddd_framework/settings/provider.py,sha256=AvMrdWML_wbbJEqNb9IH8_OcUUX8QbdEpxw4GDibdA4,3216
410
- python_ddd_framework/settings/refresh.py,sha256=jYYqEdTU4cOXyHmdMEdw_94qybp4bzVPRdrM6WF8q6k,5413
411
- python_ddd_framework/settings/refresh_module.py,sha256=wDxWau4oZCtBiMO6TDXZFbZRcKTiYaTFGWPjZnaFNug,2225
412
405
  python_ddd_framework/settings/sqlalchemy/__init__.py,sha256=G-S-sSsxwfjZxr0mVAyXUBG0SIxC3ZCMtrdpMsZ14YM,158
413
406
  python_ddd_framework/settings/sqlalchemy/migrations/0001_settings.py,sha256=wx_GcxijY-43V9DoNNzdvfwg8d5oYWkmeWSe23xtXLA,1045
414
407
  python_ddd_framework/settings/sqlalchemy/migrations/0002_physical_delete.py,sha256=JtPmESosI_SIe4ijFuBFX7zvcgsnk-7dtjULipdC6NU,982
@@ -418,7 +411,7 @@ python_ddd_framework/settings/sqlalchemy/models.py,sha256=qKbRHhdm0uDPUUtLgeVeFv
418
411
  python_ddd_framework/settings/sqlalchemy/module.py,sha256=NbvxE40aSW1aWf7CbU3GRPN_WrvsQgUXp05hAAoDtcE,1212
419
412
  python_ddd_framework/settings/sqlalchemy/store.py,sha256=I9yRtpZBzNEYG0NANFAgVvVTY0_Qnl5JinXf00ebQwE,3597
420
413
  python_ddd_framework/settings/store.py,sha256=3tdF-0l0owUdWuNEd0K8OfbXncI38hx0pD6anU5GdmA,442
421
- python_ddd_framework/settings/values.py,sha256=KMRZDQu2FRNXDIdJwGVgHn656Hc5qRY2WQGjbBxfhO4,898
414
+ python_ddd_framework/settings/values.py,sha256=smw2jLySVP6aKefqmkOqHp8z9pjc2nGfEofE6uGzMZY,687
422
415
  python_ddd_framework/sqlalchemy/__init__.py,sha256=DP6PAJHevoc1i-n9ma8_2CAiPmAvWoN7opqRYzHR4Sg,2054
423
416
  python_ddd_framework/sqlalchemy/alembic_runtime/__init__.py,sha256=r-ZHMiEhca5M2xv3plW9U3fHfzt5lVQeDohEFqrTuv0,82
424
417
  python_ddd_framework/sqlalchemy/alembic_runtime/env.py,sha256=ArKiDG9n5JOPQG44oSrJUd3o96zyY-b2PPkGysFy674,1389
@@ -452,9 +445,9 @@ python_ddd_framework/unit_of_work/module.py,sha256=EjsUtCG7w56NmLU_xqBRiwJ65Mw5h
452
445
  python_ddd_framework/unit_of_work/options.py,sha256=AVcEmwwn39qvj8PLQetBeGzdU_eblABGuNLDIQU5tyI,3365
453
446
  python_ddd_framework/validation/__init__.py,sha256=nTN_BgIXMLHeUtMgSj2hpisWc1_sk6UWTapk30oh1us,100
454
447
  python_ddd_framework/validation/models.py,sha256=Ydz5ZYgqYMPZEXi9A3DA6beN5lD9AcMaImnxDf1aRXs,1737
455
- python_ddd_framework-0.8.0.dist-info/licenses/LICENSE,sha256=2sSWLZdtk4EhG2GlwpksXzmyux-G6Qiov0D27lE_bqw,805
456
- python_ddd_framework-0.8.0.dist-info/licenses/src/python_ddd_framework/background_jobs/pgqueuer/UPSTREAM_LICENSE.txt,sha256=0lCGUd5Pke2Up1Kqn1kRnHcwLlBz60E8xvR7WL4k_kE,1066
457
- python_ddd_framework-0.8.0.dist-info/WHEEL,sha256=si2p8vW03RnhyBnhWl4tj-ObJa78SpE-c9HsEtblGR0,80
458
- python_ddd_framework-0.8.0.dist-info/entry_points.txt,sha256=CMy4XBD8IKGUfHwe0YBmHmSJtjfnA3yyDHqsMZCLsc8,447
459
- python_ddd_framework-0.8.0.dist-info/METADATA,sha256=IbP9K_ypVhMhck9GNfdMSwDRTeyqV_Muvph0XxBUDDY,68850
460
- python_ddd_framework-0.8.0.dist-info/RECORD,,
448
+ python_ddd_framework-0.9.0.dist-info/licenses/LICENSE,sha256=2sSWLZdtk4EhG2GlwpksXzmyux-G6Qiov0D27lE_bqw,805
449
+ python_ddd_framework-0.9.0.dist-info/licenses/src/python_ddd_framework/background_jobs/pgqueuer/UPSTREAM_LICENSE.txt,sha256=0lCGUd5Pke2Up1Kqn1kRnHcwLlBz60E8xvR7WL4k_kE,1066
450
+ python_ddd_framework-0.9.0.dist-info/WHEEL,sha256=si2p8vW03RnhyBnhWl4tj-ObJa78SpE-c9HsEtblGR0,80
451
+ python_ddd_framework-0.9.0.dist-info/entry_points.txt,sha256=CMy4XBD8IKGUfHwe0YBmHmSJtjfnA3yyDHqsMZCLsc8,447
452
+ python_ddd_framework-0.9.0.dist-info/METADATA,sha256=hk9U10YzJOgUMz5XK2ZTFvqjAwrhoBquHOzoMXqJQgI,71605
453
+ python_ddd_framework-0.9.0.dist-info/RECORD,,
@@ -1,14 +0,0 @@
1
- """Settings 变更只通知标识,数据库仍是有效值的唯一权威。"""
2
-
3
- from pydantic import BaseModel, ConfigDict
4
-
5
- from ..notifications import NotificationDefinition
6
-
7
-
8
- class SettingChanged(BaseModel):
9
- model_config = ConfigDict(frozen=True, extra="forbid")
10
-
11
- name: str
12
-
13
-
14
- SETTINGS_CHANGED = NotificationDefinition("settings.changed", SettingChanged)
@@ -1,18 +0,0 @@
1
- """Settings handler 的关系声明;实例和生命周期仍由原生 DI 管理。"""
2
-
3
- from dataclasses import dataclass
4
- from typing import Any
5
-
6
- from ..modularity import AppModule, ModuleDeclaration
7
- from .handlers import SettingHandlerDefinition
8
-
9
-
10
- @dataclass(frozen=True, slots=True)
11
- class SettingHandlers(ModuleDeclaration):
12
- definitions: tuple[SettingHandlerDefinition[Any], ...]
13
-
14
- @property
15
- def required_module(self) -> type[AppModule]:
16
- from .module import SettingsModule
17
-
18
- return SettingsModule
@@ -1,43 +0,0 @@
1
- """长期组件的 typed 应用契约;执行上下文由组件自身负责。"""
2
-
3
- from __future__ import annotations
4
-
5
- import inspect
6
- from dataclasses import dataclass
7
- from typing import Generic, Protocol, TypeVar
8
-
9
- from .contracts import SettingDefinition
10
- from .errors import SettingDefinitionError
11
- from .values import SettingSnapshot
12
-
13
- _T = TypeVar("_T")
14
-
15
-
16
- class SettingHandler(Protocol[_T]):
17
- async def apply(self, snapshot: SettingSnapshot[_T]) -> None: ...
18
-
19
-
20
- @dataclass(frozen=True, slots=True)
21
- class SettingHandlerDefinition(Generic[_T]):
22
- setting: SettingDefinition[_T]
23
- handler_type: type[SettingHandler[_T]]
24
-
25
- def __post_init__(self) -> None:
26
- if not isinstance(self.setting, SettingDefinition):
27
- raise SettingDefinitionError(setting="handler", reason="setting must be a definition")
28
- if (
29
- not isinstance(self.handler_type, type)
30
- or inspect.isabstract(self.handler_type)
31
- or not inspect.iscoroutinefunction(getattr(self.handler_type, "apply", None))
32
- ):
33
- raise SettingDefinitionError(
34
- setting=self.setting.name, reason="handler must have an async apply method"
35
- )
36
-
37
-
38
- @dataclass(frozen=True, slots=True)
39
- class SettingApplicationStatus:
40
- setting: str
41
- handler: str
42
- last_applied: SettingSnapshot[object] | None
43
- error_type: str | None
@@ -1,41 +0,0 @@
1
- """Settings 是通用通知的使用方,重连和漏消息的补偿由 Settings 自身拥有。"""
2
-
3
- from __future__ import annotations
4
-
5
- from contextlib import AsyncExitStack
6
-
7
- from ..lifecycle import PreInitializeContext, ShutdownContext
8
- from ..modularity import AppModule
9
- from ..notifications import Notifications
10
- from ..notifications.declarations import NotificationDefinitions
11
- from ..notifications.module import NotificationsModule
12
- from .changes import SETTINGS_CHANGED, SettingChanged
13
- from .manager import SettingManager
14
- from .refresh import SettingsRefreshRuntime
15
- from .refresh_module import SettingsRefreshModule
16
-
17
-
18
- class SettingsNotificationsModule(AppModule):
19
- dependencies = (SettingsRefreshModule, NotificationsModule)
20
- notification_definitions = NotificationDefinitions((SETTINGS_CHANGED,))
21
-
22
- def __init__(self) -> None:
23
- self._subscriptions = AsyncExitStack()
24
-
25
- async def pre_initialize(self, context: PreInitializeContext) -> None:
26
- refresh = await context.container.get(SettingsRefreshRuntime)
27
- notifications = await context.container.get(Notifications)
28
- settings = await context.container.get(SettingManager)
29
-
30
- async def changed(message: SettingChanged) -> None:
31
- refresh.request_refresh(message.name)
32
-
33
- await self._subscriptions.enter_async_context(
34
- notifications.subscribe(SETTINGS_CHANGED, changed, on_reconnect=refresh.request_refresh)
35
- )
36
- settings._notifications = notifications
37
-
38
- async def shutdown(self, context: ShutdownContext) -> None:
39
- settings = await context.container.get(SettingManager)
40
- settings._notifications = None
41
- await self._subscriptions.aclose()
@@ -1,140 +0,0 @@
1
- """单进程 Settings 刷新 owner:合并读取、串行应用、失败后按周期重试。"""
2
-
3
- from __future__ import annotations
4
-
5
- import asyncio
6
- import logging
7
- from contextlib import suppress
8
- from dataclasses import dataclass
9
- from typing import Any, ClassVar
10
-
11
- from pydantic import ConfigDict, Field
12
-
13
- from ..hosted_services import HostedService, HostedServiceContext
14
- from ..invocation.runtime import _InvocationRuntime
15
- from ..lifecycle import ShutdownReason
16
- from ..observability.context import capture_trace_context, invocation_span
17
- from ..options import BaseOptions, Options
18
- from .contracts import SettingDefinition
19
- from .handlers import SettingApplicationStatus, SettingHandler
20
- from .provider import SettingProvider
21
- from .values import SettingSnapshot, SettingValueSource
22
-
23
- _LOGGER = logging.getLogger(__name__)
24
-
25
-
26
- class SettingsRefreshOptions(BaseOptions):
27
- model_config = ConfigDict(extra="forbid")
28
-
29
- reconciliation_interval_seconds: float = Field(default=30.0, gt=0)
30
-
31
-
32
- @dataclass(slots=True)
33
- class _ApplicationRecord:
34
- handler: SettingHandler[Any]
35
- last_applied: SettingSnapshot[Any] | None = None
36
- error_type: str | None = None
37
-
38
-
39
- class SettingsRefreshRuntime(HostedService):
40
- run_in_background_processes: ClassVar[bool] = True
41
-
42
- def __init__(
43
- self,
44
- settings: SettingProvider,
45
- options: Options[SettingsRefreshOptions],
46
- runtime: _InvocationRuntime,
47
- ) -> None:
48
- self._settings = settings
49
- self._options = options.value
50
- self._runtime = runtime
51
- self._definitions: dict[str, SettingDefinition[Any]] = {}
52
- self._records: dict[str, list[_ApplicationRecord]] = {}
53
- self._dirty: dict[str, dict[str, str]] = {}
54
- self._wakeup = asyncio.Event()
55
- self._task: asyncio.Task[None] | None = None
56
-
57
- def _register(self, definition: SettingDefinition[Any], handler: SettingHandler[Any]) -> None:
58
- self._definitions[definition.name] = definition
59
- self._records.setdefault(definition.name, []).append(_ApplicationRecord(handler))
60
-
61
- def request_refresh(self, name: str | None = None) -> None:
62
- if name is None:
63
- for key in self._definitions:
64
- self._dirty.setdefault(key, {})
65
- elif name in self._definitions:
66
- self._dirty[name] = capture_trace_context(self._runtime.tracer)
67
- if self._dirty:
68
- self._wakeup.set()
69
-
70
- @property
71
- def statuses(self) -> tuple[SettingApplicationStatus, ...]:
72
- return tuple(
73
- SettingApplicationStatus(
74
- name,
75
- f"{type(record.handler).__module__}.{type(record.handler).__qualname__}",
76
- record.last_applied,
77
- record.error_type,
78
- )
79
- for name, records in self._records.items()
80
- for record in records
81
- )
82
-
83
- async def start(self, context: HostedServiceContext) -> None:
84
- self.request_refresh()
85
- self._task = asyncio.create_task(self._run(), name=context.name)
86
-
87
- async def stop(self, reason: ShutdownReason) -> None:
88
- if self._task is not None:
89
- self._task.cancel()
90
- with suppress(asyncio.CancelledError):
91
- await self._task
92
-
93
- async def _run(self) -> None:
94
- if not self._definitions:
95
- await asyncio.Future[None]()
96
- while True:
97
- try:
98
- await asyncio.wait_for(
99
- self._wakeup.wait(), timeout=self._options.reconciliation_interval_seconds
100
- )
101
- except TimeoutError:
102
- self.request_refresh()
103
- # 取走本轮名字后立即清理;await 期间到达的新请求进入下一轮,不能被误清除。
104
- requests = tuple(self._dirty.items())
105
- self._dirty.clear()
106
- self._wakeup.clear()
107
- for name, carrier in requests:
108
- with invocation_span(
109
- self._runtime.tracer, f"refresh setting {name}", carrier=carrier
110
- ):
111
- await self._refresh(name)
112
-
113
- async def _refresh(self, name: str) -> None:
114
- try:
115
- latest = await self._settings.snapshot(self._definitions[name])
116
- except Exception as error:
117
- for record in self._records[name]:
118
- record.error_type = type(error).__name__
119
- _LOGGER.error("Settings refresh failed for %s: %s", name, type(error).__name__)
120
- return
121
- for record in self._records[name]:
122
- previous = record.last_applied
123
- if (
124
- previous is not None
125
- and record.error_type is None
126
- and previous.value == latest.value
127
- and (previous.source is SettingValueSource.UNSET)
128
- == (latest.source is SettingValueSource.UNSET)
129
- ):
130
- continue
131
- try:
132
- with invocation_span(self._runtime.tracer, f"apply setting {name}"):
133
- await record.handler.apply(latest)
134
- except Exception as error:
135
- # 失败不能覆盖成功记录,下一次校对仍会按最后成功应用的值决定重试。
136
- record.error_type = type(error).__name__
137
- _LOGGER.error("Settings handler failed for %s: %s", name, record.error_type)
138
- else:
139
- record.last_applied = latest
140
- record.error_type = None
@@ -1,52 +0,0 @@
1
- """只组装正式 handler 与刷新运行时;组件应用规则由 handler 自己拥有。"""
2
-
3
- from __future__ import annotations
4
-
5
- from dishka import DEFAULT_COMPONENT, DependencyKey
6
-
7
- from python_ddd_framework import ConfigureContext
8
-
9
- from ..hosted_services.declarations import HostedServices
10
- from ..lifecycle import PreInitializeContext, ShutdownContext
11
- from ..modularity import AppModule, ModuleRef
12
- from .catalog import SettingCatalog
13
- from .manager import SettingManager
14
- from .module import SettingsModule
15
- from .refresh import SettingsRefreshOptions, SettingsRefreshRuntime
16
-
17
-
18
- class SettingsRefreshModule(AppModule):
19
- dependencies = (
20
- SettingsModule,
21
- ModuleRef("python_ddd_framework.hosted_services.module:HostedServicesModule"),
22
- )
23
-
24
- def __init__(self) -> None:
25
- self._manager: SettingManager | None = None
26
-
27
- def configure(self, context: ConfigureContext) -> None:
28
- context.configure(SettingsRefreshOptions, section="settings_refresh")
29
-
30
- hosted_services = HostedServices((SettingsRefreshRuntime,))
31
-
32
- async def pre_initialize(self, context: PreInitializeContext) -> None:
33
- catalog = await context.container.get(SettingCatalog)
34
- refresh = await context.container.get(SettingsRefreshRuntime)
35
- for definition in catalog.handlers:
36
- handler = await context.container.get(definition.handler_type)
37
- refresh._register(definition.setting, handler)
38
- # Manager 固定归 APP;查询最终原生图,含 alias,不构造服务或维护第二清单。
39
- # 无存储仍应用只读值;已注册服务由原生 get 解析,构造失败不能降级。
40
- if (
41
- context.container.registry.get_factory(DependencyKey(SettingManager, DEFAULT_COMPONENT))
42
- is not None
43
- ):
44
- settings = await context.container.get(SettingManager)
45
- settings._refresh = refresh
46
- self._manager = settings
47
-
48
- async def shutdown(self, context: ShutdownContext) -> None:
49
- # 只解除本实例完成的接线;启动部分失败后的关闭不得重新构造依赖。
50
- if self._manager is not None:
51
- self._manager._refresh = None
52
- self._manager = None