appecosystem-client 0.3.1__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.
- appecosystem_client-0.3.1/LICENSE +21 -0
- appecosystem_client-0.3.1/PKG-INFO +112 -0
- appecosystem_client-0.3.1/README.md +78 -0
- appecosystem_client-0.3.1/appecosystem_client.egg-info/PKG-INFO +112 -0
- appecosystem_client-0.3.1/appecosystem_client.egg-info/SOURCES.txt +17 -0
- appecosystem_client-0.3.1/appecosystem_client.egg-info/dependency_links.txt +1 -0
- appecosystem_client-0.3.1/appecosystem_client.egg-info/requires.txt +12 -0
- appecosystem_client-0.3.1/appecosystem_client.egg-info/top_level.txt +1 -0
- appecosystem_client-0.3.1/ecosystem_client/__init__.py +237 -0
- appecosystem_client-0.3.1/ecosystem_client/config.py +116 -0
- appecosystem_client-0.3.1/ecosystem_client/discovery.py +224 -0
- appecosystem_client-0.3.1/ecosystem_client/event_publisher.py +144 -0
- appecosystem_client-0.3.1/ecosystem_client/event_subscriber.py +77 -0
- appecosystem_client-0.3.1/ecosystem_client/log_handler.py +47 -0
- appecosystem_client-0.3.1/ecosystem_client/match.py +20 -0
- appecosystem_client-0.3.1/ecosystem_client/peer.py +81 -0
- appecosystem_client-0.3.1/ecosystem_client/topology.py +114 -0
- appecosystem_client-0.3.1/pyproject.toml +56 -0
- appecosystem_client-0.3.1/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Mikel Smart
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: appecosystem-client
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: Service registration, peer discovery and event bus client for appEcosystem
|
|
5
|
+
Author: Mikel Smart
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/M1K31/appEcosystem
|
|
8
|
+
Project-URL: Source, https://github.com/M1K31/appEcosystem
|
|
9
|
+
Project-URL: Issues, https://github.com/M1K31/appEcosystem/issues
|
|
10
|
+
Keywords: service-discovery,events,microservices,mdns,appecosystem
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: httpx>=0.24.0
|
|
25
|
+
Requires-Dist: appecosystem-auth>=0.4.0
|
|
26
|
+
Provides-Extra: mdns
|
|
27
|
+
Requires-Dist: zeroconf>=0.80.0; extra == "mdns"
|
|
28
|
+
Provides-Extra: yaml
|
|
29
|
+
Requires-Dist: pyyaml>=6.0; extra == "yaml"
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# appecosystem-client
|
|
36
|
+
|
|
37
|
+
Client library for joining the
|
|
38
|
+
[appEcosystem](https://github.com/M1K31/appEcosystem) service mesh: register a
|
|
39
|
+
service, discover peers, and publish or subscribe to events.
|
|
40
|
+
|
|
41
|
+
Services find each other through a local registry (or mDNS), so an application
|
|
42
|
+
can react to what other applications on the network are doing — a doorbell
|
|
43
|
+
camera detecting motion, a SIEM raising an alert — without any of them being
|
|
44
|
+
hard-wired to each other.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install appecosystem-client
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Requires Python 3.9+. Pulls in `appecosystem-auth` for request signing.
|
|
53
|
+
|
|
54
|
+
Optional extras:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install "appecosystem-client[mdns]" # zeroconf peer discovery
|
|
58
|
+
pip install "appecosystem-client[yaml]" # YAML config files
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Join the ecosystem
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import asyncio
|
|
65
|
+
from ecosystem_client import EcosystemClient
|
|
66
|
+
|
|
67
|
+
async def main():
|
|
68
|
+
eco = EcosystemClient(
|
|
69
|
+
service_name="my-app",
|
|
70
|
+
service_port=9000,
|
|
71
|
+
health_endpoint="/health",
|
|
72
|
+
)
|
|
73
|
+
await eco.start() # registers, then discovers peers
|
|
74
|
+
|
|
75
|
+
await eco.publish("myapp.ready", {"version": "1.0"})
|
|
76
|
+
|
|
77
|
+
peer = await eco.discover("openeye")
|
|
78
|
+
if peer:
|
|
79
|
+
print("found OpenEye at", peer)
|
|
80
|
+
|
|
81
|
+
await eco.stop() # deregisters cleanly
|
|
82
|
+
|
|
83
|
+
asyncio.run(main())
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Receive events
|
|
87
|
+
|
|
88
|
+
Register a handler for an event pattern. `*` matches one namespace segment:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
@eco.on("camera.*")
|
|
92
|
+
async def on_camera_event(event):
|
|
93
|
+
print(event["type"], event["data"])
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Deliver incoming webhooks to `eco.handle_webhook(payload)` from whatever HTTP
|
|
97
|
+
route your framework exposes.
|
|
98
|
+
|
|
99
|
+
## Event patterns
|
|
100
|
+
|
|
101
|
+
| Pattern | Matches |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `camera.motion` | that exact type |
|
|
104
|
+
| `camera.*` | `camera.motion`, `camera.offline` |
|
|
105
|
+
| `*` | every event with a non-empty type |
|
|
106
|
+
|
|
107
|
+
An event with an empty type matches nothing — a malformed publish from one
|
|
108
|
+
service cannot fan out to every subscriber.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT — see [LICENSE](https://github.com/M1K31/appEcosystem/blob/main/LICENSE).
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# appecosystem-client
|
|
2
|
+
|
|
3
|
+
Client library for joining the
|
|
4
|
+
[appEcosystem](https://github.com/M1K31/appEcosystem) service mesh: register a
|
|
5
|
+
service, discover peers, and publish or subscribe to events.
|
|
6
|
+
|
|
7
|
+
Services find each other through a local registry (or mDNS), so an application
|
|
8
|
+
can react to what other applications on the network are doing — a doorbell
|
|
9
|
+
camera detecting motion, a SIEM raising an alert — without any of them being
|
|
10
|
+
hard-wired to each other.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install appecosystem-client
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Requires Python 3.9+. Pulls in `appecosystem-auth` for request signing.
|
|
19
|
+
|
|
20
|
+
Optional extras:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install "appecosystem-client[mdns]" # zeroconf peer discovery
|
|
24
|
+
pip install "appecosystem-client[yaml]" # YAML config files
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Join the ecosystem
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import asyncio
|
|
31
|
+
from ecosystem_client import EcosystemClient
|
|
32
|
+
|
|
33
|
+
async def main():
|
|
34
|
+
eco = EcosystemClient(
|
|
35
|
+
service_name="my-app",
|
|
36
|
+
service_port=9000,
|
|
37
|
+
health_endpoint="/health",
|
|
38
|
+
)
|
|
39
|
+
await eco.start() # registers, then discovers peers
|
|
40
|
+
|
|
41
|
+
await eco.publish("myapp.ready", {"version": "1.0"})
|
|
42
|
+
|
|
43
|
+
peer = await eco.discover("openeye")
|
|
44
|
+
if peer:
|
|
45
|
+
print("found OpenEye at", peer)
|
|
46
|
+
|
|
47
|
+
await eco.stop() # deregisters cleanly
|
|
48
|
+
|
|
49
|
+
asyncio.run(main())
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Receive events
|
|
53
|
+
|
|
54
|
+
Register a handler for an event pattern. `*` matches one namespace segment:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
@eco.on("camera.*")
|
|
58
|
+
async def on_camera_event(event):
|
|
59
|
+
print(event["type"], event["data"])
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Deliver incoming webhooks to `eco.handle_webhook(payload)` from whatever HTTP
|
|
63
|
+
route your framework exposes.
|
|
64
|
+
|
|
65
|
+
## Event patterns
|
|
66
|
+
|
|
67
|
+
| Pattern | Matches |
|
|
68
|
+
|---|---|
|
|
69
|
+
| `camera.motion` | that exact type |
|
|
70
|
+
| `camera.*` | `camera.motion`, `camera.offline` |
|
|
71
|
+
| `*` | every event with a non-empty type |
|
|
72
|
+
|
|
73
|
+
An event with an empty type matches nothing — a malformed publish from one
|
|
74
|
+
service cannot fan out to every subscriber.
|
|
75
|
+
|
|
76
|
+
## License
|
|
77
|
+
|
|
78
|
+
MIT — see [LICENSE](https://github.com/M1K31/appEcosystem/blob/main/LICENSE).
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: appecosystem-client
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: Service registration, peer discovery and event bus client for appEcosystem
|
|
5
|
+
Author: Mikel Smart
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/M1K31/appEcosystem
|
|
8
|
+
Project-URL: Source, https://github.com/M1K31/appEcosystem
|
|
9
|
+
Project-URL: Issues, https://github.com/M1K31/appEcosystem/issues
|
|
10
|
+
Keywords: service-discovery,events,microservices,mdns,appecosystem
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: httpx>=0.24.0
|
|
25
|
+
Requires-Dist: appecosystem-auth>=0.4.0
|
|
26
|
+
Provides-Extra: mdns
|
|
27
|
+
Requires-Dist: zeroconf>=0.80.0; extra == "mdns"
|
|
28
|
+
Provides-Extra: yaml
|
|
29
|
+
Requires-Dist: pyyaml>=6.0; extra == "yaml"
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# appecosystem-client
|
|
36
|
+
|
|
37
|
+
Client library for joining the
|
|
38
|
+
[appEcosystem](https://github.com/M1K31/appEcosystem) service mesh: register a
|
|
39
|
+
service, discover peers, and publish or subscribe to events.
|
|
40
|
+
|
|
41
|
+
Services find each other through a local registry (or mDNS), so an application
|
|
42
|
+
can react to what other applications on the network are doing — a doorbell
|
|
43
|
+
camera detecting motion, a SIEM raising an alert — without any of them being
|
|
44
|
+
hard-wired to each other.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install appecosystem-client
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Requires Python 3.9+. Pulls in `appecosystem-auth` for request signing.
|
|
53
|
+
|
|
54
|
+
Optional extras:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install "appecosystem-client[mdns]" # zeroconf peer discovery
|
|
58
|
+
pip install "appecosystem-client[yaml]" # YAML config files
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Join the ecosystem
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import asyncio
|
|
65
|
+
from ecosystem_client import EcosystemClient
|
|
66
|
+
|
|
67
|
+
async def main():
|
|
68
|
+
eco = EcosystemClient(
|
|
69
|
+
service_name="my-app",
|
|
70
|
+
service_port=9000,
|
|
71
|
+
health_endpoint="/health",
|
|
72
|
+
)
|
|
73
|
+
await eco.start() # registers, then discovers peers
|
|
74
|
+
|
|
75
|
+
await eco.publish("myapp.ready", {"version": "1.0"})
|
|
76
|
+
|
|
77
|
+
peer = await eco.discover("openeye")
|
|
78
|
+
if peer:
|
|
79
|
+
print("found OpenEye at", peer)
|
|
80
|
+
|
|
81
|
+
await eco.stop() # deregisters cleanly
|
|
82
|
+
|
|
83
|
+
asyncio.run(main())
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Receive events
|
|
87
|
+
|
|
88
|
+
Register a handler for an event pattern. `*` matches one namespace segment:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
@eco.on("camera.*")
|
|
92
|
+
async def on_camera_event(event):
|
|
93
|
+
print(event["type"], event["data"])
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Deliver incoming webhooks to `eco.handle_webhook(payload)` from whatever HTTP
|
|
97
|
+
route your framework exposes.
|
|
98
|
+
|
|
99
|
+
## Event patterns
|
|
100
|
+
|
|
101
|
+
| Pattern | Matches |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `camera.motion` | that exact type |
|
|
104
|
+
| `camera.*` | `camera.motion`, `camera.offline` |
|
|
105
|
+
| `*` | every event with a non-empty type |
|
|
106
|
+
|
|
107
|
+
An event with an empty type matches nothing — a malformed publish from one
|
|
108
|
+
service cannot fan out to every subscriber.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT — see [LICENSE](https://github.com/M1K31/appEcosystem/blob/main/LICENSE).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
appecosystem_client.egg-info/PKG-INFO
|
|
5
|
+
appecosystem_client.egg-info/SOURCES.txt
|
|
6
|
+
appecosystem_client.egg-info/dependency_links.txt
|
|
7
|
+
appecosystem_client.egg-info/requires.txt
|
|
8
|
+
appecosystem_client.egg-info/top_level.txt
|
|
9
|
+
ecosystem_client/__init__.py
|
|
10
|
+
ecosystem_client/config.py
|
|
11
|
+
ecosystem_client/discovery.py
|
|
12
|
+
ecosystem_client/event_publisher.py
|
|
13
|
+
ecosystem_client/event_subscriber.py
|
|
14
|
+
ecosystem_client/log_handler.py
|
|
15
|
+
ecosystem_client/match.py
|
|
16
|
+
ecosystem_client/peer.py
|
|
17
|
+
ecosystem_client/topology.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ecosystem_client
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Ecosystem client library for inter-service communication."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import logging
|
|
6
|
+
import socket
|
|
7
|
+
from typing import Any, Callable, Coroutine
|
|
8
|
+
|
|
9
|
+
from .config import EcosystemConfig
|
|
10
|
+
from .discovery import DiscoveryManager, DiscoveryMode
|
|
11
|
+
from .event_publisher import EventPublisher
|
|
12
|
+
from .event_subscriber import EventSubscriber
|
|
13
|
+
from .log_handler import EcosystemLogHandler
|
|
14
|
+
from .peer import Peer
|
|
15
|
+
|
|
16
|
+
# Keep in step with packages/ecosystem-client/pyproject.toml. This drifted to
|
|
17
|
+
# 0.1.0 while pyproject said 0.3.1, so anything reporting the runtime version
|
|
18
|
+
# (logs, diagnostics, compatibility checks) named a release that never shipped.
|
|
19
|
+
__version__ = "0.3.1"
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
HandlerFunc = Callable[[dict[str, Any]], Coroutine[Any, Any, None]]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class EcosystemClient:
|
|
27
|
+
"""
|
|
28
|
+
Thin client for ecosystem integration.
|
|
29
|
+
|
|
30
|
+
Handles service discovery, event pub/sub, and direct peer calls
|
|
31
|
+
across three operating modes:
|
|
32
|
+
- REGISTRY: full ecosystem with appEcosystem registry
|
|
33
|
+
- PEER_TO_PEER: direct mDNS or static peer discovery
|
|
34
|
+
- STANDALONE: no-op, project runs independently
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
service_name: str,
|
|
40
|
+
service_port: int,
|
|
41
|
+
health_endpoint: str = "/health",
|
|
42
|
+
subscriptions: list[str] | None = None,
|
|
43
|
+
config: EcosystemConfig | None = None,
|
|
44
|
+
priority: int = 0,
|
|
45
|
+
):
|
|
46
|
+
self._config = config or EcosystemConfig.from_env()
|
|
47
|
+
self._config.service_name = service_name
|
|
48
|
+
self._config.service_port = service_port
|
|
49
|
+
self._config.health_endpoint = health_endpoint
|
|
50
|
+
if priority:
|
|
51
|
+
self._config.priority = priority
|
|
52
|
+
|
|
53
|
+
self._service_name = service_name
|
|
54
|
+
self._service_port = service_port
|
|
55
|
+
self._health_endpoint = health_endpoint
|
|
56
|
+
self._subscriptions = subscriptions or []
|
|
57
|
+
|
|
58
|
+
self._discovery = DiscoveryManager(self._config)
|
|
59
|
+
self._publisher = EventPublisher(
|
|
60
|
+
self._config, mode=DiscoveryMode.STANDALONE, service_name=service_name,
|
|
61
|
+
)
|
|
62
|
+
self._subscriber = EventSubscriber(hmac_secret=self._config.hmac_secret)
|
|
63
|
+
|
|
64
|
+
self._peers: dict[str, dict[str, Any]] = {}
|
|
65
|
+
self._peer_objects: dict[str, Peer] = {}
|
|
66
|
+
self._started = False
|
|
67
|
+
self._refresh_task: asyncio.Task | None = None
|
|
68
|
+
self._advertised_host: str | None = None # last host we registered with
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def mode(self) -> DiscoveryMode:
|
|
72
|
+
return self._discovery.mode
|
|
73
|
+
|
|
74
|
+
async def start(self) -> None:
|
|
75
|
+
"""Start the ecosystem client: detect mode, register, discover peers."""
|
|
76
|
+
if self._started:
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
mode = await self._discovery.detect_mode()
|
|
80
|
+
self._publisher._mode = mode
|
|
81
|
+
|
|
82
|
+
if mode == DiscoveryMode.REGISTRY:
|
|
83
|
+
await self._register_self()
|
|
84
|
+
|
|
85
|
+
# Discover peers
|
|
86
|
+
await self._refresh_peers()
|
|
87
|
+
|
|
88
|
+
self._started = True
|
|
89
|
+
logger.info(
|
|
90
|
+
f"Ecosystem client started: {self._service_name} in {mode.value} mode"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Start background refresh
|
|
94
|
+
self._refresh_task = asyncio.create_task(self._periodic_refresh())
|
|
95
|
+
|
|
96
|
+
async def stop(self) -> None:
|
|
97
|
+
"""Stop the ecosystem client: deregister, cancel background tasks."""
|
|
98
|
+
if self._refresh_task:
|
|
99
|
+
self._refresh_task.cancel()
|
|
100
|
+
try:
|
|
101
|
+
await self._refresh_task
|
|
102
|
+
except asyncio.CancelledError:
|
|
103
|
+
pass
|
|
104
|
+
|
|
105
|
+
if self._discovery.mode == DiscoveryMode.REGISTRY:
|
|
106
|
+
await self._discovery.deregister_self(self._service_name)
|
|
107
|
+
|
|
108
|
+
self._started = False
|
|
109
|
+
logger.info(f"Ecosystem client stopped: {self._service_name}")
|
|
110
|
+
|
|
111
|
+
async def discover(self, service_name: str) -> Peer | None:
|
|
112
|
+
"""Get a Peer object for a discovered service, or None if not found."""
|
|
113
|
+
if service_name in self._peer_objects:
|
|
114
|
+
peer = self._peer_objects[service_name]
|
|
115
|
+
if not peer.is_degraded:
|
|
116
|
+
return peer
|
|
117
|
+
|
|
118
|
+
if service_name in self._peers:
|
|
119
|
+
peer_info = self._peers[service_name]
|
|
120
|
+
base_url = peer_info.get("base_url", "")
|
|
121
|
+
if base_url:
|
|
122
|
+
peer = Peer(
|
|
123
|
+
name=service_name,
|
|
124
|
+
base_url=base_url,
|
|
125
|
+
hmac_secret=self._config.hmac_secret,
|
|
126
|
+
timeout=self._config.request_timeout,
|
|
127
|
+
)
|
|
128
|
+
self._peer_objects[service_name] = peer
|
|
129
|
+
return peer
|
|
130
|
+
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
async def publish(self, event_type: str, data: dict[str, Any]) -> dict:
|
|
134
|
+
"""Publish an event to the ecosystem."""
|
|
135
|
+
return await self._publisher.publish(event_type, data)
|
|
136
|
+
|
|
137
|
+
def on(self, event_pattern: str, handler: HandlerFunc | None = None):
|
|
138
|
+
"""Register an event handler. Works as method or decorator."""
|
|
139
|
+
result = self._subscriber.on(event_pattern, handler)
|
|
140
|
+
# Update subscriptions list for registration
|
|
141
|
+
if event_pattern not in self._subscriptions:
|
|
142
|
+
self._subscriptions.append(event_pattern)
|
|
143
|
+
return result
|
|
144
|
+
|
|
145
|
+
async def handle_webhook(self, envelope: dict[str, Any]) -> None:
|
|
146
|
+
"""Process an incoming webhook event."""
|
|
147
|
+
await self._subscriber.dispatch(envelope)
|
|
148
|
+
|
|
149
|
+
async def _current_advertise_host(self) -> str:
|
|
150
|
+
"""The host other services should use to reach us, resolved fresh each
|
|
151
|
+
call so a DHCP/IP change is picked up. Falls back to the legacy local-IP
|
|
152
|
+
probe if the topology helper is unavailable."""
|
|
153
|
+
try:
|
|
154
|
+
from .topology import advertise_host
|
|
155
|
+
return advertise_host()
|
|
156
|
+
except Exception:
|
|
157
|
+
return self._get_local_ip()
|
|
158
|
+
|
|
159
|
+
async def _register_self(self) -> bool:
|
|
160
|
+
"""(Re-)register this service with the registry using the current
|
|
161
|
+
advertise host. Idempotent — the registry upserts by name, so calling
|
|
162
|
+
this on an interval acts as a heartbeat that keeps our IP and last-seen
|
|
163
|
+
fresh and re-adds us if we were pruned while unreachable."""
|
|
164
|
+
host = await self._current_advertise_host()
|
|
165
|
+
webhook_url = f"http://{host}:{self._service_port}{self._config.webhook_path}"
|
|
166
|
+
all_subs = list(set(self._subscriptions + self._subscriber.subscriptions))
|
|
167
|
+
ok = await self._discovery.register_self(
|
|
168
|
+
name=self._service_name,
|
|
169
|
+
host=host,
|
|
170
|
+
port=self._service_port,
|
|
171
|
+
health_endpoint=self._health_endpoint,
|
|
172
|
+
webhook_url=webhook_url,
|
|
173
|
+
subscriptions=all_subs,
|
|
174
|
+
priority=self._config.priority,
|
|
175
|
+
)
|
|
176
|
+
if ok:
|
|
177
|
+
self._advertised_host = host
|
|
178
|
+
return ok
|
|
179
|
+
|
|
180
|
+
async def _refresh_peers(self) -> None:
|
|
181
|
+
"""Refresh the peer list from discovery."""
|
|
182
|
+
self._peers = await self._discovery.get_peers()
|
|
183
|
+
# Clear cached peer objects for removed peers
|
|
184
|
+
for name in list(self._peer_objects.keys()):
|
|
185
|
+
if name not in self._peers:
|
|
186
|
+
del self._peer_objects[name]
|
|
187
|
+
# Update publisher's peer webhooks for Mode 2
|
|
188
|
+
if self._discovery.mode == DiscoveryMode.PEER_TO_PEER:
|
|
189
|
+
webhooks = {}
|
|
190
|
+
for name, info in self._peers.items():
|
|
191
|
+
base_url = info.get("base_url", "")
|
|
192
|
+
webhooks[name] = {
|
|
193
|
+
"webhook_url": f"{base_url}{self._config.webhook_path}",
|
|
194
|
+
"subscriptions": info.get("subscriptions", ["*"]),
|
|
195
|
+
}
|
|
196
|
+
self._publisher.set_peer_webhooks(webhooks)
|
|
197
|
+
|
|
198
|
+
async def _periodic_refresh(self) -> None:
|
|
199
|
+
"""Periodically re-check discovery, re-register self, and refresh peers.
|
|
200
|
+
|
|
201
|
+
Re-registering each interval is what makes dynamic IPs work: if this
|
|
202
|
+
host's address changes (DHCP renewal, reconnect) we push the new
|
|
203
|
+
advertise host to the registry instead of leaving a stale, unreachable
|
|
204
|
+
registration behind. It also re-adds us if the health monitor pruned us
|
|
205
|
+
while we were briefly unreachable."""
|
|
206
|
+
while True:
|
|
207
|
+
await asyncio.sleep(self._config.discovery_interval)
|
|
208
|
+
try:
|
|
209
|
+
old_mode = self._discovery.mode
|
|
210
|
+
new_mode = await self._discovery.detect_mode()
|
|
211
|
+
if new_mode != old_mode:
|
|
212
|
+
logger.info(
|
|
213
|
+
f"Mode changed: {old_mode.value} -> {new_mode.value}"
|
|
214
|
+
)
|
|
215
|
+
self._publisher._mode = new_mode
|
|
216
|
+
if new_mode == DiscoveryMode.REGISTRY:
|
|
217
|
+
prev = self._advertised_host
|
|
218
|
+
await self._register_self() # heartbeat / IP refresh
|
|
219
|
+
if prev and prev != self._advertised_host:
|
|
220
|
+
logger.info(
|
|
221
|
+
f"Advertise host changed {prev} -> {self._advertised_host}; "
|
|
222
|
+
"re-registered with the new address"
|
|
223
|
+
)
|
|
224
|
+
await self._refresh_peers()
|
|
225
|
+
except Exception as e:
|
|
226
|
+
logger.debug(f"Periodic refresh error: {e}")
|
|
227
|
+
|
|
228
|
+
@staticmethod
|
|
229
|
+
def _get_local_ip() -> str:
|
|
230
|
+
try:
|
|
231
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
232
|
+
s.connect(("8.8.8.8", 80))
|
|
233
|
+
ip = s.getsockname()[0]
|
|
234
|
+
s.close()
|
|
235
|
+
return ip
|
|
236
|
+
except Exception:
|
|
237
|
+
return "127.0.0.1"
|