Skip to main content

Typed NATS client wrapper, subject builders, and JetStream KV bucket primitives for 3tears applications

Project description

3tears-nats

Typed NATS client wrapper, subject builders, and JetStream KV bucket primitives for 3tears applications.

What this package provides

  • NatsClient -- single canonical wrapper around nats-py. Handles connect (with bounded startup-timeout + bounded runtime reconnect ceiling), graceful shutdown/drain, typed publish, kw-only subscribe with optional Pydantic validation, request/reply with timedelta timeouts, and JetStream KV bucket access.
  • Subject + Subjects -- opaque subject dataclass and factory of every canonical subject family used by 3tears applications. Replaces ad-hoc f"{namespace}.tools.call" string-concatenation across the platform.
  • NatsKvBucket -- operations against one JetStream KV bucket (get / put / delete / create / update / get_entry). Bucket name auto-prefixed by the connected client's nats_subject_namespace.
  • nats_distributed_lock -- TTL-based distributed lock primitive built on NatsKvBucket.create (put-if-absent). Atomic acquisition + background heartbeat + automatic cleanup; on holder death the TTL expires the key.
  • StreamTransport -- narrow Protocol used by streaming consumers; lets test fakes substitute for the live client.
  • Errors -- NatsClientError, SubscribeError, PublishError, RequestError, KvError.

Why a separate package

The wrapper is consumed by the platform services (broker, gateway, registry, channel adapters, agent SDK) and any 3tears-based application. Keeping it in 3tears-nats avoids forcing those apps to depend on a host application repo just for a NATS primitive.

Mistake-proofed API

  • Subscribe is keyword-only after self. A common production bug (nc.subscribe(subject, callback) silently treating the callback as a queue group in nats-py 2.10+) is impossible to reproduce against this wrapper.
  • Publish accepts BaseModel instances. Raw bytes go through the explicit escape hatch publish_raw.
  • Subjects are typed Subject objects, not strings. The factory owns subject formatting; callers cannot accidentally interpolate the wrong shape.
  • Default deadletter_on_failure=True. Uncaught subscribe-callback exceptions auto-republish to {ns}.deadletter.{path}.

Usage

from datetime import timedelta

from threetears.nats import NatsClient, Subjects

nc = await NatsClient.connect(
    nats_url="nats://localhost:4222",
    nats_subject_namespace="myapp",
    client_name="my-service",
)

# Typed publish
await nc.publish(
    subject=Subjects.audit_event("workspace.doc_set"),
    message=AuditEvent(...),
)

# Typed request/reply
response = await nc.request(
    subject=Subjects.tools_call(),
    message=ToolCallRequest(...),
    response_type=ToolCallResponse,
    timeout=timedelta(seconds=5),
)

# Subscribe with Pydantic validation
sub = await nc.subscribe_typed(
    subject=Subjects.audit_wildcard(),
    cb=on_audit_event,
    message_type=AuditEvent,
    queue="audit-consumer",
)

# JetStream KV
bucket = await nc.kv_bucket(name="agent_config", ttl=timedelta(hours=2))
await bucket.put(key="agent-1", value=b"config-payload")

await nc.shutdown()

Distributed locks

nats_distributed_lock is a TTL-backed lock for "only one pod should run this body" patterns (scheduled jobs, periodic ticks, exclusive resource access). It is layered on top of NatsKvBucket.create (atomic put-if-absent), with a background heartbeat that refreshes the entry while the body runs and a TTL that bounds the orphan-lock window after a pod death.

from datetime import timedelta

from threetears.nats import LockHeld, nats_distributed_lock

try:
    async with nats_distributed_lock(
        nc,
        "backup-job",
        bucket_name="scheduler-locks",     # default; override per consumer
        ttl=timedelta(seconds=60),         # KV entry TTL
        heartbeat=timedelta(seconds=20),   # heartbeat MUST be < ttl
    ):
        await run_backup()
except LockHeld:
    # another pod owns the lock; skip this run cleanly
    return

client=None is a graceful no-op that yields immediately. Single-pod dev environments without NATS work unchanged. LockHeld is distinct from KvError (transport / bucket failures); callers should treat the former as the expected "another pod is running" branch and surface the latter separately.

Enforcement

Direct from nats import / from nats.aio imports are flagged by the per-repo enforcement walker tests/enforcement/test_nats_wrapper_usage.py. Strict mode by default; exemptions require a # rationale: ... line.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

3tears_nats-0.14.1.tar.gz (125.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

3tears_nats-0.14.1-py3-none-any.whl (81.9 kB view details)

Uploaded Python 3

File details

Details for the file 3tears_nats-0.14.1.tar.gz.

File metadata

  • Download URL: 3tears_nats-0.14.1.tar.gz
  • Upload date:
  • Size: 125.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.1 {"installer":{"name":"uv","version":"0.11.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for 3tears_nats-0.14.1.tar.gz
Algorithm Hash digest
SHA256 c67a3aaf76214e89e216c636fa4b3fcb366f70f596005847aa4499c70884ac16
MD5 b0a1fe4f759b2a07eaaf148bd50e3fdb
BLAKE2b-256 fd8b7271abbfda6f9d19d9ad0afc26a09c1cf01e64b3df06e6d0c95644e84413

See more details on using hashes here.

File details

Details for the file 3tears_nats-0.14.1-py3-none-any.whl.

File metadata

  • Download URL: 3tears_nats-0.14.1-py3-none-any.whl
  • Upload date:
  • Size: 81.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.1 {"installer":{"name":"uv","version":"0.11.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for 3tears_nats-0.14.1-py3-none-any.whl
Algorithm Hash digest
SHA256 835d2723ca04817df6f7a982f30f2d432f68f825db3cba15cfbb910cdf436d96
MD5 c9c0510564d0b56c1efc1c6687fdb827
BLAKE2b-256 1c53a8524d2f3d9798252ed6fe20f9052f031700a651a758e74740ae00528d7e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page