Managing Subscriptions¶
Create, wait for, inspect, list, and delete subscriptions. A subscription is a standing server-side request for events; it outlives your process until you delete it. Creating one is accepted at once and provisioned in the background — this page shows how to create a subscription, wait for it, read what it covers, and delete it. For the underlying model see Subscriptions & Events.
Create a subscription¶
subscription_id = client.rabbitmq.subscribe(
event_types=["person", "moving"], # required: at least one
geohash_regions=["dhxpfr5", "dhxpfr4b"], # required: 1–9 characters each, or ["*"] for everywhere
lens_alias="demo-lens", # required: one of your lenses, or a public one
callback=handle_event, # required: called for each event
name="parking-monitor-prod", # optional: human-readable label
)
coverage = client.rabbitmq.wait_until_ready(subscription_id, timeout=120)
print(coverage)
subscribe() asks the platform to create the subscription, which is accepted at once (status pending) and provisioned in the background — sensors matched, processing started, the delivery queue bound. The call returns the subscription id immediately and starts a background thread consuming the queue; events begin when provisioning finishes. Call wait_until_ready() to block until then and read the coverage report.
Arguments
| Argument | Type | Notes |
|---|---|---|
event_types |
list[str] |
Checked locally against the platform's list of event types — a typo raises ValueError before any request is made. The platform checks again and refuses an unknown type with UnknownEventType. |
geohash_regions |
list[str] |
One or more geohash cells, 1–9 characters each, or ["*"] alone for everywhere your organization can see. Cells nested inside a coarser one you also listed are folded into it; at most 64 distinct cells per subscription. Regions select sensors by their area of view. |
lens_alias |
str |
Alias of one of your organization's lenses, or of a public lens. An alias that is unknown or private to another organization is refused with LensNotAccessible. |
callback |
callable |
Receives one argument — the event dict. Required. Control messages never reach it. |
name |
str |
Optional. Shown in the portal and in list_subscriptions(). Defaults to a timestamped name. |
Return value
Always the subscription id string, returned as soon as the platform has accepted the request. Nothing matching your regions is not a refusal — the subscription becomes active with a coverage report that says, per event type, why nothing is covered yet, and the hourly re-check fills it in when the world changes.
Name your subscriptions
Passing name= makes a subscription easy to recognize later in list_subscriptions() and in the portal.
Regions select sensors by their area of view
["*"] subscribes to everything your organization can see. A region selects a sensor by its area of view, not by the pin on its location — a sensor whose area of view reaches into your cell is matched wherever its pin is. See Subscriptions & Events.
A subscription's lifecycle¶
stateDiagram-v2
[*] --> pending : subscribe() returns the id — the platform has accepted the request
pending --> active : ready control message — wait_until_ready() returns the coverage report
pending --> error : set-up failed and will not be retried — error control message, wait_until_ready() raises SubscriptionError
active --> active : updated control message — coverage changed on the hourly re-check
pending --> deleting : unsubscribe()
active --> deleting : unsubscribe()
error --> deleting : unsubscribe()
deleting --> [*] : delivery queue removed at once, processing released shortly after
| Status | Meaning |
|---|---|
pending |
Accepted and being provisioned. subscribe() has already returned the id; the delivery queue exists, and events may start arriving before the ready message does. |
active |
Provisioned. The delivery queue is bound for every covered event type, and events arrive as the processing behind it runs. The coverage report may still be empty — see Read the coverage report. |
error |
Setting it up failed and the platform will not try again, or the subscription was created before the current delivery system. A reason code says which — see When a subscription is in error. Delete it and subscribe again. |
deleting |
unsubscribe() was accepted. Delivery has already stopped; the processing behind the subscription is released shortly after, and the id no longer appears in list_subscriptions(). |
The platform tells the SDK about each change with a control message (ready, updated or error) placed in the subscription's own delivery queue. The SDK handles those itself and never passes them to your callback.
What the exchange looks like end to end — note that the id comes back before any sensor is matched, and that the delivery queue is removed inside the delete request:
sequenceDiagram
participant App as Your code
participant SDK as SDK
participant API as Dory platform
participant Q as Delivery queue
App->>SDK: subscribe(event_types, geohash_regions, lens_alias, callback)
SDK->>API: create subscription
API-->>SDK: accepted (status pending, queue name)
SDK->>Q: start consuming on a background thread
SDK-->>App: subscription id
App->>SDK: wait_until_ready(id)
Note over API,Q: sensors matched, processing started, queue bound
Q-->>SDK: ready control message (coverage report)
SDK-->>App: coverage report
Q-->>SDK: event
SDK-->>App: callback(event)
App->>SDK: unsubscribe(id)
SDK->>API: delete subscription
API->>Q: remove the queue (delivery stops)
API-->>SDK: accepted (status deleting)
SDK-->>App: returns
Wait for provisioning¶
from dory import SubscriptionError, SubscriptionTimeout
try:
coverage = client.wait_until_ready(subscription_id, timeout=60)
except SubscriptionTimeout:
print("still provisioning — call again, or read client.get_subscription(subscription_id)")
except SubscriptionError as e:
print(f"{e.message} ({e.code})")
client.rabbitmq.unsubscribe(subscription_id) # then subscribe again
wait_until_ready(subscription_id, timeout=60.0) — available as client.wait_until_ready(...) and client.rabbitmq.wait_until_ready(...) — blocks until the platform's ready control message arrives and returns the coverage report. If the platform reports that provisioning failed, it raises SubscriptionError. If nothing has been heard within timeout seconds, the SDK asks the platform once (a consumer that connected late may have missed the message) and raises SubscriptionTimeout only if the platform still says pending. Provisioning continues in the background regardless, so you can simply call it again, or read get_subscription().
flowchart TD
W["wait_until_ready(id, timeout)"] --> S{"ready or error heard<br/>within timeout?"}
S -->|ready| C["return the coverage report"]
S -->|error| E["raise SubscriptionError"]
S -->|nothing yet| G["ask the platform once<br/>get_subscription(id)"]
G -->|active| C
G -->|error| E
G -->|still pending| T["raise SubscriptionTimeout<br/>provisioning continues, call again"]
G -->|not found| N["raise SubscriptionNotFound"]
Two things to know while you wait:
- Events may already be arriving. The delivery queue exists from the moment
subscribe()returns, and processing that was already running for another subscription can deliver before thereadymessage does. Your callback runs normally throughout. - It is meant for subscriptions made in this process. An id from an earlier session gets no
readymessage here, so the call waits the full timeout before asking the platform. For those, useget_subscription()instead.
Read the coverage report¶
{
"event_types": {
"person": {"covered": true},
"moving": {"covered": false, "reason": "NO_COMPATIBLE_SENSOR"}
},
"sensors_matched": 3,
"sensors_served": 3,
"processors_started": 2,
"processors_reused": 1
}
The report says, for each event type you asked for, whether it is covered — and if not, why — followed by four counts: sensors matched by your regions, sensors actually being processed for you, processing started for this subscription, and processing that was already running for another subscription and is now shared with yours. It contains counts only, never sensor names or locations: your regions may match another organization's public sensors, and those details are not yours to see.
| Reason | In plain words |
|---|---|
NO_SENSORS_IN_REGION |
No sensor you can see — your own or a public one — has an area of view touching your regions. |
NO_TEMPLATE_EMITS_IT |
The lens has no template that produces this event type. |
NO_COMPATIBLE_SENSOR |
A template in the lens produces it, but not from the kinds of sensor found in your regions. |
LENS_NOT_ACCESSIBLE |
The lens has been deleted, or made private by the organization that owns it, since you subscribed. Coverage returns if a private lens is made public again; a deleted lens does not come back. |
Empty coverage is not an error
A report with every event type uncovered is a live subscription, not a failure. Coverage is re-checked every hour — as sensors are added, published, moved or retired, as the lens's templates change, and as the lens itself is opened or closed — and whenever it changes the platform sends an updated control message that replaces the SDK's local copy of the report. Nothing needs to be re-created.
Check on a subscription¶
# Ask the platform — always current, one request.
detail = client.get_subscription(subscription_id)
print(detail["status"], detail["coverage"], detail["lastErrorCode"])
# What this client has heard so far — no request at all.
local = client.rabbitmq.subscription_status(subscription_id)
client.get_subscription(subscription_id)(alsoclient.rabbitmq.get_subscription(...)) asks the platform. Among its fields areid,name,description,status,coverage,lastErrorCode(the reason code on anerrorsubscription,nullotherwise),queueName,eventTypes,geohashes,lensAlias(nullif the lens has since been deleted),boundSensorCount,createdAt,updatedAtandactivatedAt. It raisesSubscriptionNotFoundwhen the id is missing, deleted (a subscription being deleted included), or belongs to another organization, and a plainRuntimeErrorwhen it belongs to another app client in your organization or the request fails for any other reason. It also refreshes the SDK's local view, which is whywait_until_ready()uses it as its fallback.client.rabbitmq.subscription_status(subscription_id)returns the SDK's local view —{"status": ..., "coverage": ..., "error": ...}— built from the control messages received so far, with no network call.erroris{"code", "message"}when the status iserrorandNoneotherwise. It returnsNonefor an id this client has never heard of.
List subscriptions¶
for sub in client.list_subscriptions():
print(sub["id"], sub["name"], sub["status"], sub["lastErrorCode"])
list_subscriptions() returns every subscription your app client still holds, newest first — pending, active and error alike, and including ones created in previous sessions. A deleted subscription is not listed. Each entry includes at least id, name, status, queueName, eventTypes, geohashes, coverage (the report, once provisioned), lastErrorCode (the reason code on an error entry, null otherwise), createdAt and activatedAt. List entries do not name the lens; get_subscription() does, as lensAlias. The owning app client is inferred from your token, so no arguments are needed. Use it to spot an error entry that should be deleted and re-created, and to clean up subscriptions a previous run left behind.
When a subscription is in error¶
A subscription in error stays that way: the platform does not try to set it up again, and the hourly re-check passes it by. The remedy is always the same — delete it and subscribe again. The reason reaches you as a code with a plain sentence keyed on it, never as the platform's internal diagnostic:
SubscriptionError.codeand.message, whenwait_until_ready()raises;subscription_status(id)["error"], as{"code": ..., "message": ...};lastErrorCodeinget_subscription()and in everylist_subscriptions()entry.
| Code | What happened | What to do |
|---|---|---|
BROKER_REFUSED |
The message broker refused a request while the subscription was being set up. Trying the same set-up again cannot fix it. | Delete it and subscribe again. If it keeps failing, contact support with the subscription id. |
PROVISIONING_FAILED |
Setting it up kept failing on temporary problems until the platform ran out of attempts. | Delete it and subscribe again. If it keeps failing, contact support with the subscription id. |
QUEUE_ORPHANED |
The delivery queue could not be created, and the platform could not clean up after it. Your subscribe() call raised BrokerUnavailable, so you never received this id — it turns up in list_subscriptions(). |
Delete it, which removes what was left behind, and subscribe again. |
LEGACY_RESUBSCRIBE |
The subscription was created before the current delivery system. | Delete it and subscribe again. |
The portal explains the same codes in its own words. describe_subscription_error(code) returns the SDK's sentence for a code you read from a list entry:
from dory.rabbitmq import describe_subscription_error
for sub in client.list_subscriptions():
if sub["status"] == "error":
print(sub["name"], sub["lastErrorCode"], describe_subscription_error(sub["lastErrorCode"]))
client.rabbitmq.unsubscribe(sub["id"]) # then subscribe again
Delete a subscription¶
unsubscribe() stops the local consumer (if this process created it) and asks the platform to delete the subscription. The request is accepted at once: the delivery queue is removed within the request, so no more events arrive, and the processing behind it is released shortly after in the background. From that moment the id is gone — it no longer appears in list_subscriptions(), and get_subscription() raises SubscriptionNotFound.
It works on any id your app client owns, including ids obtained from list_subscriptions() in a fresh process, and it is fine to call while the subscription is still pending. An error subscription is cleaned up the same way: delete it, then subscribe again.
What the outcome means:
- Accepted (the platform answers 202) — the local entry is dropped. Done.
- Already gone (the platform answers 404) — treated as a successful no-op; the local entry is dropped.
- Belongs to another app client in your organization (the platform answers 403) — raises
RuntimeError; the local entry is kept and the subscription is not deleted. - Any other failure, including the platform not being reachable — raises
RuntimeError. The local consumer has already been stopped, so no more events are delivered locally; the local entry is kept, so callunsubscribe()again to retry the server-side cleanup.
If a subscription is deleted from somewhere else — the portal, say — the broker cancels the consumer and the SDK's background thread for it ends on its own.
Clean up everything from this session¶
close() unsubscribes every subscription created by this client instance (best-effort) and releases connections. Use it in a finally block or shutdown handler.
Multiple subscriptions¶
One client can hold several subscriptions at once, each with its own filters and callback:
people = client.rabbitmq.subscribe(event_types=["person"], geohash_regions=["dhxpfr5"],
lens_alias="demo-lens", callback=on_person, name="people")
accidents = client.rabbitmq.subscribe(event_types=["accidents"], geohash_regions=["dhxp"],
lens_alias="demo-lens", callback=on_accident, name="accidents")
Each one is provisioned independently, so wait on each id separately with wait_until_ready().
Putting it together¶
Subscribe, wait, inspect the coverage, run until interrupted, then delete — the flow of the SDK's example script, with each typed error handled:
import json, signal, time
from dory import DoryClient, SubscriptionError, SubscriptionRefused, SubscriptionTimeout
running = True
def handle_event(event: dict):
print(json.dumps(event, indent=2))
def stop(*_):
global running
running = False
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop)
client = DoryClient()
try:
subscription_id = client.rabbitmq.subscribe(
event_types=["person", "moving"],
geohash_regions=["dhxpfr5"],
lens_alias="demo-lens",
callback=handle_event,
name="demo-consumer",
)
except SubscriptionRefused as e:
print(f"Refused: {e.api_message} [{e.code}]")
client.close()
raise SystemExit(1)
print(f"Subscription accepted: {subscription_id}")
try:
coverage = client.rabbitmq.wait_until_ready(subscription_id, timeout=120)
for event_type, result in coverage.get("event_types", {}).items():
state = "covered" if result["covered"] else f"not covered ({result['reason']})"
print(f" {event_type}: {state}")
except SubscriptionTimeout:
print("Still provisioning; events start when it finishes.") # keep running
except SubscriptionError as e:
print(f"Set-up failed: {e.message} [{e.code}]")
client.rabbitmq.unsubscribe(subscription_id) # then subscribe again
client.close()
raise SystemExit(1)
try:
while running:
time.sleep(1)
finally:
client.rabbitmq.unsubscribe(subscription_id)
client.close()
Errors¶
Every error class below is importable from the package:
from dory import (
SubscriptionRefused, UnknownEventType, LensNotAccessible, InvalidRegion,
RegionTooFine, TooManyCells, TooManySensors, QuotaExceeded, BrokerUnavailable,
SubscriptionError, SubscriptionTimeout, SubscriptionNotFound,
)
Refused before acceptance. subscribe() raises one of these when the platform turns the request down, and normally nothing is created. All of them subclass SubscriptionRefused, which is a RuntimeError — so an existing except RuntimeError still works — and each carries .code (the platform's reason code), .status and .api_message. A refusal that carries no reason code — a credential without permission to create subscriptions, for example — raises a plain RuntimeError instead.
| Raised | When |
|---|---|
SubscriptionRefused (the base class itself) |
A reason code with no class of its own, such as INVALID_REQUEST for a malformed request the local checks did not catch. |
UnknownEventType |
An event type the platform does not know. |
LensNotAccessible |
No lens by that alias is usable from your organization — it is unknown, or private to another organization. Both cases get the same answer. |
InvalidRegion |
A geohash is malformed, or "*" was mixed with other cells. "*" must be the only region given. |
RegionTooFine |
A cell is longer than 9 characters. |
TooManyCells |
More than 64 distinct cells remain after nested ones collapse. |
TooManySensors |
The regions would match more than 200 sensors. Ask for a smaller area. |
QuotaExceeded |
Your organization already holds 100 subscriptions across all its app clients; deleted ones do not count. Delete one first. |
BrokerUnavailable |
The message broker did not accept the subscription's delivery queue. Retry. Normally nothing is left behind; if the platform could not clean up, a subscription appears in list_subscriptions() with status error and code QUEUE_ORPHANED — delete it. |
After acceptance. The subscription exists; these say what happened to it.
| Raised | When |
|---|---|
SubscriptionError (a RuntimeError) |
wait_until_ready(): the subscription is in error. Carries .subscription_id, .code (see When a subscription is in error) and .message, the plain sentence for that code. Delete it and subscribe again. |
SubscriptionTimeout (a TimeoutError, not a RuntimeError) |
wait_until_ready(): still pending after the timeout, and the platform agrees. Carries .subscription_id and .status. Provisioning continues — call again, or read get_subscription(). |
SubscriptionNotFound (a RuntimeError) |
get_subscription() or wait_until_ready(): no subscription by that id is visible to your credential — missing, deleted, or another organization's. Carries .subscription_id. |
RuntimeError |
unsubscribe(): the subscription belongs to another app client (403), or any other failure except 404; the local consumer is already stopped and the entry kept, so call again to retry. get_subscription(): another app client's subscription (403), or any other failure except 404. Also any failure from list_subscriptions(). |
Checked locally. ValueError is raised before any request is made for an empty event_types or geohash_regions, a missing lens_alias, no callback, or an event type not in the platform's list.
Branch on the specific class first, then on the family:
from dory import LensNotAccessible, SubscriptionRefused
try:
subscription_id = client.rabbitmq.subscribe(
event_types=["person"], geohash_regions=["dhxpfr5"],
lens_alias="demo-lens", callback=handle_event,
)
except LensNotAccessible:
print("Check the alias, or make the lens public / create it in your organization.")
except SubscriptionRefused as e:
print(f"The platform refused the request: {e.api_message} [{e.code}]")
A coverage report with every event type uncovered is not an error — see Read the coverage report above.