natbus


Namenatbus JSON
Version 0.1.17 PyPI version JSON
download
home_pageNone
SummaryMinimal NATS JetStream client for internal services
upload_time2025-08-12 08:25:12
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseMIT License Copyright (c) 2025 Servicepod Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords nats jetstream messaging asyncio
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # NATBus #

• Auth: library uses explicit user=/password= with a host:port server so credentials are always sent.

• Streams: set stream_create=True to auto-create one stream (optional).

• Payloads: BusMessage.from_json sets content-type=application/json; binary pass-through uses from_bytes.

• Handlers: receive ReceivedMessage with ack()/nak()/term() for JetStream flow control.

• Durable consumers: pass durable="name"; bind=True lets pods restart without “already bound” errors.


# Add to Project
Add to the service’s requirements.txt
```text
pip install --find-links=/mnt/nas_share/python_package_repository/natbus natbus==<version>
```
# Usage
```python
import asyncio
from natbus import NatsConfig, NatsBus, BusMessage, ReceivedMessage

CFG = NatsConfig(
    server="nats-nats-jetstream:4222",
    username="nats-user",
    password="changeme",
    name="orders-svc",
    stream_create=True,
    stream_name="TEST_STREAM",
    stream_subjects=("test.stream",),

    # Optional defaults for PUSH; can be overridden per call
    queue_group=None,   # e.g. "orders-workers" to load-balance PUSH subscribers
    manual_ack=True,
)

# ---------- handlers ----------
async def handle_push(msg: ReceivedMessage):
    print("PUSH RX:", msg.subject, {
        "trace_id": msg.trace_id,
        "correlation_id": msg.correlation_id,
        "sender": msg.sender,
        "content_type": msg.content_type,
    })
    try:
        print("PUSH as_text:", msg.as_text())
    except Exception:
        pass
    await msg.ack()

async def handle_pull(msg: ReceivedMessage):
    print("PULL RX:", msg.subject, {
        "trace_id": msg.trace_id,
        "correlation_id": msg.correlation_id,
        "sender": msg.sender,
        "content_type": msg.content_type,
    })
    try:
        print("PULL as_text:", msg.as_text())
    except Exception:
        pass
    await msg.ack()

# ---------- app ----------
async def main():
    bus = NatsBus(CFG)
    await bus.connect()

    # --- PUSH consumer (server pushes to our callback) ---
    # Use a queue group to load-balance across many pods:
    # queue="orders-workers"  # uncomment to enable worker-pool behavior
    await bus.push_subscribe(
        subject="test.stream",
        handler=handle_push,
        durable="orders_push",   # retains cursor/acks
        # queue="orders-workers",  # optional: load-balanced PUSH
        manual_ack=True,
    )
    print("PUSH consumer ready (durable=orders_push)")

    # --- PULL consumer (we fetch batches, good for explicit backpressure) ---
    # Creates/ensures a pull-based durable (no queue group concept for pull)
    await bus.pull_subscribe(
        stream="TEST_STREAM",
        subject="test.stream",
        durable="orders_pull",
        handler=handle_pull,
        batch=10,        # fetch up to 10 msgs per request
        expires=1.5,     # server waits up to 1.5s for batch to fill
        manual_ack=True,
    )
    print("PULL consumer ready (durable=orders_pull)")

    # --- publish some messages (both consumers will see them, since durables differ) ---
    msg_json = BusMessage.from_json(
        "test.stream",
        {"hello": "world"},
        sender="orders-svc",
    )
    await bus.publish(msg_json)

    msg_bin = BusMessage.from_bytes(
        "test.stream",
        b"\xff\xd8\xff...binary...",
        sender="orders-svc",
        headers={"content-type": "image/jpeg"},
    )
    await bus.publish(msg_bin)

    # Keep the service alive
    while True:
        await asyncio.sleep(60)

if __name__ == "__main__":
    asyncio.run(main())


```


## Build

Version is controlled in pyproject.toml (project.version). Bump it before each release.

```shell
python3.11 -m venv .venv && . .venv/bin/activate
python -m pip install --upgrade pip build
python -m build
# artifacts: dist/natsbus-0.1.0.tar.gz and dist/natsbus-0.1.0-py3-none-any.whl

```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "natbus",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": null,
    "keywords": "nats, jetstream, messaging, asyncio",
    "author": null,
    "author_email": "Servicepod <admin@servicepod.net>",
    "download_url": "https://files.pythonhosted.org/packages/52/7a/e08c0674eecfc8246301cf4b8f1d48902e4f8fe090e38d75f0f136f8f133/natbus-0.1.17.tar.gz",
    "platform": null,
    "description": "# NATBus #\n\n\u2022 Auth: library uses explicit user=/password= with a host:port server so credentials are always sent.\n\n\u2022 Streams: set stream_create=True to auto-create one stream (optional).\n\n\u2022 Payloads: BusMessage.from_json sets content-type=application/json; binary pass-through uses from_bytes.\n\n\u2022 Handlers: receive ReceivedMessage with ack()/nak()/term() for JetStream flow control.\n\n\u2022 Durable consumers: pass durable=\"name\"; bind=True lets pods restart without \u201calready bound\u201d errors.\n\n\n# Add to Project\nAdd to the service\u2019s requirements.txt\n```text\npip install --find-links=/mnt/nas_share/python_package_repository/natbus natbus==<version>\n```\n# Usage\n```python\nimport asyncio\nfrom natbus import NatsConfig, NatsBus, BusMessage, ReceivedMessage\n\nCFG = NatsConfig(\n    server=\"nats-nats-jetstream:4222\",\n    username=\"nats-user\",\n    password=\"changeme\",\n    name=\"orders-svc\",\n    stream_create=True,\n    stream_name=\"TEST_STREAM\",\n    stream_subjects=(\"test.stream\",),\n\n    # Optional defaults for PUSH; can be overridden per call\n    queue_group=None,   # e.g. \"orders-workers\" to load-balance PUSH subscribers\n    manual_ack=True,\n)\n\n# ---------- handlers ----------\nasync def handle_push(msg: ReceivedMessage):\n    print(\"PUSH RX:\", msg.subject, {\n        \"trace_id\": msg.trace_id,\n        \"correlation_id\": msg.correlation_id,\n        \"sender\": msg.sender,\n        \"content_type\": msg.content_type,\n    })\n    try:\n        print(\"PUSH as_text:\", msg.as_text())\n    except Exception:\n        pass\n    await msg.ack()\n\nasync def handle_pull(msg: ReceivedMessage):\n    print(\"PULL RX:\", msg.subject, {\n        \"trace_id\": msg.trace_id,\n        \"correlation_id\": msg.correlation_id,\n        \"sender\": msg.sender,\n        \"content_type\": msg.content_type,\n    })\n    try:\n        print(\"PULL as_text:\", msg.as_text())\n    except Exception:\n        pass\n    await msg.ack()\n\n# ---------- app ----------\nasync def main():\n    bus = NatsBus(CFG)\n    await bus.connect()\n\n    # --- PUSH consumer (server pushes to our callback) ---\n    # Use a queue group to load-balance across many pods:\n    # queue=\"orders-workers\"  # uncomment to enable worker-pool behavior\n    await bus.push_subscribe(\n        subject=\"test.stream\",\n        handler=handle_push,\n        durable=\"orders_push\",   # retains cursor/acks\n        # queue=\"orders-workers\",  # optional: load-balanced PUSH\n        manual_ack=True,\n    )\n    print(\"PUSH consumer ready (durable=orders_push)\")\n\n    # --- PULL consumer (we fetch batches, good for explicit backpressure) ---\n    # Creates/ensures a pull-based durable (no queue group concept for pull)\n    await bus.pull_subscribe(\n        stream=\"TEST_STREAM\",\n        subject=\"test.stream\",\n        durable=\"orders_pull\",\n        handler=handle_pull,\n        batch=10,        # fetch up to 10 msgs per request\n        expires=1.5,     # server waits up to 1.5s for batch to fill\n        manual_ack=True,\n    )\n    print(\"PULL consumer ready (durable=orders_pull)\")\n\n    # --- publish some messages (both consumers will see them, since durables differ) ---\n    msg_json = BusMessage.from_json(\n        \"test.stream\",\n        {\"hello\": \"world\"},\n        sender=\"orders-svc\",\n    )\n    await bus.publish(msg_json)\n\n    msg_bin = BusMessage.from_bytes(\n        \"test.stream\",\n        b\"\\xff\\xd8\\xff...binary...\",\n        sender=\"orders-svc\",\n        headers={\"content-type\": \"image/jpeg\"},\n    )\n    await bus.publish(msg_bin)\n\n    # Keep the service alive\n    while True:\n        await asyncio.sleep(60)\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n\n\n```\n\n\n## Build\n\nVersion is controlled in pyproject.toml (project.version). Bump it before each release.\n\n```shell\npython3.11 -m venv .venv && . .venv/bin/activate\npython -m pip install --upgrade pip build\npython -m build\n# artifacts: dist/natsbus-0.1.0.tar.gz and dist/natsbus-0.1.0-py3-none-any.whl\n\n```\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 Servicepod\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \u201cSoftware\u201d), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in\n        all copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \u201cAS IS\u201d, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n        THE SOFTWARE.",
    "summary": "Minimal NATS JetStream client for internal services",
    "version": "0.1.17",
    "project_urls": {
        "Homepage": "https://servicepod.net",
        "Issues": "https://servicepod.net",
        "Source": "https://servicepod.net"
    },
    "split_keywords": [
        "nats",
        " jetstream",
        " messaging",
        " asyncio"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "6b43afa1fd0d4f4f6f4356eb85cbdc0f4833c753b31a28cbbe9948ccc64e640f",
                "md5": "5ac18848d6ef2301f84e78f3f731cf12",
                "sha256": "5a827e92dda81c498e50f03c803c6f45828adbbd3235400f94df9b6488d57ea3"
            },
            "downloads": -1,
            "filename": "natbus-0.1.17-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5ac18848d6ef2301f84e78f3f731cf12",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 11599,
            "upload_time": "2025-08-12T08:25:10",
            "upload_time_iso_8601": "2025-08-12T08:25:10.893200Z",
            "url": "https://files.pythonhosted.org/packages/6b/43/afa1fd0d4f4f6f4356eb85cbdc0f4833c753b31a28cbbe9948ccc64e640f/natbus-0.1.17-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "527ae08c0674eecfc8246301cf4b8f1d48902e4f8fe090e38d75f0f136f8f133",
                "md5": "ec05354fde4f4b42339caf61f121a574",
                "sha256": "a6bb0d370a390b0051d1f9b0893f11dad02e19b7666ad42c084a7dc9e3b2e10a"
            },
            "downloads": -1,
            "filename": "natbus-0.1.17.tar.gz",
            "has_sig": false,
            "md5_digest": "ec05354fde4f4b42339caf61f121a574",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 12284,
            "upload_time": "2025-08-12T08:25:12",
            "upload_time_iso_8601": "2025-08-12T08:25:12.341004Z",
            "url": "https://files.pythonhosted.org/packages/52/7a/e08c0674eecfc8246301cf4b8f1d48902e4f8fe090e38d75f0f136f8f133/natbus-0.1.17.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-12 08:25:12",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "natbus"
}
        
Elapsed time: 0.52218s