dskity 0.1.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.
- dskity-0.1.0/PKG-INFO +13 -0
- dskity-0.1.0/README.md +0 -0
- dskity-0.1.0/pyproject.toml +36 -0
- dskity-0.1.0/setup.cfg +4 -0
- dskity-0.1.0/src/dskity/__init__.py +5 -0
- dskity-0.1.0/src/dskity/__main__.py +7 -0
- dskity-0.1.0/src/dskity/app.py +16 -0
- dskity-0.1.0/src/dskity/bootstrap.py +294 -0
- dskity-0.1.0/src/dskity/cli.py +95 -0
- dskity-0.1.0/src/dskity/config/__init__.py +0 -0
- dskity-0.1.0/src/dskity/config/loader.py +108 -0
- dskity-0.1.0/src/dskity/config/settings.py +322 -0
- dskity-0.1.0/src/dskity/kvstore/__init__.py +0 -0
- dskity-0.1.0/src/dskity/kvstore/backends.py +359 -0
- dskity-0.1.0/src/dskity/kvstore/client.py +43 -0
- dskity-0.1.0/src/dskity/kvstore/ring.py +153 -0
- dskity-0.1.0/src/dskity/logging.py +79 -0
- dskity-0.1.0/src/dskity/metrics.py +57 -0
- dskity-0.1.0/src/dskity/modules/__init__.py +0 -0
- dskity-0.1.0/src/dskity/modules/contracts.py +33 -0
- dskity-0.1.0/src/dskity/modules/kvstore/__init__.py +0 -0
- dskity-0.1.0/src/dskity/modules/kvstore/module.py +95 -0
- dskity-0.1.0/src/dskity/modules/modules_resolver.py +143 -0
- dskity-0.1.0/src/dskity/modules/registry.py +63 -0
- dskity-0.1.0/src/dskity/registry/__init__.py +0 -0
- dskity-0.1.0/src/dskity/registry/api.py +204 -0
- dskity-0.1.0/src/dskity/registry/heartbeat.py +80 -0
- dskity-0.1.0/src/dskity/registry/middleware.py +51 -0
- dskity-0.1.0/src/dskity/registry/service_registry.py +164 -0
- dskity-0.1.0/src/dskity/registry/store.py +23 -0
- dskity-0.1.0/src/dskity/request_id.py +64 -0
- dskity-0.1.0/src/dskity/transport/__init__.py +0 -0
- dskity-0.1.0/src/dskity/transport/grpc.py +43 -0
- dskity-0.1.0/src/dskity/transport/mqtt.py +36 -0
- dskity-0.1.0/src/dskity/transport/rest_client.py +13 -0
- dskity-0.1.0/src/dskity.egg-info/PKG-INFO +13 -0
- dskity-0.1.0/src/dskity.egg-info/SOURCES.txt +39 -0
- dskity-0.1.0/src/dskity.egg-info/dependency_links.txt +1 -0
- dskity-0.1.0/src/dskity.egg-info/entry_points.txt +2 -0
- dskity-0.1.0/src/dskity.egg-info/requires.txt +7 -0
- dskity-0.1.0/src/dskity.egg-info/top_level.txt +1 -0
dskity-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dskity
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Requires-Python: >=3.14
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: fastapi>=0.136.0
|
|
8
|
+
Requires-Dist: httpx>=0.28.1
|
|
9
|
+
Requires-Dist: prometheus-client>=0.25.0
|
|
10
|
+
Requires-Dist: pydantic-settings>=2.14.0
|
|
11
|
+
Requires-Dist: pyyaml>=6.0.3
|
|
12
|
+
Requires-Dist: requests>=2.33.1
|
|
13
|
+
Requires-Dist: uvicorn>=0.44.0
|
dskity-0.1.0/README.md
ADDED
|
File without changes
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dskity"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Add your description here"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.14"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"fastapi>=0.136.0",
|
|
13
|
+
"httpx>=0.28.1",
|
|
14
|
+
"prometheus-client>=0.25.0",
|
|
15
|
+
"pydantic-settings>=2.14.0",
|
|
16
|
+
"pyyaml>=6.0.3",
|
|
17
|
+
"requests>=2.33.1",
|
|
18
|
+
"uvicorn>=0.44.0",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
dskity = "dskity.__main__:main"
|
|
23
|
+
|
|
24
|
+
[dependency-groups]
|
|
25
|
+
dev = [
|
|
26
|
+
"pytest>=9.0.3",
|
|
27
|
+
"ruff>=0.15.12",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.setuptools]
|
|
31
|
+
package-dir = {"" = "src"}
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.packages.find]
|
|
34
|
+
where = ["src"]
|
|
35
|
+
include = ["dskity*"]
|
|
36
|
+
exclude = ["dskity.tests*"]
|
dskity-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from fastapi import FastAPI
|
|
4
|
+
|
|
5
|
+
from dskity.bootstrap import bootstrap
|
|
6
|
+
from dskity.logging import configure_logging
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def create_app() -> FastAPI:
|
|
10
|
+
configure_logging()
|
|
11
|
+
app = FastAPI(title="dskity")
|
|
12
|
+
bootstrap(app)
|
|
13
|
+
return app
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
app = create_app()
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
import logging
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from fastapi import FastAPI
|
|
11
|
+
|
|
12
|
+
from dskity.config.loader import load_config
|
|
13
|
+
from dskity.kvstore.backends import backend_from_config, generate_node_id
|
|
14
|
+
from dskity.metrics import install_metrics
|
|
15
|
+
from dskity.modules.registry import ModuleRegistry
|
|
16
|
+
from dskity.modules.contracts import TransportClients
|
|
17
|
+
from dskity.transport.mqtt import MQTTClient
|
|
18
|
+
from dskity.transport.grpc import GRPCClient
|
|
19
|
+
from dskity.modules.modules_resolver import ModulesResolver
|
|
20
|
+
from dskity.request_id import install_request_id
|
|
21
|
+
from dskity.registry.api import router as registry_router
|
|
22
|
+
from dskity.registry.heartbeat import HeartbeatConfig, start_heartbeat, stop_heartbeat
|
|
23
|
+
from dskity.registry.middleware import EnabledModuleInfo, RegistryAdvertiseMiddleware
|
|
24
|
+
from dskity.registry.store import RegistryStore
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _resolve_app_init_dir(config_path: str | None) -> Path:
|
|
31
|
+
if not config_path:
|
|
32
|
+
return Path.cwd().resolve()
|
|
33
|
+
|
|
34
|
+
cfg_path = Path(config_path).expanduser()
|
|
35
|
+
if not cfg_path.is_absolute():
|
|
36
|
+
cfg_path = Path.cwd() / cfg_path
|
|
37
|
+
return cfg_path.resolve().parent
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _resolve_modules_search_paths(config, config_path: str | None) -> list[Path]:
|
|
41
|
+
app_init_dir = _resolve_app_init_dir(config_path)
|
|
42
|
+
|
|
43
|
+
candidates: list[Path] = [
|
|
44
|
+
Path.cwd().resolve(),
|
|
45
|
+
app_init_dir,
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
configured_paths = getattr(config, "modules_search_paths", []) or []
|
|
49
|
+
for raw_path in configured_paths:
|
|
50
|
+
if not isinstance(raw_path, str):
|
|
51
|
+
continue
|
|
52
|
+
|
|
53
|
+
entry = raw_path.strip()
|
|
54
|
+
if not entry:
|
|
55
|
+
continue
|
|
56
|
+
|
|
57
|
+
# Apenas entradas com aparência de caminho de filesystem entram no sys.path.
|
|
58
|
+
if "/" not in entry and "\\" not in entry and not entry.startswith((".", "~")):
|
|
59
|
+
continue
|
|
60
|
+
|
|
61
|
+
path = Path(entry).expanduser()
|
|
62
|
+
if not path.is_absolute():
|
|
63
|
+
path = app_init_dir / path
|
|
64
|
+
candidates.append(path.resolve())
|
|
65
|
+
|
|
66
|
+
seen: set[str] = set()
|
|
67
|
+
resolved: list[Path] = []
|
|
68
|
+
for path in candidates:
|
|
69
|
+
key = str(path)
|
|
70
|
+
if key in seen:
|
|
71
|
+
continue
|
|
72
|
+
seen.add(key)
|
|
73
|
+
resolved.append(path)
|
|
74
|
+
return resolved
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _install_modules_search_paths(paths: list[Path]) -> list[str]:
|
|
78
|
+
ordered = [str(path) for path in paths]
|
|
79
|
+
for path_str in reversed(ordered):
|
|
80
|
+
if path_str not in sys.path:
|
|
81
|
+
sys.path.insert(0, path_str)
|
|
82
|
+
return ordered
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _is_probably_package_path(value: str) -> bool:
|
|
86
|
+
if not value or "/" in value or "\\" in value or value.startswith((".", "~")):
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
parts = value.split(".")
|
|
90
|
+
return bool(parts) and all(part.isidentifier() for part in parts)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _resolve_modules_import_packages(config: Any) -> list[str]:
|
|
94
|
+
configured_paths = getattr(config, "modules_search_paths", []) or []
|
|
95
|
+
candidates: list[str] = []
|
|
96
|
+
for item in configured_paths:
|
|
97
|
+
if not isinstance(item, str):
|
|
98
|
+
continue
|
|
99
|
+
entry = item.strip()
|
|
100
|
+
if not entry or not _is_probably_package_path(entry):
|
|
101
|
+
continue
|
|
102
|
+
candidates.append(entry)
|
|
103
|
+
|
|
104
|
+
seen: set[str] = set()
|
|
105
|
+
packages: list[str] = []
|
|
106
|
+
for package in candidates:
|
|
107
|
+
if package in seen:
|
|
108
|
+
continue
|
|
109
|
+
seen.add(package)
|
|
110
|
+
packages.append(package)
|
|
111
|
+
return packages
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def bootstrap(app: FastAPI) -> None:
|
|
115
|
+
config_path = os.getenv("DSKITY_CONFIG")
|
|
116
|
+
config = load_config(override_path=config_path)
|
|
117
|
+
|
|
118
|
+
# Salva config no app.state para acesso posterior
|
|
119
|
+
app.state.config = config
|
|
120
|
+
|
|
121
|
+
targets_env = os.getenv("DSKITY_TARGETS")
|
|
122
|
+
target_modules: set[str] | None = None
|
|
123
|
+
if isinstance(targets_env, str) and targets_env.strip():
|
|
124
|
+
parts = [p.strip() for p in targets_env.split(",")]
|
|
125
|
+
target_modules = {p for p in parts if p}
|
|
126
|
+
|
|
127
|
+
# Disponibiliza a configuração completa em runtime.
|
|
128
|
+
# Útil para handlers/middlewares e módulos que precisem consultar settings depois do bootstrap.
|
|
129
|
+
app.state.config = config
|
|
130
|
+
app.state.config_path = config_path
|
|
131
|
+
|
|
132
|
+
# Métricas Prometheus (HTTP) + endpoint /metrics.
|
|
133
|
+
install_metrics(app)
|
|
134
|
+
|
|
135
|
+
# Resolver de módulos: permite obter URL de um módulo por nome.
|
|
136
|
+
# Ex.: request.app.modules.get("echo") -> URL (random entre instâncias)
|
|
137
|
+
app.modules = ModulesResolver(app) # type: ignore[attr-defined]
|
|
138
|
+
|
|
139
|
+
@app.middleware("http")
|
|
140
|
+
async def _modules_resolver_middleware(request, call_next):
|
|
141
|
+
# Garante que o resolver exista na instância do app em runtime.
|
|
142
|
+
if not hasattr(request.app, "modules"):
|
|
143
|
+
request.app.modules = ModulesResolver(request.app) # type: ignore[attr-defined]
|
|
144
|
+
return await call_next(request)
|
|
145
|
+
|
|
146
|
+
# advertise_url: URL publicada no discovery (separada do listen host/port).
|
|
147
|
+
# config agora é DSkitySettings (Pydantic model), não um dict
|
|
148
|
+
# NOTA: Se não configurado explicitamente, não definimos advertise_url com fallback de porta.
|
|
149
|
+
# O heartbeat e middleware cuidam do registro com a porta correta.
|
|
150
|
+
if config.common.advertise_url:
|
|
151
|
+
advertise_url = config.common.advertise_url
|
|
152
|
+
else:
|
|
153
|
+
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
154
|
+
# s.connect(("8.8.8.8", 80))
|
|
155
|
+
# ip = s.getsockname()[0]
|
|
156
|
+
# port = app.state.listen_port if hasattr(app.state, "listen_port") else 8000
|
|
157
|
+
# advertise_url = f"http://{ip}:{port}".rstrip("/")
|
|
158
|
+
advertise_url = None
|
|
159
|
+
app.state.advertise_url = advertise_url.rstrip("/") if isinstance(advertise_url, str) and advertise_url else None
|
|
160
|
+
|
|
161
|
+
# Acessa registry config via atributos do Pydantic model
|
|
162
|
+
if config and config.common.registry:
|
|
163
|
+
app.state.registry_ttl_seconds = config.common.registry.ttl_seconds or 60
|
|
164
|
+
app.state.registry_heartbeat_interval_seconds = config.common.registry.heartbeat_interval_seconds or max(
|
|
165
|
+
10, app.state.registry_ttl_seconds // 2
|
|
166
|
+
)
|
|
167
|
+
else:
|
|
168
|
+
app.state.registry_ttl_seconds = 60
|
|
169
|
+
app.state.registry_heartbeat_interval_seconds = 30
|
|
170
|
+
|
|
171
|
+
# Identidade desta instância (processo) para discovery.
|
|
172
|
+
app.state.instance_id = generate_node_id()
|
|
173
|
+
|
|
174
|
+
# Inicializa um store compartilhável para service discovery (registry).
|
|
175
|
+
# Padrão desejado (estilo Loki/Cortex): o registry é um recurso de core e pode estar
|
|
176
|
+
# habilitado mesmo que o módulo `kvstore` (API HTTP /kv) esteja desabilitado.
|
|
177
|
+
#
|
|
178
|
+
# Compat: se `common.registry.enabled` não estiver setado, usamos o valor antigo de `kvstore.enabled`.
|
|
179
|
+
# config agora é DSkitySettings (Pydantic model)
|
|
180
|
+
|
|
181
|
+
# Para compatibilidade com código antigo que usava modules["kvstore"],
|
|
182
|
+
# verifica se há config e acessa via atributos Pydantic
|
|
183
|
+
registry_cfg = config.common.registry if config and config.common else None
|
|
184
|
+
legacy_registry_enabled = False # Já não há módulo 'kvstore' em novo código
|
|
185
|
+
|
|
186
|
+
registry_enabled = bool(registry_cfg.enabled) if registry_cfg else legacy_registry_enabled
|
|
187
|
+
if registry_enabled:
|
|
188
|
+
try:
|
|
189
|
+
store_name, backend = backend_from_config(config)
|
|
190
|
+
except (ValueError, NotImplementedError) as e:
|
|
191
|
+
raise RuntimeError(str(e)) from e
|
|
192
|
+
app.state.kvstore_backend = backend
|
|
193
|
+
app.state.kvstore_store = store_name
|
|
194
|
+
app.state.registry_store = RegistryStore(backend=backend)
|
|
195
|
+
|
|
196
|
+
modules_search_paths = _resolve_modules_search_paths(config, config_path)
|
|
197
|
+
app.state.modules_search_paths = _install_modules_search_paths(modules_search_paths)
|
|
198
|
+
|
|
199
|
+
modules_import_packages = _resolve_modules_import_packages(config)
|
|
200
|
+
if not modules_import_packages:
|
|
201
|
+
modules_import_packages = ["dskity.modules"]
|
|
202
|
+
app.state.modules_import_packages = modules_import_packages
|
|
203
|
+
|
|
204
|
+
discovered_by_name: dict[str, Any] = {}
|
|
205
|
+
for package in modules_import_packages:
|
|
206
|
+
try:
|
|
207
|
+
package_registry = ModuleRegistry.from_package(package)
|
|
208
|
+
except ModuleNotFoundError:
|
|
209
|
+
continue
|
|
210
|
+
|
|
211
|
+
for module in package_registry.modules:
|
|
212
|
+
discovered_by_name.setdefault(module.meta.name, module)
|
|
213
|
+
|
|
214
|
+
if not discovered_by_name:
|
|
215
|
+
logger.debug(
|
|
216
|
+
"No modules found in modules_search_paths=%s.",
|
|
217
|
+
modules_import_packages,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
registry = ModuleRegistry(modules=tuple(discovered_by_name.values()))
|
|
221
|
+
if target_modules:
|
|
222
|
+
enabled_modules = [m for m in registry.modules if m.meta.name in target_modules]
|
|
223
|
+
app.state.target_modules = sorted(target_modules)
|
|
224
|
+
else:
|
|
225
|
+
enabled_modules = list(registry.enabled_modules(config))
|
|
226
|
+
|
|
227
|
+
loaded_module_names = [m.meta.name for m in enabled_modules]
|
|
228
|
+
if loaded_module_names:
|
|
229
|
+
logger.info("Modules loaded successfully in API: %s", loaded_module_names)
|
|
230
|
+
else:
|
|
231
|
+
logger.warning(
|
|
232
|
+
"No enabled modules were loaded into the API; modules_search_paths=%s",
|
|
233
|
+
app.state.modules_import_packages,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
app.state.enabled_modules = [
|
|
237
|
+
EnabledModuleInfo(name=m.meta.name, base_path=m.meta.base_path) for m in enabled_modules
|
|
238
|
+
]
|
|
239
|
+
|
|
240
|
+
# Create an object grouping transport clients available to modules.
|
|
241
|
+
mqtt_client = MQTTClient() # lightweight singleton — does not auto-connect
|
|
242
|
+
grpc_client = GRPCClient()
|
|
243
|
+
clients = TransportClients(http=app, grpc=grpc_client, mqtt=mqtt_client)
|
|
244
|
+
|
|
245
|
+
for module in enabled_modules:
|
|
246
|
+
module.register(clients=clients, config=config)
|
|
247
|
+
|
|
248
|
+
# If there is a shared store (kvstore enabled), expose discovery endpoints
|
|
249
|
+
# and auto-register modules using a base_url inferred from requests.
|
|
250
|
+
if getattr(app.state, "registry_store", None) is not None:
|
|
251
|
+
app.include_router(registry_router)
|
|
252
|
+
app.add_middleware(RegistryAdvertiseMiddleware)
|
|
253
|
+
|
|
254
|
+
existing_lifespan = getattr(app.router, "lifespan_context", None)
|
|
255
|
+
|
|
256
|
+
@asynccontextmanager
|
|
257
|
+
async def _lifespan(inner_app: FastAPI):
|
|
258
|
+
if callable(existing_lifespan):
|
|
259
|
+
async with existing_lifespan(inner_app):
|
|
260
|
+
start_heartbeat(
|
|
261
|
+
inner_app,
|
|
262
|
+
cfg=HeartbeatConfig(
|
|
263
|
+
ttl_seconds=inner_app.state.registry_ttl_seconds,
|
|
264
|
+
interval_seconds=inner_app.state.registry_heartbeat_interval_seconds,
|
|
265
|
+
),
|
|
266
|
+
)
|
|
267
|
+
try:
|
|
268
|
+
yield
|
|
269
|
+
finally:
|
|
270
|
+
await stop_heartbeat(inner_app)
|
|
271
|
+
else:
|
|
272
|
+
start_heartbeat(
|
|
273
|
+
inner_app,
|
|
274
|
+
cfg=HeartbeatConfig(
|
|
275
|
+
ttl_seconds=inner_app.state.registry_ttl_seconds,
|
|
276
|
+
interval_seconds=inner_app.state.registry_heartbeat_interval_seconds,
|
|
277
|
+
),
|
|
278
|
+
)
|
|
279
|
+
try:
|
|
280
|
+
yield
|
|
281
|
+
finally:
|
|
282
|
+
await stop_heartbeat(inner_app)
|
|
283
|
+
|
|
284
|
+
app.router.lifespan_context = _lifespan
|
|
285
|
+
|
|
286
|
+
@app.get("/")
|
|
287
|
+
def root() -> dict:
|
|
288
|
+
enabled = [m.meta.name for m in enabled_modules]
|
|
289
|
+
return {"service": "dskity", "enabled_modules": enabled}
|
|
290
|
+
|
|
291
|
+
# Correlation id por request (X-Request-Id).
|
|
292
|
+
# Precisa ser o último middleware adicionado para ficar mais externo e cobrir
|
|
293
|
+
# também os middlewares HTTP (BaseHTTPMiddleware), garantindo request_id nos access logs.
|
|
294
|
+
install_request_id(app)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import uvicorn
|
|
7
|
+
|
|
8
|
+
from dskity.config.loader import resolve_config_path
|
|
9
|
+
from dskity.logging import configure_logging
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _parse_targets(values: list[str] | None) -> list[str]:
|
|
13
|
+
if not values:
|
|
14
|
+
return []
|
|
15
|
+
|
|
16
|
+
parts: list[str] = []
|
|
17
|
+
for v in values:
|
|
18
|
+
if not isinstance(v, str):
|
|
19
|
+
continue
|
|
20
|
+
for p in v.split(","):
|
|
21
|
+
p = p.strip()
|
|
22
|
+
if p:
|
|
23
|
+
parts.append(p)
|
|
24
|
+
|
|
25
|
+
# mantém ordem (remove duplicados)
|
|
26
|
+
seen: set[str] = set()
|
|
27
|
+
ordered: list[str] = []
|
|
28
|
+
for p in parts:
|
|
29
|
+
if p in seen:
|
|
30
|
+
continue
|
|
31
|
+
seen.add(p)
|
|
32
|
+
ordered.append(p)
|
|
33
|
+
return ordered
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main(argv: list[str] | None = None) -> int:
|
|
37
|
+
parser = argparse.ArgumentParser(prog="dskity")
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--config",
|
|
40
|
+
"-c",
|
|
41
|
+
dest="config_path",
|
|
42
|
+
default=None,
|
|
43
|
+
help="Path to a TOML or YAML config file that overrides the defaults",
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument("--host", "-H", default=None)
|
|
46
|
+
parser.add_argument("--port", "-p", type=int, default=None)
|
|
47
|
+
parser.add_argument(
|
|
48
|
+
"--advertise-url",
|
|
49
|
+
dest="advertise_url",
|
|
50
|
+
default=None,
|
|
51
|
+
help="URL advertised in service discovery (if different from listen host/port)",
|
|
52
|
+
)
|
|
53
|
+
parser.add_argument(
|
|
54
|
+
"--target",
|
|
55
|
+
"-t",
|
|
56
|
+
dest="targets",
|
|
57
|
+
action="append",
|
|
58
|
+
default=None,
|
|
59
|
+
help=(
|
|
60
|
+
"List of modules to enable (overrides YAML). "
|
|
61
|
+
"Accepts CSV (e.g. echo,health) and can be repeated (e.g. -t echo -t health)."
|
|
62
|
+
),
|
|
63
|
+
)
|
|
64
|
+
args = parser.parse_args(argv)
|
|
65
|
+
|
|
66
|
+
config_path = resolve_config_path(args.config_path)
|
|
67
|
+
|
|
68
|
+
# Garante que o bootstrap use o YAML escolhido.
|
|
69
|
+
os.environ["DSKITY_CONFIG"] = config_path
|
|
70
|
+
|
|
71
|
+
targets = _parse_targets(args.targets)
|
|
72
|
+
if targets:
|
|
73
|
+
os.environ["DSKITY_TARGETS"] = ",".join(targets)
|
|
74
|
+
else:
|
|
75
|
+
os.environ.pop("DSKITY_TARGETS", None)
|
|
76
|
+
|
|
77
|
+
# Base URL anunciada para discovery (inferida a partir do host/port escolhidos).
|
|
78
|
+
host = args.host or "0.0.0.0"
|
|
79
|
+
port = args.port or 8000
|
|
80
|
+
if args.advertise_url:
|
|
81
|
+
advertise_url = args.advertise_url or f"http://{host}:{port}"
|
|
82
|
+
os.environ["DSKITY_ADVERTISE_URL"] = advertise_url
|
|
83
|
+
|
|
84
|
+
log_config = configure_logging()
|
|
85
|
+
|
|
86
|
+
uvicorn.run(
|
|
87
|
+
"dskity.app:app",
|
|
88
|
+
host=host,
|
|
89
|
+
port=port,
|
|
90
|
+
reload=True,
|
|
91
|
+
env_file=None,
|
|
92
|
+
log_level="info",
|
|
93
|
+
log_config=log_config,
|
|
94
|
+
)
|
|
95
|
+
return 0
|
|
File without changes
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import tomllib
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
from .settings import DSkitySettings, load_config_from_yaml
|
|
11
|
+
|
|
12
|
+
DEFAULT_CONFIG_FILENAME = "settings.toml"
|
|
13
|
+
FALLBACK_CONFIG_FILENAME = "settings.yaml"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _default_config_candidates() -> tuple[Path, Path]:
|
|
17
|
+
cwd = Path.cwd()
|
|
18
|
+
return (cwd / DEFAULT_CONFIG_FILENAME, cwd / FALLBACK_CONFIG_FILENAME)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _default_config_path() -> Path:
|
|
22
|
+
toml_path, yaml_path = _default_config_candidates()
|
|
23
|
+
if toml_path.exists():
|
|
24
|
+
return toml_path
|
|
25
|
+
if yaml_path.exists():
|
|
26
|
+
return yaml_path
|
|
27
|
+
return toml_path
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_config_path(cli_path: str | None) -> str:
|
|
31
|
+
if cli_path:
|
|
32
|
+
return cli_path
|
|
33
|
+
env_path = os.getenv("DSKITY_CONFIG")
|
|
34
|
+
if env_path:
|
|
35
|
+
return env_path
|
|
36
|
+
return str(_default_config_path())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
|
|
40
|
+
result: dict[str, Any] = dict(base)
|
|
41
|
+
for key, value in override.items():
|
|
42
|
+
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
43
|
+
result[key] = _deep_merge(result[key], value)
|
|
44
|
+
else:
|
|
45
|
+
result[key] = value
|
|
46
|
+
return result
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _read_config_file(path: str | Path, *, optional: bool = False) -> dict[str, Any]:
|
|
50
|
+
path = Path(path)
|
|
51
|
+
if not path.exists():
|
|
52
|
+
if optional:
|
|
53
|
+
return {}
|
|
54
|
+
raise FileNotFoundError(path)
|
|
55
|
+
|
|
56
|
+
if path.suffix.lower() == ".toml":
|
|
57
|
+
with open(path, "rb") as f:
|
|
58
|
+
data = tomllib.load(f) or {}
|
|
59
|
+
else:
|
|
60
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
61
|
+
data = yaml.safe_load(f) or {}
|
|
62
|
+
|
|
63
|
+
if not isinstance(data, dict):
|
|
64
|
+
raise ValueError(f"Config must be a top-level mapping: {path}")
|
|
65
|
+
return data
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def load_config(override_path: str | None = None) -> DSkitySettings:
|
|
69
|
+
"""Load configuration with support for TOML, YAML and environment variables.
|
|
70
|
+
|
|
71
|
+
Precedence (highest to lowest):
|
|
72
|
+
1. Environment variables (DSKITY_*)
|
|
73
|
+
2. Override file (--config)
|
|
74
|
+
3. settings.toml (or settings.yaml as fallback) in current directory
|
|
75
|
+
4. Default values
|
|
76
|
+
|
|
77
|
+
Environment variables:
|
|
78
|
+
- Prefix: DSKITY_
|
|
79
|
+
- Hierarchy separator: __ (two underscores)
|
|
80
|
+
|
|
81
|
+
Examples:
|
|
82
|
+
- DSKITY_COMMON__INTERNAL_BASE_URL="http://api.example.com"
|
|
83
|
+
- DSKITY_KV__STORE="redis"
|
|
84
|
+
- DSKITY_MODULES__PERSON__DATABASE__URL="postgresql://user:pass@localhost/db"
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
override_path: Optional path to an override YAML/TOML file
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
DSkitySettings with all values validated
|
|
91
|
+
"""
|
|
92
|
+
default_path = _default_config_path()
|
|
93
|
+
base = _read_config_file(default_path, optional=True)
|
|
94
|
+
|
|
95
|
+
# If an override is provided, perform a deep merge (override > default settings.toml/settings.yaml)
|
|
96
|
+
if override_path:
|
|
97
|
+
override_path_obj = Path(override_path)
|
|
98
|
+
if override_path_obj.resolve() == default_path.resolve():
|
|
99
|
+
config_dict = _read_config_file(override_path_obj, optional=True)
|
|
100
|
+
else:
|
|
101
|
+
override = _read_config_file(override_path_obj, optional=False)
|
|
102
|
+
config_dict = _deep_merge(base, override)
|
|
103
|
+
else:
|
|
104
|
+
config_dict = base
|
|
105
|
+
|
|
106
|
+
# Pass config_dict to load_config_from_yaml
|
|
107
|
+
# which creates a DSkitySettings instance with env vars taking precedence
|
|
108
|
+
return load_config_from_yaml(config_dict)
|