romeways-nats-queue 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.
@@ -0,0 +1,160 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit tests / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ .idea/
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.5
2
+ Name: romeways-nats-queue
3
+ Version: 0.1.0
4
+ Summary: NATS JetStream queue connector for romeways
5
+ Project-URL: homepage, https://github.com/CenturyBoys/romeways
6
+ Project-URL: repository, https://github.com/CenturyBoys/romeways
7
+ Author-email: Marco Sievers de Almeida Ximit Gaia <im.ximit@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Requires-Python: <4,>=3.11
15
+ Requires-Dist: nats-py<3,>=2.6
16
+ Description-Content-Type: text/markdown
17
+
18
+ # Romeways NATS (JetStream)
19
+
20
+ This is an extra package for romeways — for more details access the
21
+ [romeways](https://github.com/CenturyBoys/romeways) Github page.
22
+
23
+ This package uses [nats-py](https://pypi.org/project/nats-py/) and **NATS JetStream** to provide
24
+ a durable, at-least-once queue consumer. It requires a NATS server with JetStream enabled
25
+ (`nats-server -js`).
26
+
27
+ ## Configs
28
+
29
+ ### Queue
30
+
31
+ ```python
32
+ from dataclasses import dataclass
33
+
34
+ from romeways import GenericQueueConfig
35
+
36
+
37
+ @dataclass(slots=True, frozen=True)
38
+ class NatsQueueConfig(GenericQueueConfig):
39
+ """
40
+ subject: str JetStream subject to consume from / publish to.
41
+ stream: str JetStream stream that captures `subject` (created if missing).
42
+ durable: str Durable pull-consumer name (redelivery survives reconnects).
43
+ fetch_timeout: float Seconds to wait for a batch before returning empty.
44
+ """
45
+
46
+ subject: str
47
+ stream: str
48
+ durable: str
49
+ fetch_timeout: float = 1.0
50
+ connector_name: str
51
+ frequency: float
52
+ max_chunk_size: int
53
+ sequential: bool
54
+ retries: int
55
+ ```
56
+
57
+ ### Connector
58
+
59
+ ```python
60
+ from dataclasses import dataclass
61
+
62
+ from romeways import GenericConnectorConfig
63
+
64
+
65
+ @dataclass(slots=True, frozen=True)
66
+ class NatsConnectorConfig(GenericConnectorConfig):
67
+ """
68
+ servers: str | list[str] NATS server URL(s), e.g. "nats://localhost:4222".
69
+ name: str | None Optional client name reported to the server.
70
+ """
71
+
72
+ servers: str | list[str] = "nats://localhost:4222"
73
+ name: str | None = None
74
+ ```
75
+
76
+ ## Use case
77
+
78
+ ```python
79
+ import asyncio
80
+
81
+ import romeways
82
+
83
+ # Create a queue config
84
+ config_q = romeways.NatsQueueConfig(
85
+ subject="queue.payment.done",
86
+ stream="payments",
87
+ durable="payment-consumer",
88
+ connector_name="nats-dev1",
89
+ frequency=1,
90
+ max_chunk_size=10,
91
+ sequential=False,
92
+ retries=3,
93
+ )
94
+
95
+
96
+ # Register a controller/consumer for the queue name
97
+ @romeways.queue_consumer(queue_name="queue.payment.done", config=config_q)
98
+ async def controller(message: romeways.Message):
99
+ print(message)
100
+
101
+
102
+ config_p = romeways.NatsConnectorConfig(
103
+ connector_name="nats-dev1",
104
+ servers="nats://localhost:4222",
105
+ )
106
+
107
+ # Register a connector
108
+ romeways.connector_register(
109
+ connector=romeways.NatsQueueConnector, config=config_p, spawn_process=False
110
+ )
111
+
112
+ asyncio.run(romeways.start())
113
+ ```
114
+
115
+ ## Semantics
116
+
117
+ - Messages are consumed through a **durable pull consumer**, so unacked messages are
118
+ redelivered after a restart.
119
+ - Each fetched message is acked once handed to romeways; romeways' own resend-on-error
120
+ (`ResendException`) republishes to the same subject, honouring the queue's `retries`.
121
+ - Use `spawn_process=False`: the NATS connection is created in `on_start` on the running
122
+ event loop.
@@ -0,0 +1,105 @@
1
+ # Romeways NATS (JetStream)
2
+
3
+ This is an extra package for romeways — for more details access the
4
+ [romeways](https://github.com/CenturyBoys/romeways) Github page.
5
+
6
+ This package uses [nats-py](https://pypi.org/project/nats-py/) and **NATS JetStream** to provide
7
+ a durable, at-least-once queue consumer. It requires a NATS server with JetStream enabled
8
+ (`nats-server -js`).
9
+
10
+ ## Configs
11
+
12
+ ### Queue
13
+
14
+ ```python
15
+ from dataclasses import dataclass
16
+
17
+ from romeways import GenericQueueConfig
18
+
19
+
20
+ @dataclass(slots=True, frozen=True)
21
+ class NatsQueueConfig(GenericQueueConfig):
22
+ """
23
+ subject: str JetStream subject to consume from / publish to.
24
+ stream: str JetStream stream that captures `subject` (created if missing).
25
+ durable: str Durable pull-consumer name (redelivery survives reconnects).
26
+ fetch_timeout: float Seconds to wait for a batch before returning empty.
27
+ """
28
+
29
+ subject: str
30
+ stream: str
31
+ durable: str
32
+ fetch_timeout: float = 1.0
33
+ connector_name: str
34
+ frequency: float
35
+ max_chunk_size: int
36
+ sequential: bool
37
+ retries: int
38
+ ```
39
+
40
+ ### Connector
41
+
42
+ ```python
43
+ from dataclasses import dataclass
44
+
45
+ from romeways import GenericConnectorConfig
46
+
47
+
48
+ @dataclass(slots=True, frozen=True)
49
+ class NatsConnectorConfig(GenericConnectorConfig):
50
+ """
51
+ servers: str | list[str] NATS server URL(s), e.g. "nats://localhost:4222".
52
+ name: str | None Optional client name reported to the server.
53
+ """
54
+
55
+ servers: str | list[str] = "nats://localhost:4222"
56
+ name: str | None = None
57
+ ```
58
+
59
+ ## Use case
60
+
61
+ ```python
62
+ import asyncio
63
+
64
+ import romeways
65
+
66
+ # Create a queue config
67
+ config_q = romeways.NatsQueueConfig(
68
+ subject="queue.payment.done",
69
+ stream="payments",
70
+ durable="payment-consumer",
71
+ connector_name="nats-dev1",
72
+ frequency=1,
73
+ max_chunk_size=10,
74
+ sequential=False,
75
+ retries=3,
76
+ )
77
+
78
+
79
+ # Register a controller/consumer for the queue name
80
+ @romeways.queue_consumer(queue_name="queue.payment.done", config=config_q)
81
+ async def controller(message: romeways.Message):
82
+ print(message)
83
+
84
+
85
+ config_p = romeways.NatsConnectorConfig(
86
+ connector_name="nats-dev1",
87
+ servers="nats://localhost:4222",
88
+ )
89
+
90
+ # Register a connector
91
+ romeways.connector_register(
92
+ connector=romeways.NatsQueueConnector, config=config_p, spawn_process=False
93
+ )
94
+
95
+ asyncio.run(romeways.start())
96
+ ```
97
+
98
+ ## Semantics
99
+
100
+ - Messages are consumed through a **durable pull consumer**, so unacked messages are
101
+ redelivered after a restart.
102
+ - Each fetched message is acked once handed to romeways; romeways' own resend-on-error
103
+ (`ResendException`) republishes to the same subject, honouring the queue's `retries`.
104
+ - Use `spawn_process=False`: the NATS connection is created in `on_start` on the running
105
+ event loop.
@@ -0,0 +1,32 @@
1
+ [project]
2
+ name = "romeways-nats-queue"
3
+ version = "0.1.0"
4
+ description = "NATS JetStream queue connector for romeways"
5
+ authors = [{ name = "Marco Sievers de Almeida Ximit Gaia", email = "im.ximit@gmail.com" }]
6
+ requires-python = ">=3.11,<4"
7
+ readme = "README.md"
8
+ license = "Apache-2.0"
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Programming Language :: Python :: 3.11",
12
+ "Programming Language :: Python :: 3.12",
13
+ "Programming Language :: Python :: 3.13",
14
+ "Programming Language :: Python :: 3.14",
15
+ ]
16
+ # `rome-ways` is intentionally NOT declared (installed via `rome-ways[nats]`,
17
+ # so the core is always present) to avoid a circular dependency.
18
+ dependencies = ["nats-py>=2.6,<3"]
19
+
20
+ [project.urls]
21
+ homepage = "https://github.com/CenturyBoys/romeways"
22
+ repository = "https://github.com/CenturyBoys/romeways"
23
+
24
+ [build-system]
25
+ requires = ["hatchling"]
26
+ build-backend = "hatchling.build"
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["romeways_nats_queue"]
30
+
31
+ [tool.hatch.build.targets.sdist]
32
+ include = ["romeways_nats_queue"]
@@ -0,0 +1,2 @@
1
+ from .config import NatsConnectorConfig, NatsQueueConfig
2
+ from .infrastructure import NatsQueueConnector
@@ -0,0 +1,2 @@
1
+ from .connector import NatsConnectorConfig
2
+ from .queue import NatsQueueConfig
@@ -0,0 +1 @@
1
+ from .model import NatsConnectorConfig
@@ -0,0 +1,15 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ from romeways import GenericConnectorConfig
4
+
5
+
6
+ @dataclass(slots=True, frozen=True)
7
+ class NatsConnectorConfig(GenericConnectorConfig):
8
+ """
9
+ servers: str | list[str] NATS server URL(s), e.g. "nats://localhost:4222".
10
+ See nats.connect doc -> https://nats-io.github.io/nats.py/
11
+ name: str | None Optional client name reported to the server.
12
+ """
13
+
14
+ servers: str | list[str] = "nats://localhost:4222"
15
+ name: str | None = field(default=None)
@@ -0,0 +1 @@
1
+ from .model import NatsQueueConfig
@@ -0,0 +1,18 @@
1
+ from dataclasses import dataclass
2
+
3
+ from romeways import GenericQueueConfig
4
+
5
+
6
+ @dataclass(slots=True, frozen=True)
7
+ class NatsQueueConfig(GenericQueueConfig):
8
+ """
9
+ subject: str JetStream subject to consume from / publish to.
10
+ stream: str JetStream stream that captures ``subject`` (created if missing).
11
+ durable: str Durable pull-consumer name (so redelivery survives reconnects).
12
+ fetch_timeout: float Seconds to wait for a batch before returning empty.
13
+ """
14
+
15
+ subject: str
16
+ stream: str
17
+ durable: str
18
+ fetch_timeout: float = 1.0
@@ -0,0 +1 @@
1
+ from .connector import NatsQueueConnector
@@ -0,0 +1 @@
1
+ from .infrastructure import NatsQueueConnector
@@ -0,0 +1,58 @@
1
+ import logging
2
+
3
+ import nats
4
+ from nats.errors import TimeoutError as NatsTimeoutError
5
+ from nats.js.errors import NotFoundError
6
+
7
+ from romeways import AQueueConnector
8
+
9
+ from romeways_nats_queue.config import NatsConnectorConfig, NatsQueueConfig
10
+
11
+ logger = logging.getLogger("romeways")
12
+
13
+
14
+ class NatsQueueConnector(AQueueConnector):
15
+ """romeways connector backed by NATS JetStream (durable, at-least-once).
16
+
17
+ Uses a durable pull consumer so messages are redelivered across restarts.
18
+ Each fetched message is acked after it is handed to romeways; romeways' own
19
+ resend-on-error (``ResendException``) republishes to the same subject.
20
+ """
21
+
22
+ _connector_config: NatsConnectorConfig
23
+ _config: NatsQueueConfig
24
+
25
+ async def on_start(self):
26
+ self._nc = await nats.connect(
27
+ servers=self._connector_config.servers,
28
+ name=self._connector_config.name,
29
+ )
30
+ self._js = self._nc.jetstream()
31
+ # Ensure the stream exists for the subject (idempotent).
32
+ try:
33
+ await self._js.stream_info(self._config.stream)
34
+ except NotFoundError:
35
+ await self._js.add_stream(
36
+ name=self._config.stream, subjects=[self._config.subject]
37
+ )
38
+ self._subscription = await self._js.pull_subscribe(
39
+ subject=self._config.subject,
40
+ durable=self._config.durable,
41
+ )
42
+
43
+ async def get_messages(self, max_chunk_size: int) -> list[bytes]:
44
+ try:
45
+ messages = await self._subscription.fetch(
46
+ batch=abs(max_chunk_size),
47
+ timeout=self._config.fetch_timeout,
48
+ )
49
+ except NatsTimeoutError:
50
+ return []
51
+ buffer = []
52
+ for message in messages:
53
+ await message.ack()
54
+ buffer.append(message.data)
55
+ return buffer
56
+
57
+ async def send_messages(self, message: bytes):
58
+ await self._js.publish(self._config.subject, message)