3tears-nats
Typed NATS client wrapper, subject builders, and JetStream KV bucket primitives for 3tears applications.
What this package provides
NatsClient-- single canonical wrapper aroundnats-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 withtimedeltatimeouts, and JetStream KV bucket access.Subject+Subjects-- opaque subject dataclass and factory of every canonical subject family used by 3tears applications. Replaces ad-hocf"{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'snats_subject_namespace.nats_distributed_lock-- TTL-based distributed lock primitive built onNatsKvBucket.create(put-if-absent). Atomic acquisition + background heartbeat + automatic cleanup; on holder death the TTL expires the key.forward/serve_owner-- payload-agnostic owner-routed request/reply: send a request to whichever pod currently serves a key and get its reply back. A separate election mechanism decides who owns the key; this only carries the message.attach_pipe/serve_pipe/open_pipe-- a payload-agnostic byte pipe to whichever pod owns a key, for reaching a process that has no inbound network path. Rendezvous ridesforward; the stream then moves to its own subjects with a sequenced framing (a lost frame raises rather than being skipped) and a credit window that stops the producer reading its source when the consumer falls behind.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 innats-py2.10+) is impossible to reproduce against this wrapper. - Publish accepts
BaseModelinstances. Raw bytes go through the explicit escape hatchpublish_raw. - Subjects are typed
Subjectobjects, 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.
Release files for 3tears-nats 0.51.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| 3tears_nats-0.51.0.tar.gz | 347.5 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| 3tears_nats-0.51.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 544.7 kB
Release files / 3tears_nats-0.51.0.tar.gz
| Download URL | 3tears_nats-0.51.0.tar.gz |
|---|---|
| Size | 347.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c12c2e2bc8a96042ebe27f33b09087041442b013fe3c7f57e1644d8ed0b83aa8
|
|
BLAKE2b-256 checksum How to use checksums |
a2f3d80f859d31d4f660972d26bdb73ef7d7cc5048de8e6c9334f3fd6c8ff64b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 24, 2026.
Transparency logRelease files / 3tears_nats-0.51.0-py3-none-any.whl
| Download URL | 3tears_nats-0.51.0-py3-none-any.whl |
|---|---|
| Size | 197.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
35b9f62a0f8b0466f90f52352104ea81dbc07510cbc791bfed7af8adb919018e
|
|
BLAKE2b-256 checksum How to use checksums |
77951c8d0cf5cab276b8b84821f758cf3d2456dc67525ac1d10c16033cb8a2ca
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 24, 2026.
Transparency log