Metadata-Version: 2.4
Name: countwatch
Version: 0.1.2
Summary: CountWatch: count events in your app and get alerts when a count spikes, drops or goes silent.
License-Expression: MIT
Project-URL: Homepage, https://countwatch.com
Project-URL: Documentation, https://api.countwatch.com/docs/guides.md
Keywords: monitoring,alerting,anomaly-detection,metrics,counter
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# countwatch

Count events in your app and get an alert when a count spikes, drops or goes silent: [CountWatch](https://countwatch.com).
Python 3.10–3.13 tested in CI (3.9+ allowed), standard library only.

```python
from countwatch import CountWatch

cw = CountWatch()  # COUNTWATCH_API_KEY (and COUNTWATCH_API_URL, if set) from the environment
cw.count("orders")                   # +1
cw.count("orders", 3, {"plan": "pro"})  # +3 for the watch orders · plan:pro (its tags)
```

- Run `npx countwatch init` in the project (Node is needed for this one step): you approve a write key in your browser and
  it is saved as `COUNTWATCH_API_KEY` in `.countwatch.env`; put it in the app's environment. The API is https://api.countwatch.com; set `COUNTWATCH_API_URL` (or `api_url=`) for another host.
- `count()` never raises and never blocks; it is thread-safe. Counts are summed per 5-minute bucket and sent in
  batches on a daemon thread every 5 minutes (the account's `send_interval_seconds` from `GET /v1/status`;
  `send_interval_seconds=` can only make it longer): about 8,640 requests a month per process (30 days at 5 minutes). The process flushes
  once more at exit.
- Counting events that happened earlier (a backlog read after a reconnect, a queue drained late)? Pass when each
  happened: `cw.count("edits", 1, {"wiki": "enwiki"}, at=event_time)` (a timezone-aware `datetime` or ISO 8601
  text, within the last 6 hours). It lands in its own 5-minute window. Older history goes through `POST /v1/import`.
- Errors go to `on_error(e)` with a stable `e.code` (`invalid_call`, `send_failed`, `unauthorized`, …). A 401 stops
  the client. Failed sends are retried with the same `Idempotency-Key`, so nothing counts twice.
- Each metric it has seen gets a 0 for every 5-minute bucket with no events, so an hour without events is a real zero (a drop
  alert), while a stopped process sends nothing and raises the no-data alert. Declare metrics up front to get zeros
  before the first event: `CountWatch(metrics=["orders", {"metric": "orders", "tags": {"plan": "pro"}}])`.
- It re-reads the send interval after each send, so a change of plan takes effect with no restart.
- Without the timer (serverless, `countwatch send`) nothing sends zeros later, so the watch is a push watch: a slot
  with no events counts as zero, and the no-data alert needs the watch's `expected_interval_minutes`. Pass `source="explicit"` if your job sends its own zeros.
- Use the write API key only. Not for browsers or other clients you hand out: use a Webhook URL there (Senders,
  under Connect, in the dashboard). HTTPS only (plain HTTP to localhost). Nothing is stored on disk: counts still buffered when
  a process is killed are lost.
- After `os.fork()` (gunicorn, uWSGI, Celery prefork) the child starts with an empty buffer (its thread starts at
  its first count); the parent sends its own. Create the client in each worker (a `post_fork` hook), not in a preloading master: a master
  that declared metrics keeps sending their zeros even when every worker is gone, which would hide the no-data alert.

| Where | Pattern |
|---|---|
| Django, Flask, FastAPI, Celery workers | one module-level `cw = CountWatch()`; nothing else |
| asyncio | `cw = AsyncCountWatch()`; `cw.count(...)`; `await cw.aclose()` on shutdown |
| AWS Lambda, Cloud Functions | `cw = CountWatch(auto_flush=False)` and decorate the handler with `@cw.flush_after` |
| Short scripts, cron jobs | `cw.flush()` at the end (or `npx countwatch send <metric>`) |

There is no Python CLI: `npx countwatch init` gets the key (you approve it in your browser), or make a write key under Settings → API keys, and set `COUNTWATCH_API_KEY`.
