uns-kit 0.2.2__tar.gz → 0.2.5__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 (66) hide show
  1. {uns_kit-0.2.2 → uns_kit-0.2.5}/PKG-INFO +62 -11
  2. {uns_kit-0.2.2 → uns_kit-0.2.5}/README.md +60 -9
  3. {uns_kit-0.2.2 → uns_kit-0.2.5}/pyproject.toml +2 -2
  4. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/__init__.py +22 -0
  5. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/api/event_routing.py +0 -3
  6. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/__init__.py +22 -0
  7. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/datahub_client.py +104 -1
  8. uns_kit-0.2.5/src/uns_kit/core/runtime_service_registration.py +103 -0
  9. uns_kit-0.2.5/src/uns_kit/core/service_token_provider.py +69 -0
  10. uns_kit-0.2.5/src/uns_kit/core/state.py +53 -0
  11. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/topic_builder.py +0 -1
  12. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/database/schema.py +10 -1
  13. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/README.md +1 -1
  14. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/api/__init__.py +0 -0
  15. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/api/data_catalog.py +0 -0
  16. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/api/interfaces.py +0 -0
  17. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/api/proxy.py +0 -0
  18. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/cli.py +0 -0
  19. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/auth_client.py +0 -0
  20. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/client.py +3 -3
  21. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/config_file.py +0 -0
  22. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/config_schema.py +0 -0
  23. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/events.py +0 -0
  24. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/logger.py +0 -0
  25. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/packet.py +0 -0
  26. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/proxy.py +0 -0
  27. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/proxy_process.py +0 -0
  28. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/proxy_process_sync.py +0 -0
  29. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/runtime_metadata.py +0 -0
  30. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/secret_resolver.py +0 -0
  31. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/secure_store.py +0 -0
  32. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/status_monitor.py +0 -0
  33. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/topic_matcher.py +0 -0
  34. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/uns_mqtt_proxy.py +0 -0
  35. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/core/uns_path.py +0 -0
  36. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/cron/__init__.py +0 -0
  37. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/cron/proxy.py +0 -0
  38. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/database/__init__.py +0 -0
  39. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/database/client.py +0 -0
  40. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/database/params.py +0 -0
  41. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/database/sql.py +0 -0
  42. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/database/types.py +0 -0
  43. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/service_bundle.py +0 -0
  44. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/api/src/api_routes.py +0 -0
  45. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/api/src/main.py +0 -0
  46. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/azure-pipelines.yml +0 -0
  47. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/cron/src/cron_example.py +0 -0
  48. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/data-offer/src/api_routes.py +0 -0
  49. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/data-offer/src/data_offers/__init__.py +0 -0
  50. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/data-offer/src/data_offers/demo_coils.py +0 -0
  51. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/data-offer/src/data_offers/demo_export.py +0 -0
  52. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/data-offer/src/data_offers/sql/demo_coils.sql +0 -0
  53. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/data-offer/src/data_offers/sql/demo_export.sql +0 -0
  54. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/data-offer/src/main.py +0 -0
  55. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/.gitignore +0 -0
  56. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/package.json +0 -0
  57. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/pyproject.toml +0 -0
  58. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/runtime.json +0 -0
  59. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/src/config/project_config_extension.example.py +0 -0
  60. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/src/config/project_config_extension.py +0 -0
  61. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/default/src/main.py +0 -0
  62. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/vscode/extensions.json +0 -0
  63. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/vscode/launch.json +0 -0
  64. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/vscode/settings.json +0 -0
  65. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/templates/workspace/workspace.json +0 -0
  66. {uns_kit-0.2.2 → uns_kit-0.2.5}/src/uns_kit/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: uns-kit
3
- Version: 0.2.2
3
+ Version: 0.2.5
4
4
  Summary: Lightweight Python UNS MQTT client (pub/sub + infra topics)
5
5
  License: MIT
6
6
  Author: Aljoša Vister
@@ -27,7 +27,7 @@ Requires-Dist: oracledb (>=2.5.1,<3.0.0) ; extra == "database"
27
27
  Requires-Dist: pandas (>=2.3.3,<3.0.0) ; extra == "api"
28
28
  Requires-Dist: psycopg[binary] (>=3.2.9,<4.0.0) ; extra == "database"
29
29
  Requires-Dist: pyarrow (>=21.0.0,<22.0.0) ; extra == "api"
30
- Requires-Dist: pyjwt[crypto] (>=2.10.1,<3.0.0) ; extra == "api"
30
+ Requires-Dist: pyjwt[crypto] (>=2.13.0,<3.0.0) ; extra == "api"
31
31
  Requires-Dist: uvicorn (>=0.35.0,<0.36.0) ; extra == "api"
32
32
  Description-Content-Type: text/markdown
33
33
 
@@ -271,19 +271,19 @@ separate physical table family while the UNS path still comes from
271
271
 
272
272
  ### Datahub client (last value + history)
273
273
 
274
- `UnsClient` provides a minimal REST client for the UNS Datahub API, including batch last-value, single-topic catch-all history, and batch range endpoints. For service-to-service access, prefer passing a long-lived service token directly. Use `AuthClient` only when you need user-style login/refresh from `config.json`.
274
+ `UnsClient` provides a minimal REST client for the UNS OpenHub API, including batch last-value, single-topic catch-all history, and batch range endpoints. A controller-managed RTT service should use `ServiceTokenProvider`; it reads the short-lived token file mounted by the controller for every request. Direct local development can use `.env`/exported `UNS_SERVICE_TOKEN`, a resolved `uns.token`, or an explicit `AuthClient` fallback.
275
275
 
276
276
  ```python
277
277
  import pandas as pd
278
278
  from pathlib import Path
279
- from uns_kit.core import ConfigFile, UnsClient
279
+ from uns_kit.core import ConfigFile, ServiceTokenProvider, UnsClient
280
280
  import io
281
281
 
282
282
  cfg = ConfigFile.load_config(Path("config.json"))
283
283
  client = UnsClient(
284
284
  cfg["uns"]["rest"],
285
285
  api_base_path="/api",
286
- token=cfg["uns"].get("token"),
286
+ token_provider=ServiceTokenProvider(config_token=cfg["uns"].get("token")),
287
287
  )
288
288
 
289
289
  values = client.last_value([
@@ -327,20 +327,71 @@ batch_history = client.history(
327
327
  print(batch_history.by_topic)
328
328
  ```
329
329
 
330
- If your service token comes from an environment variable or secret store, resolve it before constructing the client:
330
+ When several modules in one application use the same REST client, register it
331
+ once during startup and retrieve the same named instance wherever it is needed:
331
332
 
332
333
  ```python
333
- import os
334
- from uns_kit.core import UnsClient
334
+ from uns_kit import ServiceTokenProvider, get_uns_client, register_uns_client
335
+
336
+ # application startup
337
+ register_uns_client(
338
+ cfg["uns"]["rest"],
339
+ token_provider=ServiceTokenProvider(config_token=cfg["uns"].get("token")),
340
+ )
341
+
342
+ # handler or another application module
343
+ client = get_uns_client()
344
+ values = client.last_value("raw/data/line-1/motor/main/temperature")
345
+ ```
346
+
347
+ Use distinct names when the application needs clients for more than one UNS
348
+ OpenHub endpoint: `register_uns_client(url, name="secondary")` and
349
+ `get_uns_client("secondary")`.
350
+
351
+ For a directly started local service, load its `.env` by the application and use the provider. Do not set `RTT_NODE` or `RTT_INSTANCE_ID` yourself; those identifiers are injected only by the controller.
352
+
353
+ ```python
354
+ from uns_kit.core import ServiceTokenProvider, UnsClient
335
355
 
336
356
  client = UnsClient(
337
357
  "https://datahub.example.com",
338
- token=os.environ["UNS_SERVICE_TOKEN"],
358
+ token_provider=ServiceTokenProvider(),
359
+ )
360
+ ```
361
+
362
+ After a Python service has successfully started its MQTT/API runtime, it can register its non-secret descriptor when managed by the controller. This is a no-op in direct local development:
363
+
364
+ ```python
365
+ from uns_kit.core import RuntimeServiceDescriptor, register_service
366
+
367
+ register_service(
368
+ client,
369
+ RuntimeServiceDescriptor(
370
+ id="uns-example",
371
+ version="1.2.3",
372
+ capabilities=["example-api"],
373
+ health_contract="service-metadata-v1",
374
+ process_name="uns-example",
375
+ ),
339
376
  )
340
377
  ```
341
378
 
342
379
  For larger service API and data-offer examples, use `configure-data-offer`. The scaffold uses `await register_api_catalog(...)` in `src/main.py`, while `src/api_routes.py` holds the `service_apis` and `data_offer_sources` definitions together with their handlers.
343
380
 
381
+ ### Shared application state
382
+
383
+ `State` is a thread-safe, in-memory key/value store shared by every module in
384
+ one Python process. It is not persisted and starts empty after every restart.
385
+
386
+ ```python
387
+ from uns_kit import State
388
+
389
+ state = State()
390
+ state.set("mark_machine", {"plateID": "P123"})
391
+ plate = state.get("mark_machine")
392
+ state.pop("mark_machine")
393
+ ```
394
+
344
395
  ## Config placeholders (env + Infisical)
345
396
  `uns-py` now resolves config placeholders in the same style as `uns-core`.
346
397
  For Infisical placeholders, install the optional extra:
@@ -417,7 +468,7 @@ poetry install
417
468
  poetry run python src/main.py
418
469
  ```
419
470
 
420
- The generated `package.json` declares `unsDatahub.kind: "addon"` and controller compatibility so tagged releases can be discovered by UNS Datahub controllers.
471
+ The generated `package.json` declares `unsDatahub.kind: "addon"` and controller compatibility so tagged releases can be discovered by UNS OpenHub controllers.
421
472
 
422
473
  To add optional feature scaffolding later:
423
474
  ```bash
@@ -432,7 +483,7 @@ For an existing Python project, add the current non-destructive package metadata
432
483
  poetry run uns-kit-py upgrade .
433
484
  ```
434
485
 
435
- The command adds the UNS Datahub add-on marker only when `unsDatahub` is absent and preserves existing metadata.
486
+ The command adds the UNS OpenHub add-on marker only when `unsDatahub` is absent and preserves existing metadata.
436
487
 
437
488
  `configure-api` adds a service-API scaffold:
438
489
  - `src/main.py`
@@ -238,19 +238,19 @@ separate physical table family while the UNS path still comes from
238
238
 
239
239
  ### Datahub client (last value + history)
240
240
 
241
- `UnsClient` provides a minimal REST client for the UNS Datahub API, including batch last-value, single-topic catch-all history, and batch range endpoints. For service-to-service access, prefer passing a long-lived service token directly. Use `AuthClient` only when you need user-style login/refresh from `config.json`.
241
+ `UnsClient` provides a minimal REST client for the UNS OpenHub API, including batch last-value, single-topic catch-all history, and batch range endpoints. A controller-managed RTT service should use `ServiceTokenProvider`; it reads the short-lived token file mounted by the controller for every request. Direct local development can use `.env`/exported `UNS_SERVICE_TOKEN`, a resolved `uns.token`, or an explicit `AuthClient` fallback.
242
242
 
243
243
  ```python
244
244
  import pandas as pd
245
245
  from pathlib import Path
246
- from uns_kit.core import ConfigFile, UnsClient
246
+ from uns_kit.core import ConfigFile, ServiceTokenProvider, UnsClient
247
247
  import io
248
248
 
249
249
  cfg = ConfigFile.load_config(Path("config.json"))
250
250
  client = UnsClient(
251
251
  cfg["uns"]["rest"],
252
252
  api_base_path="/api",
253
- token=cfg["uns"].get("token"),
253
+ token_provider=ServiceTokenProvider(config_token=cfg["uns"].get("token")),
254
254
  )
255
255
 
256
256
  values = client.last_value([
@@ -294,20 +294,71 @@ batch_history = client.history(
294
294
  print(batch_history.by_topic)
295
295
  ```
296
296
 
297
- If your service token comes from an environment variable or secret store, resolve it before constructing the client:
297
+ When several modules in one application use the same REST client, register it
298
+ once during startup and retrieve the same named instance wherever it is needed:
298
299
 
299
300
  ```python
300
- import os
301
- from uns_kit.core import UnsClient
301
+ from uns_kit import ServiceTokenProvider, get_uns_client, register_uns_client
302
+
303
+ # application startup
304
+ register_uns_client(
305
+ cfg["uns"]["rest"],
306
+ token_provider=ServiceTokenProvider(config_token=cfg["uns"].get("token")),
307
+ )
308
+
309
+ # handler or another application module
310
+ client = get_uns_client()
311
+ values = client.last_value("raw/data/line-1/motor/main/temperature")
312
+ ```
313
+
314
+ Use distinct names when the application needs clients for more than one UNS
315
+ OpenHub endpoint: `register_uns_client(url, name="secondary")` and
316
+ `get_uns_client("secondary")`.
317
+
318
+ For a directly started local service, load its `.env` by the application and use the provider. Do not set `RTT_NODE` or `RTT_INSTANCE_ID` yourself; those identifiers are injected only by the controller.
319
+
320
+ ```python
321
+ from uns_kit.core import ServiceTokenProvider, UnsClient
302
322
 
303
323
  client = UnsClient(
304
324
  "https://datahub.example.com",
305
- token=os.environ["UNS_SERVICE_TOKEN"],
325
+ token_provider=ServiceTokenProvider(),
326
+ )
327
+ ```
328
+
329
+ After a Python service has successfully started its MQTT/API runtime, it can register its non-secret descriptor when managed by the controller. This is a no-op in direct local development:
330
+
331
+ ```python
332
+ from uns_kit.core import RuntimeServiceDescriptor, register_service
333
+
334
+ register_service(
335
+ client,
336
+ RuntimeServiceDescriptor(
337
+ id="uns-example",
338
+ version="1.2.3",
339
+ capabilities=["example-api"],
340
+ health_contract="service-metadata-v1",
341
+ process_name="uns-example",
342
+ ),
306
343
  )
307
344
  ```
308
345
 
309
346
  For larger service API and data-offer examples, use `configure-data-offer`. The scaffold uses `await register_api_catalog(...)` in `src/main.py`, while `src/api_routes.py` holds the `service_apis` and `data_offer_sources` definitions together with their handlers.
310
347
 
348
+ ### Shared application state
349
+
350
+ `State` is a thread-safe, in-memory key/value store shared by every module in
351
+ one Python process. It is not persisted and starts empty after every restart.
352
+
353
+ ```python
354
+ from uns_kit import State
355
+
356
+ state = State()
357
+ state.set("mark_machine", {"plateID": "P123"})
358
+ plate = state.get("mark_machine")
359
+ state.pop("mark_machine")
360
+ ```
361
+
311
362
  ## Config placeholders (env + Infisical)
312
363
  `uns-py` now resolves config placeholders in the same style as `uns-core`.
313
364
  For Infisical placeholders, install the optional extra:
@@ -384,7 +435,7 @@ poetry install
384
435
  poetry run python src/main.py
385
436
  ```
386
437
 
387
- The generated `package.json` declares `unsDatahub.kind: "addon"` and controller compatibility so tagged releases can be discovered by UNS Datahub controllers.
438
+ The generated `package.json` declares `unsDatahub.kind: "addon"` and controller compatibility so tagged releases can be discovered by UNS OpenHub controllers.
388
439
 
389
440
  To add optional feature scaffolding later:
390
441
  ```bash
@@ -399,7 +450,7 @@ For an existing Python project, add the current non-destructive package metadata
399
450
  poetry run uns-kit-py upgrade .
400
451
  ```
401
452
 
402
- The command adds the UNS Datahub add-on marker only when `unsDatahub` is absent and preserves existing metadata.
453
+ The command adds the UNS OpenHub add-on marker only when `unsDatahub` is absent and preserves existing metadata.
403
454
 
404
455
  `configure-api` adds a service-API scaffold:
405
456
  - `src/main.py`
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "uns-kit"
3
- version = "0.2.2"
3
+ version = "0.2.5"
4
4
  description = "Lightweight Python UNS MQTT client (pub/sub + infra topics)"
5
5
  authors = ["Aljoša Vister <aljosa.vister@gmail.com>"]
6
6
  license = "MIT"
@@ -16,7 +16,7 @@ graypy = "^2.1.0"
16
16
  fastapi = { version = "^0.116.1", optional = true }
17
17
  uvicorn = { version = "^0.35.0", optional = true }
18
18
  apscheduler = { version = "^3.11.0", optional = true }
19
- pyjwt = { version = "^2.10.1", extras = ["crypto"], optional = true }
19
+ pyjwt = { version = "^2.13.0", extras = ["crypto"], optional = true }
20
20
  psycopg = { version = "^3.2.9", extras = ["binary"], optional = true }
21
21
  oracledb = { version = "^2.5.1", optional = true }
22
22
  pandas = { version = "^2.3.3", optional = true }
@@ -11,6 +11,7 @@ from .api import (
11
11
  UnsApiProxy,
12
12
  )
13
13
  from .core import (
14
+ AccessTokenProvider,
14
15
  AuthClient,
15
16
  BatchRangeResponse,
16
17
  BatchRangeTopicResult,
@@ -18,6 +19,7 @@ from .core import (
18
19
  ConfigFile,
19
20
  DataPayload,
20
21
  FileStore,
22
+ UnsClientManager,
21
23
  HostResolverOptions,
22
24
  InfisicalResolverOptions,
23
25
  LastValueResult,
@@ -29,6 +31,8 @@ from .core import (
29
31
  SecretResolverOptions,
30
32
  SecureStore,
31
33
  SecureStoreFactory,
34
+ ServiceTokenProvider,
35
+ State,
32
36
  StatusMonitor,
33
37
  TablePayload,
34
38
  TopicBuilder,
@@ -41,6 +45,9 @@ from .core import (
41
45
  UnsProcessParameters,
42
46
  UnsProxyProcess,
43
47
  UnsProxyProcessSync,
48
+ RuntimeServiceDescriptor,
49
+ RuntimeServiceRegistration,
50
+ RuntimeServiceRegistrationClient,
44
51
  base_config_schema,
45
52
  boolean_schema,
46
53
  build_uns_identity_path,
@@ -51,6 +58,10 @@ from .core import (
51
58
  integer_schema,
52
59
  load_project_extras_schema,
53
60
  resolve_infisical_config,
61
+ register_service,
62
+ register_uns_client,
63
+ get_uns_client,
64
+ delete_uns_client,
54
65
  secret_value_schema,
55
66
  strict_object,
56
67
  string_schema,
@@ -127,6 +138,12 @@ __all__ = [
127
138
  "CronSchedule",
128
139
  "CronScheduleInput",
129
140
  "UnsClient",
141
+ "UnsClientManager",
142
+ "AccessTokenProvider",
143
+ "ServiceTokenProvider",
144
+ "register_uns_client",
145
+ "get_uns_client",
146
+ "delete_uns_client",
130
147
  "AuthClient",
131
148
  "RawResponse",
132
149
  "RangeQuery",
@@ -135,9 +152,14 @@ __all__ = [
135
152
  "BatchRangeResponse",
136
153
  "LastValueResult",
137
154
  "ClientError",
155
+ "RuntimeServiceDescriptor",
156
+ "RuntimeServiceRegistration",
157
+ "RuntimeServiceRegistrationClient",
158
+ "register_service",
138
159
  "SecureStore",
139
160
  "SecureStoreFactory",
140
161
  "FileStore",
162
+ "State",
141
163
  "build_uns_identity_path",
142
164
  "build_uns_route_path",
143
165
  "DatabaseDialect",
@@ -5,9 +5,6 @@ from typing import Any, Callable, Mapping
5
5
  from .interfaces import (
6
6
  ApiInteractionDefinition,
7
7
  ApiInteractionMethod,
8
- DataCatalogOfferRegistration,
9
- DataCatalogOfferSourceRegistration,
10
- ServiceApiRegistration,
11
8
  build_api_interaction_topic_path,
12
9
  build_api_interactions_from_data_offer_sources,
13
10
  build_data_catalog_offers_from_sources,
@@ -33,6 +33,12 @@ __all__ = [
33
33
  "UnsParameters",
34
34
  "UnsMqttProxySync",
35
35
  "UnsClient",
36
+ "UnsClientManager",
37
+ "AccessTokenProvider",
38
+ "ServiceTokenProvider",
39
+ "register_uns_client",
40
+ "get_uns_client",
41
+ "delete_uns_client",
36
42
  "AuthClient",
37
43
  "RawResponse",
38
44
  "RangeQuery",
@@ -41,6 +47,10 @@ __all__ = [
41
47
  "BatchRangeResponse",
42
48
  "LastValueResult",
43
49
  "ClientError",
50
+ "RuntimeServiceDescriptor",
51
+ "RuntimeServiceRegistration",
52
+ "RuntimeServiceRegistrationClient",
53
+ "register_service",
44
54
  "SecureStore",
45
55
  "SecureStoreFactory",
46
56
  "FileStore",
@@ -52,6 +62,7 @@ __all__ = [
52
62
  "build_uns_route_path",
53
63
  "configure_logger",
54
64
  "get_logger",
65
+ "State",
55
66
  ]
56
67
 
57
68
  _LAZY_EXPORTS: dict[str, tuple[str, str]] = {
@@ -85,6 +96,12 @@ _LAZY_EXPORTS: dict[str, tuple[str, str]] = {
85
96
  "UnsParameters": ("uns_kit.core.proxy_process", "UnsParameters"),
86
97
  "UnsMqttProxySync": ("uns_kit.core.proxy_process_sync", "UnsMqttProxySync"),
87
98
  "UnsClient": ("uns_kit.core.datahub_client", "UnsClient"),
99
+ "UnsClientManager": ("uns_kit.core.datahub_client", "UnsClientManager"),
100
+ "AccessTokenProvider": ("uns_kit.core.service_token_provider", "AccessTokenProvider"),
101
+ "ServiceTokenProvider": ("uns_kit.core.service_token_provider", "ServiceTokenProvider"),
102
+ "register_uns_client": ("uns_kit.core.datahub_client", "register_uns_client"),
103
+ "get_uns_client": ("uns_kit.core.datahub_client", "get_uns_client"),
104
+ "delete_uns_client": ("uns_kit.core.datahub_client", "delete_uns_client"),
88
105
  "AuthClient": ("uns_kit.core.auth_client", "AuthClient"),
89
106
  "RawResponse": ("uns_kit.core.datahub_client", "RawResponse"),
90
107
  "RangeQuery": ("uns_kit.core.datahub_client", "RangeQuery"),
@@ -93,6 +110,10 @@ _LAZY_EXPORTS: dict[str, tuple[str, str]] = {
93
110
  "BatchRangeResponse": ("uns_kit.core.datahub_client", "BatchRangeResponse"),
94
111
  "LastValueResult": ("uns_kit.core.datahub_client", "LastValueResult"),
95
112
  "ClientError": ("uns_kit.core.datahub_client", "ClientError"),
113
+ "RuntimeServiceDescriptor": ("uns_kit.core.runtime_service_registration", "RuntimeServiceDescriptor"),
114
+ "RuntimeServiceRegistration": ("uns_kit.core.runtime_service_registration", "RuntimeServiceRegistration"),
115
+ "RuntimeServiceRegistrationClient": ("uns_kit.core.runtime_service_registration", "RuntimeServiceRegistrationClient"),
116
+ "register_service": ("uns_kit.core.runtime_service_registration", "register_service"),
96
117
  "SecureStore": ("uns_kit.core.secure_store", "SecureStore"),
97
118
  "SecureStoreFactory": ("uns_kit.core.secure_store", "SecureStoreFactory"),
98
119
  "FileStore": ("uns_kit.core.secure_store", "FileStore"),
@@ -104,6 +125,7 @@ _LAZY_EXPORTS: dict[str, tuple[str, str]] = {
104
125
  "build_uns_route_path": ("uns_kit.core.uns_path", "build_uns_route_path"),
105
126
  "configure_logger": ("uns_kit.core.logger", "configure_logger"),
106
127
  "get_logger": ("uns_kit.core.logger", "get_logger"),
128
+ "State": ("uns_kit.core.state", "State"),
107
129
  }
108
130
 
109
131
 
@@ -4,10 +4,12 @@ import json
4
4
  import urllib.error
5
5
  import urllib.parse
6
6
  import urllib.request
7
+ import threading
7
8
  from dataclasses import dataclass
8
9
  from typing import Any, Literal, Mapping, Optional, Sequence, TYPE_CHECKING, TypedDict, Unpack
9
10
 
10
11
  from .auth_client import AuthClient
12
+ from .service_token_provider import AccessTokenProvider
11
13
 
12
14
  if TYPE_CHECKING:
13
15
  import pandas as pd
@@ -190,6 +192,7 @@ class UnsClient:
190
192
  *,
191
193
  api_base_path: str = "/api",
192
194
  token: Optional[str] = None,
195
+ token_provider: Optional[AccessTokenProvider] = None,
193
196
  auth_client: Optional[AuthClient] = None,
194
197
  timeout: float = 10.0,
195
198
  ) -> None:
@@ -202,20 +205,29 @@ class UnsClient:
202
205
  self.base_url = stripped_base_url
203
206
  self.api_url = f"{stripped_base_url}{self.api_base_path}"
204
207
  self.manual_access_token = token
208
+ self.access_token = token
209
+ self.token_provider = token_provider
205
210
  self.timeout = timeout
206
211
  self.auth_client = auth_client
207
212
  self._opener = urllib.request.build_opener()
208
213
 
209
214
  def set_token(self, token: Optional[str]) -> None:
210
215
  self.manual_access_token = token
216
+ self.access_token = token
211
217
 
212
218
  def ensure_token(self) -> Optional[str]:
213
219
  if self.manual_access_token:
214
220
  return self.manual_access_token
221
+ if self.token_provider:
222
+ service_token = self.token_provider.get_access_token()
223
+ if service_token:
224
+ self.access_token = service_token
225
+ return service_token
215
226
  try:
216
227
  if self.auth_client is None:
217
228
  self.auth_client = AuthClient.create()
218
- return self.auth_client.get_access_token()
229
+ self.access_token = self.auth_client.get_access_token()
230
+ return self.access_token
219
231
 
220
232
  except Exception as exc:
221
233
  raise RuntimeError("No access token available, please login again.") from exc
@@ -415,3 +427,94 @@ class UnsClient:
415
427
  return ""
416
428
  return stripped if stripped.startswith("/") else f"/{stripped}"
417
429
 
430
+
431
+ class UnsClientManager:
432
+ """Process-local registry for sharing configured :class:`UnsClient` instances."""
433
+
434
+ def __init__(self) -> None:
435
+ self._clients: dict[str, UnsClient] = {}
436
+ self._lock = threading.RLock()
437
+
438
+ def register(
439
+ self,
440
+ name: str,
441
+ base_url: str,
442
+ *,
443
+ api_base_path: str = "/api",
444
+ token: Optional[str] = None,
445
+ token_provider: Optional[AccessTokenProvider] = None,
446
+ auth_client: Optional[AuthClient] = None,
447
+ timeout: float = 10.0,
448
+ ) -> UnsClient:
449
+ client = UnsClient(
450
+ base_url,
451
+ api_base_path=api_base_path,
452
+ token=token,
453
+ token_provider=token_provider,
454
+ auth_client=auth_client,
455
+ timeout=timeout,
456
+ )
457
+ with self._lock:
458
+ self._clients[_normalize_client_name(name)] = client
459
+ return client
460
+
461
+ def get(self, name: str = "default") -> UnsClient:
462
+ normalized_name = _normalize_client_name(name)
463
+ with self._lock:
464
+ client = self._clients.get(normalized_name)
465
+ if client is None:
466
+ raise RuntimeError(
467
+ f"UNS client '{normalized_name}' is not registered. "
468
+ "Call register_uns_client() during application startup."
469
+ )
470
+ return client
471
+
472
+ def delete(self, name: str = "default") -> None:
473
+ with self._lock:
474
+ self._clients.pop(_normalize_client_name(name), None)
475
+
476
+ def clear(self) -> None:
477
+ with self._lock:
478
+ self._clients.clear()
479
+
480
+
481
+ def _normalize_client_name(name: str) -> str:
482
+ normalized_name = name.strip()
483
+ if not normalized_name:
484
+ raise ValueError("UNS client name must not be empty.")
485
+ return normalized_name
486
+
487
+
488
+ _default_uns_client_manager = UnsClientManager()
489
+
490
+
491
+ def register_uns_client(
492
+ base_url: str,
493
+ *,
494
+ name: str = "default",
495
+ api_base_path: str = "/api",
496
+ token: Optional[str] = None,
497
+ token_provider: Optional[AccessTokenProvider] = None,
498
+ auth_client: Optional[AuthClient] = None,
499
+ timeout: float = 10.0,
500
+ ) -> UnsClient:
501
+ """Create or replace a named process-local UNS REST client."""
502
+ return _default_uns_client_manager.register(
503
+ name,
504
+ base_url,
505
+ api_base_path=api_base_path,
506
+ token=token,
507
+ token_provider=token_provider,
508
+ auth_client=auth_client,
509
+ timeout=timeout,
510
+ )
511
+
512
+
513
+ def get_uns_client(name: str = "default") -> UnsClient:
514
+ """Return a named client previously registered during application startup."""
515
+ return _default_uns_client_manager.get(name)
516
+
517
+
518
+ def delete_uns_client(name: str = "default") -> None:
519
+ """Remove a named client from the process-local registry."""
520
+ _default_uns_client_manager.delete(name)
@@ -0,0 +1,103 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from dataclasses import dataclass
5
+ from typing import Any, Mapping, Optional, Protocol, Sequence
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class RuntimeServiceDescriptor:
10
+ """Non-secret description sent by a controller-managed RTT service."""
11
+
12
+ id: str
13
+ version: Optional[str] = None
14
+ capabilities: Optional[Sequence[str]] = None
15
+ health_contract: Optional[str] = None
16
+ process_name: Optional[str] = None
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class RuntimeServiceRegistration:
21
+ registered: bool
22
+ rtt_node: str
23
+ instance_id: str
24
+ rest_path: str
25
+ graphql_path: str
26
+ service_version: Optional[str] = None
27
+
28
+
29
+ class RuntimeServiceRegistrationClient(Protocol):
30
+ def post(self, endpoint: str, data: Optional[dict[str, Any]] = None) -> dict[str, Any]: ...
31
+
32
+
33
+ def register_service(
34
+ client: RuntimeServiceRegistrationClient,
35
+ service: RuntimeServiceDescriptor,
36
+ *,
37
+ environment: Optional[Mapping[str, str]] = None,
38
+ ) -> Optional[RuntimeServiceRegistration]:
39
+ """Register only controller-launched RTT services.
40
+
41
+ Direct development intentionally has no controller-injected RTT identity,
42
+ so the function returns ``None`` and never attempts registration.
43
+ """
44
+
45
+ env = environment if environment is not None else os.environ
46
+ rtt_node = _optional_string(env.get("RTT_NODE"))
47
+ instance_id = _optional_string(env.get("RTT_INSTANCE_ID"))
48
+ if not rtt_node or not instance_id:
49
+ return None
50
+
51
+ service_id = _optional_string(service.id)
52
+ if not service_id:
53
+ raise ValueError("Runtime service registration requires service.id.")
54
+ if service_id != rtt_node:
55
+ raise ValueError("Runtime service id does not match the controller-injected RTT_NODE.")
56
+
57
+ capabilities = _normalize_string_list(service.capabilities)
58
+ payload: dict[str, Any] = {"rttNode": rtt_node, "instanceId": instance_id}
59
+ if service_version := _optional_string(service.version):
60
+ payload["serviceVersion"] = service_version
61
+ if capabilities:
62
+ payload["capabilities"] = capabilities
63
+ if health_contract := _optional_string(service.health_contract):
64
+ payload["healthContract"] = health_contract
65
+ if process_name := _optional_string(service.process_name):
66
+ payload["processName"] = process_name
67
+
68
+ return _parse_registration(client.post("runtime-services/register", payload))
69
+
70
+
71
+ def _parse_registration(payload: Mapping[str, Any]) -> RuntimeServiceRegistration:
72
+ service = payload.get("service")
73
+ controller = payload.get("controller")
74
+ service_values = service if isinstance(service, Mapping) else {}
75
+ controller_values = controller if isinstance(controller, Mapping) else {}
76
+ rtt_node = _optional_string(service_values.get("rttNode"))
77
+ instance_id = _optional_string(service_values.get("instanceId"))
78
+ rest_path = _optional_string(controller_values.get("restPath"))
79
+ graphql_path = _optional_string(controller_values.get("graphqlPath"))
80
+ if payload.get("registered") is not True or not rtt_node or not instance_id or not rest_path or not graphql_path:
81
+ raise RuntimeError("Controller returned an invalid runtime service registration response.")
82
+ return RuntimeServiceRegistration(
83
+ registered=True,
84
+ rtt_node=rtt_node,
85
+ instance_id=instance_id,
86
+ rest_path=rest_path,
87
+ graphql_path=graphql_path,
88
+ service_version=_optional_string(service_values.get("serviceVersion")),
89
+ )
90
+
91
+
92
+ def _optional_string(value: object) -> Optional[str]:
93
+ normalized = value.strip() if isinstance(value, str) else ""
94
+ return normalized or None
95
+
96
+
97
+ def _normalize_string_list(values: Optional[Sequence[str]]) -> list[str]:
98
+ normalized: list[str] = []
99
+ for value in values or ():
100
+ candidate = _optional_string(value)
101
+ if candidate and candidate not in normalized:
102
+ normalized.append(candidate)
103
+ return normalized
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Callable, Mapping, Optional, Protocol
6
+
7
+
8
+ class AccessTokenProvider(Protocol):
9
+ """Minimal bearer-token source shared by service clients."""
10
+
11
+ def get_access_token(self) -> Optional[str]: ...
12
+
13
+
14
+ class ServiceTokenProvider:
15
+ """Resolve controller-managed service credentials without storing a user token.
16
+
17
+ A controller-mounted token file is deliberately authoritative and is read on
18
+ every request, so a controller can rotate the service token atomically
19
+ without restarting its RTT process. Direct local development can instead
20
+ supply ``UNS_SERVICE_TOKEN``, a resolved ``uns.token``, or a legacy login
21
+ provider.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ *,
27
+ token_file: Optional[str] = None,
28
+ environment: Optional[Mapping[str, str]] = None,
29
+ config_token: Optional[str] = None,
30
+ fallback: Optional[AccessTokenProvider] = None,
31
+ read_text: Optional[Callable[[str], str]] = None,
32
+ ) -> None:
33
+ self._token_file = _normalize_token(token_file)
34
+ self._environment = environment if environment is not None else os.environ
35
+ self._config_token = _normalize_token(config_token)
36
+ self._fallback = fallback
37
+ self._read_text = read_text or _read_token_file
38
+
39
+ def get_access_token(self) -> Optional[str]:
40
+ token_file = self._token_file or _normalize_token(self._environment.get("UNS_SERVICE_TOKEN_FILE"))
41
+ if token_file:
42
+ return self._read_controller_managed_token(token_file)
43
+
44
+ environment_token = _normalize_token(self._environment.get("UNS_SERVICE_TOKEN"))
45
+ if environment_token:
46
+ return environment_token
47
+
48
+ if self._config_token:
49
+ return self._config_token
50
+
51
+ return self._fallback.get_access_token() if self._fallback else None
52
+
53
+ def _read_controller_managed_token(self, path: str) -> str:
54
+ try:
55
+ token = _normalize_token(self._read_text(path))
56
+ if not token:
57
+ raise ValueError("empty token file")
58
+ return token
59
+ except Exception as exc:
60
+ raise RuntimeError("Controller-managed service token file is unavailable.") from exc
61
+
62
+
63
+ def _read_token_file(path: str) -> str:
64
+ return Path(path).read_text(encoding="utf-8")
65
+
66
+
67
+ def _normalize_token(value: Optional[str]) -> Optional[str]:
68
+ token = value.strip() if isinstance(value, str) else ""
69
+ return token or None
@@ -0,0 +1,53 @@
1
+ """Thread-safe, process-local application state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from typing import Any
7
+
8
+
9
+ class State:
10
+ """A shared in-memory key/value store for one Python process.
11
+
12
+ Every ``State()`` call returns the same object. State is intentionally not
13
+ persisted and is therefore cleared whenever the process restarts.
14
+ """
15
+
16
+ _instance: "State | None" = None
17
+ _instance_lock = threading.Lock()
18
+ _values: dict[str, Any]
19
+ _lock: threading.RLock
20
+
21
+ def __new__(cls) -> "State":
22
+ with cls._instance_lock:
23
+ if cls._instance is None:
24
+ instance = super().__new__(cls)
25
+ instance._values = {}
26
+ instance._lock = threading.RLock()
27
+ cls._instance = instance
28
+ return cls._instance
29
+
30
+ def set(self, key: str, value: Any) -> None:
31
+ """Store ``value`` under ``key``."""
32
+ with self._lock:
33
+ self._values[key] = value
34
+
35
+ def get(self, key: str, default: Any = None) -> Any:
36
+ """Return the value for ``key``, or ``default`` when it is absent."""
37
+ with self._lock:
38
+ return self._values.get(key, default)
39
+
40
+ def pop(self, key: str, default: Any = None) -> Any:
41
+ """Remove and return the value for ``key``, or ``default`` when absent."""
42
+ with self._lock:
43
+ return self._values.pop(key, default)
44
+
45
+ def clear(self) -> None:
46
+ """Remove every stored value."""
47
+ with self._lock:
48
+ self._values.clear()
49
+
50
+ def snapshot(self) -> dict[str, Any]:
51
+ """Return a shallow copy of the current state."""
52
+ with self._lock:
53
+ return dict(self._values)
@@ -1,7 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import re
4
- from pathlib import Path
5
4
 
6
5
  from ..version import __package_name__, __version__
7
6
  from .runtime_metadata import RUNTIME_METADATA
@@ -2,7 +2,16 @@ from __future__ import annotations
2
2
 
3
3
  from typing import Any, TypedDict
4
4
 
5
- from ..core.config_schema import any_of, boolean_schema, enum_schema, host_value_schema, integer_schema, record_schema, secret_value_schema, strict_object, string_schema
5
+ from ..core.config_schema import (
6
+ any_of,
7
+ boolean_schema,
8
+ host_value_schema,
9
+ integer_schema,
10
+ record_schema,
11
+ secret_value_schema,
12
+ strict_object,
13
+ string_schema,
14
+ )
6
15
 
7
16
 
8
17
  class PostgresDatabaseConfig(TypedDict, total=False):
@@ -63,7 +63,7 @@ These CLI helpers are useful for diagnostics and low-level checks. For applicati
63
63
 
64
64
  ## Datahub client (last value)
65
65
 
66
- `UnsClient` provides a minimal REST client for the UNS Datahub API, including the batch last-value endpoint. For service-to-service access, prefer passing a long-lived service token directly. Use `AuthClient` only when you need user login/refresh behavior.
66
+ `UnsClient` provides a minimal REST client for the UNS OpenHub API, including the batch last-value endpoint. For service-to-service access, prefer passing a long-lived service token directly. Use `AuthClient` only when you need user login/refresh behavior.
67
67
 
68
68
  ```python
69
69
  from pathlib import Path
File without changes
@@ -4,17 +4,17 @@ import asyncio
4
4
  import contextlib
5
5
  from contextlib import asynccontextmanager
6
6
  from datetime import datetime, timezone
7
- import uuid
8
7
  import socket
9
8
  from typing import AsyncIterator, List, Optional
9
+ import uuid
10
10
 
11
11
  import aiomqtt
12
12
 
13
- MqttError = aiomqtt.MqttError
14
-
15
13
  from .packet import UnsPacket
16
14
  from .topic_builder import TopicBuilder
17
15
 
16
+ MqttError = aiomqtt.MqttError
17
+
18
18
 
19
19
  class UnsMqttClient:
20
20
  _exception_handler_installed = False
File without changes