rusticai-nats 1.2.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.
- rusticai_nats-1.2.0/PKG-INFO +35 -0
- rusticai_nats-1.2.0/README.md +17 -0
- rusticai_nats-1.2.0/pyproject.toml +78 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/__init__.py +0 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/agent_ext/__init__.py +0 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/agent_ext/kvstore.py +84 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/messaging/__init__.py +19 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/messaging/backend.py +110 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/messaging/connection_manager.py +187 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/messaging/exceptions.py +7 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/messaging/message_store.py +333 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/messaging/pubsub_manager.py +513 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/messaging/retry_utils.py +126 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/state/__init__.py +0 -0
- rusticai_nats-1.2.0/src/rustic_ai/nats/state/manager.py +86 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rusticai-nats
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: NATS messaging backend for Rustic AI
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Author: Dragonscale Industries Inc.
|
|
7
|
+
Author-email: dev@dragonscale.ai
|
|
8
|
+
Requires-Python: >=3.13,<3.14
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Provides-Extra: test
|
|
12
|
+
Requires-Dist: nats-py (>=2.9.0,<3.0.0)
|
|
13
|
+
Requires-Dist: rusticai-core (>=1.2.0,<1.3.0)
|
|
14
|
+
Project-URL: Homepage, https://www.rustic.ai/
|
|
15
|
+
Project-URL: Repository, https://github.com/dragonscale-ai/rustic-ai
|
|
16
|
+
Project-URL: Rustic AI Core, https://pypi.org/project/rusticai-core/
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# Rustic AI NATS
|
|
20
|
+
|
|
21
|
+
This module provides a [NATS](https://nats.io/) Jetstream based implementations of [Rustic AI](https://www.rustic.ai/)'s messaging backend, key value store, etc.
|
|
22
|
+
|
|
23
|
+
## Installing
|
|
24
|
+
|
|
25
|
+
```shell
|
|
26
|
+
pip install rusticai-nats
|
|
27
|
+
```
|
|
28
|
+
**Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/)
|
|
29
|
+
|
|
30
|
+
## Building from Source
|
|
31
|
+
|
|
32
|
+
```shell
|
|
33
|
+
poetry install --with dev
|
|
34
|
+
poetry build
|
|
35
|
+
```
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Rustic AI NATS
|
|
2
|
+
|
|
3
|
+
This module provides a [NATS](https://nats.io/) Jetstream based implementations of [Rustic AI](https://www.rustic.ai/)'s messaging backend, key value store, etc.
|
|
4
|
+
|
|
5
|
+
## Installing
|
|
6
|
+
|
|
7
|
+
```shell
|
|
8
|
+
pip install rusticai-nats
|
|
9
|
+
```
|
|
10
|
+
**Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/)
|
|
11
|
+
|
|
12
|
+
## Building from Source
|
|
13
|
+
|
|
14
|
+
```shell
|
|
15
|
+
poetry install --with dev
|
|
16
|
+
poetry build
|
|
17
|
+
```
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["poetry-core"]
|
|
3
|
+
build-backend = "poetry.core.masonry.api"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rusticai-nats"
|
|
7
|
+
version = "1.2.0"
|
|
8
|
+
description = "NATS messaging backend for Rustic AI"
|
|
9
|
+
authors = [
|
|
10
|
+
{ name = "Dragonscale Industries Inc.", email = "dev@dragonscale.ai" },
|
|
11
|
+
]
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
readme = "README.md"
|
|
14
|
+
requires-python = ">=3.13,<3.14"
|
|
15
|
+
dynamic = ["dependencies"]
|
|
16
|
+
urls = { Homepage = "https://www.rustic.ai/", Repository = "https://github.com/dragonscale-ai/rustic-ai", "Rustic AI Core" = "https://pypi.org/project/rusticai-core/" }
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
[tool.poetry]
|
|
20
|
+
packages = [{ include = "rustic_ai", from = "src" }]
|
|
21
|
+
|
|
22
|
+
[tool.poetry.dependencies]
|
|
23
|
+
rusticai-core = { version = "1.2.0"}
|
|
24
|
+
nats-py = "^2.9.0"
|
|
25
|
+
|
|
26
|
+
[tool.poetry-monorepo.deps]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
[tool.poetry.group.dev]
|
|
30
|
+
optional = true
|
|
31
|
+
|
|
32
|
+
[tool.poetry.group.dev.dependencies]
|
|
33
|
+
pytest = "^8.3.4"
|
|
34
|
+
black = { version = "^24.2.0", extras = ["jupyter"] }
|
|
35
|
+
flake8 = "^7.1.2"
|
|
36
|
+
tox = "^4.24.1"
|
|
37
|
+
isort = "^6.0.0"
|
|
38
|
+
mypy = "^1.15.0"
|
|
39
|
+
flaky = "^3.8.1"
|
|
40
|
+
pytest-asyncio = "^0.26.0"
|
|
41
|
+
pytest-xdist = "^3.6.1"
|
|
42
|
+
rusticai-testing = { version = "1.2.0"}
|
|
43
|
+
|
|
44
|
+
[tool.poetry.extras]
|
|
45
|
+
test = ["pytest"]
|
|
46
|
+
|
|
47
|
+
[tool.black]
|
|
48
|
+
line-length = 120
|
|
49
|
+
target-version = ['py313']
|
|
50
|
+
include = '\.pyi?$'
|
|
51
|
+
exclude = '''
|
|
52
|
+
/(
|
|
53
|
+
\.git
|
|
54
|
+
| \.mypy_cache
|
|
55
|
+
| \.tox
|
|
56
|
+
| \.venv
|
|
57
|
+
| _build
|
|
58
|
+
| buck-out
|
|
59
|
+
| build
|
|
60
|
+
| dist
|
|
61
|
+
)/
|
|
62
|
+
'''
|
|
63
|
+
|
|
64
|
+
[tool.mypy]
|
|
65
|
+
python_version = "3.13"
|
|
66
|
+
ignore_missing_imports = true
|
|
67
|
+
check_untyped_defs = true
|
|
68
|
+
plugins = "pydantic.mypy"
|
|
69
|
+
explicit_package_bases = true
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
[tool.isort]
|
|
73
|
+
profile = "black"
|
|
74
|
+
force_sort_within_sections = true # For the sorting order issues
|
|
75
|
+
lines_between_sections = 1 # For the newline issue
|
|
76
|
+
known_third_party = ["pydantic"]
|
|
77
|
+
known_first_party = ["rustic_ai.core"]
|
|
78
|
+
known_local_folder = ["rustic_ai.testing"]
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""NATS KV-backed agent key-value store."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from rustic_ai.core.guild.agent_ext.depends.dependency_resolver import (
|
|
7
|
+
DependencyResolver,
|
|
8
|
+
)
|
|
9
|
+
from rustic_ai.core.guild.agent_ext.depends.kvstore.base import BaseKVStore
|
|
10
|
+
from rustic_ai.nats.messaging.connection_manager import (
|
|
11
|
+
NATSBackendConfig,
|
|
12
|
+
NATSConnectionManager,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _sanitize(name: str) -> str:
|
|
17
|
+
"""Replace characters not valid in NATS KV key tokens with underscores."""
|
|
18
|
+
return re.sub(r"[^a-zA-Z0-9\-_]", "_", name)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class NATSKVStore(BaseKVStore):
|
|
22
|
+
"""Agent KV store backed by a NATS JetStream KV bucket.
|
|
23
|
+
|
|
24
|
+
All agents share a single bucket ('agent-kvstore'). Each agent's
|
|
25
|
+
entries are prefixed with '{org_id}.{guild_id}.{agent_id}.' so they
|
|
26
|
+
are logically isolated, mirroring how Redis scopes by hash key.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
KV_BUCKET = "agent-kvstore"
|
|
30
|
+
|
|
31
|
+
def __init__(self, kv, run_async, org_id: str, guild_id: str, agent_id: str):
|
|
32
|
+
self._kv = kv
|
|
33
|
+
self._run_async = run_async
|
|
34
|
+
self._prefix = f"{_sanitize(org_id)}.{_sanitize(guild_id)}.{_sanitize(agent_id)}"
|
|
35
|
+
|
|
36
|
+
def _full_key(self, key: str) -> str:
|
|
37
|
+
return f"{self._prefix}.{_sanitize(key)}"
|
|
38
|
+
|
|
39
|
+
def get(self, key: str):
|
|
40
|
+
try:
|
|
41
|
+
entry = self._run_async(self._kv.get(self._full_key(key)))
|
|
42
|
+
return json.loads(entry.value.decode("utf-8"))
|
|
43
|
+
except Exception:
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
def set(self, key: str, value) -> None:
|
|
47
|
+
self._run_async(self._kv.put(self._full_key(key), json.dumps(value).encode("utf-8")))
|
|
48
|
+
|
|
49
|
+
def delete(self, key: str) -> None:
|
|
50
|
+
try:
|
|
51
|
+
self._run_async(self._kv.delete(self._full_key(key)))
|
|
52
|
+
except Exception:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class NATSKVStoreResolver(DependencyResolver[NATSKVStore]):
|
|
57
|
+
"""Resolves NATSKVStore instances for agents, sharing a single NATS connection."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, **kwargs) -> None:
|
|
60
|
+
super().__init__()
|
|
61
|
+
config = NATSBackendConfig.model_validate(kwargs)
|
|
62
|
+
self._connection_mgr = NATSConnectionManager(config)
|
|
63
|
+
self._js = self._connection_mgr.get_js()
|
|
64
|
+
self._run_async = self._connection_mgr.run_async
|
|
65
|
+
self._kv = self._run_async(self._ensure_bucket_async())
|
|
66
|
+
|
|
67
|
+
async def _ensure_bucket_async(self):
|
|
68
|
+
import nats.js.api
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
return await self._js.create_key_value(
|
|
72
|
+
nats.js.api.KeyValueConfig(bucket=NATSKVStore.KV_BUCKET)
|
|
73
|
+
)
|
|
74
|
+
except Exception:
|
|
75
|
+
return await self._js.key_value(NATSKVStore.KV_BUCKET)
|
|
76
|
+
|
|
77
|
+
def resolve(self, org_id: str, guild_id: str, agent_id: str) -> NATSKVStore:
|
|
78
|
+
return NATSKVStore(
|
|
79
|
+
kv=self._kv,
|
|
80
|
+
run_async=self._run_async,
|
|
81
|
+
org_id=org_id,
|
|
82
|
+
guild_id=guild_id,
|
|
83
|
+
agent_id=agent_id,
|
|
84
|
+
)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""NATS messaging backend module."""
|
|
2
|
+
|
|
3
|
+
from rustic_ai.nats.messaging.backend import NATSMessagingBackend
|
|
4
|
+
from rustic_ai.nats.messaging.connection_manager import NATSBackendConfig
|
|
5
|
+
from rustic_ai.nats.messaging.exceptions import NATSConnectionFailureError
|
|
6
|
+
from rustic_ai.nats.messaging.retry_utils import (
|
|
7
|
+
apply_jitter,
|
|
8
|
+
calculate_exponential_backoff,
|
|
9
|
+
execute_with_retry,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"NATSMessagingBackend",
|
|
14
|
+
"NATSBackendConfig",
|
|
15
|
+
"NATSConnectionFailureError",
|
|
16
|
+
"apply_jitter",
|
|
17
|
+
"calculate_exponential_backoff",
|
|
18
|
+
"execute_with_retry",
|
|
19
|
+
]
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""NATS messaging backend facade."""
|
|
2
|
+
|
|
3
|
+
from typing import Callable, Dict, List, Optional, Set, Union
|
|
4
|
+
|
|
5
|
+
from rustic_ai.core.messaging.core.message import Message
|
|
6
|
+
from rustic_ai.core.messaging.core.messaging_backend import MessagingBackend
|
|
7
|
+
from rustic_ai.core.utils import GemstoneID
|
|
8
|
+
from rustic_ai.nats.messaging.connection_manager import (
|
|
9
|
+
NATSBackendConfig,
|
|
10
|
+
NATSConnectionManager,
|
|
11
|
+
)
|
|
12
|
+
from rustic_ai.nats.messaging.message_store import NATSMessageStore
|
|
13
|
+
from rustic_ai.nats.messaging.pubsub_manager import NATSPubSubManager
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NATSMessagingBackend(MessagingBackend):
|
|
17
|
+
"""NATS implementation of the MessagingBackend interface."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, nats_client: Union[object, NATSBackendConfig, dict]) -> None:
|
|
20
|
+
"""
|
|
21
|
+
Initialize with a NATS client, config, or dict.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
nats_client: A NATS client instance, NATSBackendConfig, or configuration dict.
|
|
25
|
+
"""
|
|
26
|
+
# Initialize connection manager (creates async event loop bridge)
|
|
27
|
+
self._connection_manager = NATSConnectionManager(nats_client)
|
|
28
|
+
|
|
29
|
+
config = self._connection_manager.get_config()
|
|
30
|
+
|
|
31
|
+
# Initialize message store
|
|
32
|
+
self._message_store = NATSMessageStore(
|
|
33
|
+
self._connection_manager.get_js(),
|
|
34
|
+
self._connection_manager.run_async,
|
|
35
|
+
config,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
# Initialize pub/sub manager (pass js + ensure_stream for per-client push consumers)
|
|
39
|
+
self._pubsub_manager = NATSPubSubManager(
|
|
40
|
+
self._connection_manager.get_client(),
|
|
41
|
+
self._connection_manager.get_js(),
|
|
42
|
+
self._connection_manager.run_async,
|
|
43
|
+
config,
|
|
44
|
+
ensure_stream=self._message_store._ensure_stream,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
self._pubsub_manager.setup()
|
|
48
|
+
|
|
49
|
+
def store_message(self, namespace: str, topic: str, message: Message) -> None:
|
|
50
|
+
"""Store a message durably and publish for real-time notification."""
|
|
51
|
+
self._message_store.store_message(namespace, topic, message, self._pubsub_manager.publish)
|
|
52
|
+
|
|
53
|
+
def get_messages_for_topic(self, topic: str) -> List[Message]:
|
|
54
|
+
"""Retrieve all messages for a given topic."""
|
|
55
|
+
return self._message_store.get_messages_for_topic(topic)
|
|
56
|
+
|
|
57
|
+
def get_messages_for_topic_since(self, topic: str, msg_id_since: int) -> List[Message]:
|
|
58
|
+
"""Retrieve all messages for a given topic since a given message ID."""
|
|
59
|
+
return self._message_store.get_messages_for_topic_since(topic, msg_id_since)
|
|
60
|
+
|
|
61
|
+
def get_next_message_for_topic_since(self, topic: str, last_message_id: int) -> Optional[Message]:
|
|
62
|
+
"""Retrieve the next message for a given topic since a given message ID."""
|
|
63
|
+
return self._message_store.get_next_message_for_topic_since(topic, last_message_id)
|
|
64
|
+
|
|
65
|
+
def load_subscribers(self, namespace: str) -> Dict[str, Set[str]]:
|
|
66
|
+
"""Load subscribers for a namespace (TBD implementation)."""
|
|
67
|
+
return {}
|
|
68
|
+
|
|
69
|
+
def subscribe(
|
|
70
|
+
self,
|
|
71
|
+
topic: str,
|
|
72
|
+
handler: Callable[[Message], None],
|
|
73
|
+
client_id: Optional[str] = None,
|
|
74
|
+
namespace: Optional[str] = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
"""Subscribe to a topic.
|
|
77
|
+
|
|
78
|
+
When client_id is provided, uses per-client durable push consumer with delivery guarantees.
|
|
79
|
+
"""
|
|
80
|
+
self._pubsub_manager.subscribe(topic, handler, client_id=client_id, namespace=namespace)
|
|
81
|
+
|
|
82
|
+
def unsubscribe(self, topic: str, client_id: Optional[str] = None) -> None:
|
|
83
|
+
"""Unsubscribe from a topic."""
|
|
84
|
+
self._pubsub_manager.unsubscribe(topic, client_id=client_id)
|
|
85
|
+
|
|
86
|
+
def cleanup(self) -> None:
|
|
87
|
+
"""Clean up all resources."""
|
|
88
|
+
self._pubsub_manager.cleanup()
|
|
89
|
+
self._connection_manager.close()
|
|
90
|
+
|
|
91
|
+
def supports_subscription(self) -> bool:
|
|
92
|
+
"""NATS supports pub/sub subscriptions."""
|
|
93
|
+
return True
|
|
94
|
+
|
|
95
|
+
def get_messages_by_id(self, namespace: str, msg_ids: List[int]) -> List[Message]:
|
|
96
|
+
"""Retrieve messages by their IDs."""
|
|
97
|
+
return self._message_store.get_messages_by_id(namespace, msg_ids)
|
|
98
|
+
|
|
99
|
+
def set_failure_callback(self, callback: Optional[Callable[[Exception], None]]) -> None:
|
|
100
|
+
"""Set a custom failure callback for testing purposes."""
|
|
101
|
+
self._pubsub_manager.set_failure_callback(callback)
|
|
102
|
+
|
|
103
|
+
def _get_timestamp_for_id(self, msg_id: int) -> float:
|
|
104
|
+
"""Helper to retrieve the timestamp for a given message ID."""
|
|
105
|
+
return GemstoneID.from_int(msg_id).timestamp
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def _config(self) -> Optional[NATSBackendConfig]:
|
|
109
|
+
"""Get the NATS configuration (for testing purposes)."""
|
|
110
|
+
return self._connection_manager.get_config()
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""NATS connection manager - provides async-to-sync bridge for nats-py."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import ssl
|
|
6
|
+
import threading
|
|
7
|
+
from typing import Optional, Union
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, Field
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NATSBackendConfig(BaseModel):
|
|
13
|
+
"""Configuration for the NATS messaging backend."""
|
|
14
|
+
|
|
15
|
+
servers: list = Field(default_factory=lambda: ["nats://localhost:4222"])
|
|
16
|
+
name: Optional[str] = Field(default=None)
|
|
17
|
+
user: Optional[str] = Field(default=None)
|
|
18
|
+
password: Optional[str] = Field(default=None)
|
|
19
|
+
token: Optional[str] = Field(default=None)
|
|
20
|
+
tls: bool = Field(default=False)
|
|
21
|
+
connect_timeout: float = Field(default=10.0)
|
|
22
|
+
reconnect_time_wait: float = Field(default=2.0)
|
|
23
|
+
max_reconnect_attempts: int = Field(default=-1)
|
|
24
|
+
ping_interval: int = Field(default=120)
|
|
25
|
+
max_outstanding_pings: int = Field(default=2)
|
|
26
|
+
|
|
27
|
+
# Pub/sub retry and reconnection settings
|
|
28
|
+
pubsub_retry_enabled: bool = Field(default=True)
|
|
29
|
+
pubsub_retry_initial_delay: float = Field(default=1.0)
|
|
30
|
+
pubsub_retry_max_delay: float = Field(default=60.0)
|
|
31
|
+
pubsub_retry_multiplier: float = Field(default=2.0)
|
|
32
|
+
pubsub_health_check_interval: float = Field(default=10.0)
|
|
33
|
+
|
|
34
|
+
# Immediate retry settings
|
|
35
|
+
pubsub_immediate_retry_attempts: int = Field(default=3)
|
|
36
|
+
pubsub_immediate_retry_delay: float = Field(default=0.1)
|
|
37
|
+
pubsub_immediate_retry_multiplier: float = Field(default=2.0)
|
|
38
|
+
|
|
39
|
+
# Fail-fast settings
|
|
40
|
+
pubsub_max_retry_attempts: int = Field(default=5)
|
|
41
|
+
pubsub_max_retry_time: float = Field(default=300.0)
|
|
42
|
+
pubsub_crash_on_failure: bool = Field(default=True)
|
|
43
|
+
|
|
44
|
+
# Health monitoring settings
|
|
45
|
+
pubsub_health_monitoring_enabled: bool = Field(default=True)
|
|
46
|
+
pubsub_health_monitor_initial_delay: float = Field(default=1.0)
|
|
47
|
+
|
|
48
|
+
# Message TTL in seconds
|
|
49
|
+
message_ttl: int = Field(default=3600)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class NATSConnectionManager:
|
|
53
|
+
"""Manages NATS connection lifecycle with async-to-sync bridge."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, nats_client: Union[object, NATSBackendConfig, dict]) -> None:
|
|
56
|
+
"""
|
|
57
|
+
Initialize the connection manager.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
nats_client: A NATS client instance, NATSBackendConfig, or dict.
|
|
61
|
+
Dict with "nats_client" key uses the provided client directly.
|
|
62
|
+
Other dicts are converted to NATSBackendConfig.
|
|
63
|
+
"""
|
|
64
|
+
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
|
65
|
+
self._loop_thread: Optional[threading.Thread] = None
|
|
66
|
+
self._owns_loop: bool = False
|
|
67
|
+
self._client = None
|
|
68
|
+
self._js = None
|
|
69
|
+
self._config: Optional[NATSBackendConfig] = None
|
|
70
|
+
self._owns_client: bool = False
|
|
71
|
+
|
|
72
|
+
if isinstance(nats_client, dict):
|
|
73
|
+
if "nats_client" in nats_client:
|
|
74
|
+
actual_client = nats_client["nats_client"]
|
|
75
|
+
if not hasattr(actual_client, "jetstream"):
|
|
76
|
+
raise ValueError("nats_client in dict must be a NATS client instance")
|
|
77
|
+
# Use the client's event loop
|
|
78
|
+
self._loop = getattr(actual_client, "_loop", None)
|
|
79
|
+
self._client = actual_client
|
|
80
|
+
self._owns_client = False
|
|
81
|
+
self._owns_loop = False
|
|
82
|
+
else:
|
|
83
|
+
# Convert dict to NATSBackendConfig
|
|
84
|
+
nats_client = NATSBackendConfig(**nats_client)
|
|
85
|
+
|
|
86
|
+
if isinstance(nats_client, NATSBackendConfig):
|
|
87
|
+
self._config = nats_client
|
|
88
|
+
self._start_event_loop()
|
|
89
|
+
self._client = self.run_async(self._connect(nats_client))
|
|
90
|
+
self._owns_client = True
|
|
91
|
+
elif hasattr(nats_client, "jetstream") and self._client is None:
|
|
92
|
+
# Pre-connected NATS client
|
|
93
|
+
self._loop = getattr(nats_client, "_loop", None)
|
|
94
|
+
self._client = nats_client
|
|
95
|
+
self._owns_client = False
|
|
96
|
+
self._owns_loop = False
|
|
97
|
+
elif self._client is None:
|
|
98
|
+
raise ValueError("Invalid NATS client: must be NATSBackendConfig, dict, or NATS client instance")
|
|
99
|
+
|
|
100
|
+
# If we have a client but no loop yet (loop extracted from client), ensure we can run async ops
|
|
101
|
+
if self._loop is None:
|
|
102
|
+
self._start_event_loop()
|
|
103
|
+
|
|
104
|
+
# Get JetStream context (synchronous)
|
|
105
|
+
self._js = self._client.jetstream()
|
|
106
|
+
|
|
107
|
+
def _start_event_loop(self) -> None:
|
|
108
|
+
"""Start a dedicated event loop in a daemon thread."""
|
|
109
|
+
self._loop = asyncio.new_event_loop()
|
|
110
|
+
self._loop_thread = threading.Thread(
|
|
111
|
+
target=self._loop.run_forever,
|
|
112
|
+
daemon=True,
|
|
113
|
+
name="nats-event-loop",
|
|
114
|
+
)
|
|
115
|
+
self._loop_thread.start()
|
|
116
|
+
self._owns_loop = True
|
|
117
|
+
|
|
118
|
+
def run_async(self, coro, timeout: int = 30):
|
|
119
|
+
"""Run an async coroutine synchronously using the dedicated event loop.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
coro: Coroutine to execute
|
|
123
|
+
timeout: Timeout in seconds
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
The result of the coroutine
|
|
127
|
+
"""
|
|
128
|
+
if self._loop is None:
|
|
129
|
+
raise RuntimeError("Event loop not initialized")
|
|
130
|
+
future = asyncio.run_coroutine_threadsafe(coro, self._loop)
|
|
131
|
+
return future.result(timeout=timeout)
|
|
132
|
+
|
|
133
|
+
async def _connect(self, config: NATSBackendConfig):
|
|
134
|
+
"""Async helper to connect to NATS."""
|
|
135
|
+
import nats as nats_module
|
|
136
|
+
|
|
137
|
+
kwargs: dict = {
|
|
138
|
+
"servers": config.servers,
|
|
139
|
+
"connect_timeout": config.connect_timeout,
|
|
140
|
+
"reconnect_time_wait": config.reconnect_time_wait,
|
|
141
|
+
"max_reconnect_attempts": config.max_reconnect_attempts,
|
|
142
|
+
"ping_interval": config.ping_interval,
|
|
143
|
+
"max_outstanding_pings": config.max_outstanding_pings,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if config.name:
|
|
147
|
+
kwargs["name"] = config.name
|
|
148
|
+
if config.user:
|
|
149
|
+
kwargs["user"] = config.user
|
|
150
|
+
if config.password:
|
|
151
|
+
kwargs["password"] = config.password
|
|
152
|
+
if config.token:
|
|
153
|
+
kwargs["token"] = config.token
|
|
154
|
+
if config.tls:
|
|
155
|
+
tls_context = ssl.create_default_context()
|
|
156
|
+
kwargs["tls"] = tls_context
|
|
157
|
+
|
|
158
|
+
return await nats_module.connect(**kwargs)
|
|
159
|
+
|
|
160
|
+
def get_client(self):
|
|
161
|
+
"""Get the NATS client instance."""
|
|
162
|
+
return self._client
|
|
163
|
+
|
|
164
|
+
def get_js(self):
|
|
165
|
+
"""Get the JetStream context."""
|
|
166
|
+
return self._js
|
|
167
|
+
|
|
168
|
+
def get_config(self) -> Optional[NATSBackendConfig]:
|
|
169
|
+
"""Get the configuration if available."""
|
|
170
|
+
return self._config
|
|
171
|
+
|
|
172
|
+
def close(self) -> None:
|
|
173
|
+
"""Close the NATS connection and stop the event loop."""
|
|
174
|
+
if self._owns_client and self._client:
|
|
175
|
+
drain_coro = self._client.drain()
|
|
176
|
+
if self._loop and self._loop.is_running():
|
|
177
|
+
try:
|
|
178
|
+
self.run_async(drain_coro, timeout=5)
|
|
179
|
+
except Exception as e:
|
|
180
|
+
logging.warning(f"Error draining NATS connection: {e}")
|
|
181
|
+
else:
|
|
182
|
+
drain_coro.close() # Discard cleanly without RuntimeWarning
|
|
183
|
+
|
|
184
|
+
if self._owns_loop and self._loop and self._loop.is_running():
|
|
185
|
+
self._loop.call_soon_threadsafe(self._loop.stop)
|
|
186
|
+
if self._loop_thread:
|
|
187
|
+
self._loop_thread.join(timeout=2)
|