reach_commons
Reach's shared Python utility library — SMS encoding, phone validation, structured logging, persistence wrappers (Mongo, DynamoDB, S3, SQS, Firehose, KMS), Redis rate-limiting, and HTTP clients for internal Reach services (event-processor, callback-processor, reach-ops, reach-data-bridge), plus third-party integrations (Outscraper, Bandwidth).
Distributed as the reach-commons wheel on
PyPI. Source of truth: https://gitlab.com/reach.ai/reach-commons.
Install
pip install reach-commons # core: no web framework, no data stores
pip install "reach-commons[api]" # FastAPI: api_errors_fastapi, app_logging.log_deprecated_endpoints
pip install "reach-commons[mongo]" # pymongo + motor: mongo/*, and bson for reach_base_model
pip install "reach-commons[redis]" # redis: redis_manager, reach_aws.reach_rate_limiter, voice_conversation
Pin a version in requirements.txt / pyproject.toml like any other dep. Releases
are published from main by GitLab CI (see Release flow). Since
0.19.0 FastAPI, pymongo/motor and redis are optional extras: a service that imports one of
those modules declares the extra or the library itself, and a Lambda that does not use them
no longer ships them.
Logging
init_loggerkeeps a root handler that is already there; in Lambda that is the runtime's, so the function's Text or JSON log format applies. A bare root gets a stream handler. Its level isLOG_LEVEL, else the function's application log level, else INFO.- The shared loggers (
get_reach_logger,logging_config.setup_logger) keep their level:logger_level, else WARNING.setup_loggeradds its own handler only when root has none at the time of the call, so inside Lambda each line is written once. - All of these write the level of the same root logger, so the last call wins.
- An unknown level name in
LOG_LEVELorlogger_levelraises at import. log_with_eventcaps the event at 4096 characters and renders nothing when the logger would drop the line.
Redaction (0.31.0)
Logs carry ids, status and sizes, never message content or contact details. ReachLogger,
init_logger, setup_logger and log_with_event redact every record; the rules are in
docs/log-redaction.md.
from reach_commons.app_logging.redaction import RedactingFilter, safe_fields
# Log an allow-listed view of a payload: ids, status, error_class, *_len, duration_ms.
# Free-text `error` (str(exc)) is dropped; pass error_class=type(exc).__name__.
logger.info("sms sent", extra=safe_fields(sms, body_len=len(sms["body"]))) # stdlib / Powertools
reach_logger.info({"message": "sms sent", **safe_fields(sms)}) # get_reach_logger()
# AWS Lambda Powertools Logger (does not propagate to root): add the filter yourself.
powertools_logger.addFilter(RedactingFilter())
install_redaction(logger) adds the filter to a stdlib logger's handlers (root by default);
redact_fields, redact_value and mask_text redact a dict, any value or a string directly.
Upgrading: emails, phone numbers and content-key values (body, to, subject, ...) that
used to appear in these loggers' output now read [EMAIL], [PHONE] and [REDACTED len=N].
0.31.1 adds keys ending in _content (html_content, plain_text_content) and the person
names from_name, to_name, sender_name, recipient_name to the content keys.
Upgrading to 0.19.0
init_loggerconsumers in Lambda: Text lines change fromasctime - name - LEVEL - msgto the runtime's tab-separated[LEVEL] timestamp request-id msg, and a traceback is one event.setup_loggerconsumers in Lambda: each line was written once persetup_logger()call plus once by the runtime; it is now written once. Metric filters and alarms that count those lines need their thresholds divided accordingly.HttpRequestLoggerlogs at DEBUG (was INFO), with credential headers redacted.- KMS client logs no longer contain the payload, the ciphertext or the decrypted value.
Quick example
from reach_commons.sms_smart_encoding import MessageSmartEncoding
msg = MessageSmartEncoding("Hello world!")
print(msg.encoding, msg.length, msg.segments) # GSM-7 12 1
Repo layout
reach_commons/
├── api_errors.py the standard API error body (api_errors_fastapi.py: FastAPI handlers)
├── app_logging/ structured logger, http logger, deprecation tracker
├── clients/ thin HTTP wrappers for Reach internal services + 3rd-party APIs
│ ├── _auth.py shared Bearer-header helper (reads lambda_function_api_key)
│ ├── callback_processor.py
│ ├── event_processor.py
│ ├── nightly_lambda.py
│ ├── outscraper.py
│ ├── reach_data_bridge.py
│ └── reach_ops_api.py
├── credentials.py one named accessor per Parameter Store credential
├── mongo/ MongoDB customer persistence (sync + async)
├── reach_aws/ boto3 wrappers (dynamodb, s3, sqs, firehose, kms, rate limiter)
├── reach_base_model.py
├── redis_manager.py
├── sms_smart_encoding.py GSM-7 / UCS-2 detection + segment math
├── utils.py
└── validations.py phone-number validator (Twilio Lookups)
tests/ pytest, every suite uses @pytest.mark.parametrize
Security model
Starting with version 0.18.57, the wheel published to PyPI contains zero
credentials. Every secret consumed by reach_commons is fetched at runtime from
AWS Systems Manager Parameter Store (SecureString), sourced from
/terraform/shared-config.tf (shared_ssm_secure).
Why this matters: reach_commons is published to public PyPI. Anyone can
pip download reach-commons. The wheel is intended to be safe in that posture
— if it gets shared outside Reach (forked, cloned by an external dev, included
in a third-party tool), no Reach credentials travel with it.
Access control lives in IAM: a consumer Lambda can only read the secrets
its execution role grants ssm:GetParameter on. No hardcoded fallbacks, no
setattr side-channels. The one environment override is the internal API bearer
(below), which is unset in every Reach deployment.
Credential accessors
Every credential kept in Parameter Store has one named accessor in
reach_commons/credentials.py, and that module is the only place its path is written.
A value shared by several services is one parameter named after its vendor
(/stripe/{env}/secret-key), never after a consumer, so rotating it is one write.
from reach_commons import credentials
credentials.preload(credentials.stripe_secret_key, credentials.sendgrid_api_key)
def handler(event, context):
stripe.api_key = credentials.stripe_secret_key()
preload(...) at module import resolves the credentials during the cold start in one
batched GetParameters call (ten names per call), so a missing IAM grant or parameter
raises there instead of on the first request, and a deploy that starts many containers
at once does not exhaust Parameter Store's request rate. Handlers
then call the accessor itself, which reads the in-process cache and picks up a rotation
within the TTL. Do not copy a value into a module-level constant: that pins it for the
life of the container.
{env} resolves to staging / prod from the ENV Lambda env var (defaults to
Staging). The commons clients read theirs the same way: _auth uses
reach_internal_api_key, CommonsPhoneNumberValidation the Twilio pair, and
OutscraperClient the Outscraper token.
Required consumer Lambda IAM
Grant ssm:GetParameter on each exact parameter the consumer reads, in its own
environment only. Never a prefix and never GetParametersByPath: a by-path read is how
one service once pulled the other environment's secrets into its state.
statement {
sid = "ReadOwnCredentials"
effect = "Allow"
actions = ["ssm:GetParameter", "ssm:GetParameters"]
resources = [
"arn:aws:ssm:us-east-1:383836045505:parameter/api-keys/${lower(var.tag)}/lambda-function-api-key",
"arn:aws:ssm:us-east-1:383836045505:parameter/stripe/${lower(var.tag)}/secret-key",
]
}
The parameters use the default alias/aws/ssm key. /terraform/ssm-credential-reads.tf
is the reference for the lambda roles in that repo.
Caching and rotation
reach_commons._ssm caches each SSM value in-memory with a 1-hour TTL per
process. Cold start = 1 GetParameter per credential (~50ms each); warm
container reuses the cached value until expiry.
After 1h, a rotation in SSM is picked up automatically on the next call — no redeploy needed. To force an immediate refresh, redeploy / recycle the Lambda containers.
Test / local override
Test suites replace Parameter Store before importing code that preloads credentials:
import reach_commons.credentials
reach_commons.credentials.override_for_tests(lambda path: f"test-value-for:{path}")
Each affected client accepts explicit kwargs so tests and local tooling can bypass SSM entirely:
CommonsPhoneNumberValidation(account_sid="ACtest", auth_token="...")
OutscraperClient(token="...")
reach_api_bearer_header() has no kwarg path — tests should
monkeypatch.setattr(reach_commons.clients._auth, "get_secure", lambda p: "...").
Internal API bearer from the environment
reach_api_bearer_header() uses REACH_INTERNAL_API_KEY as the token when that
variable is set and non-blank, and reads /api-keys/{env}/lambda-function-api-key
from Parameter Store otherwise. Reach sets it nowhere, so Reach keeps the SSM read; a
deployment outside Reach AWS (a fork of the voice relay or an agent) sets it instead of
granting SSM access.
API errors
Every Reach API answers an error with the same body, so a client (the dashboard's pop-ups)
reads one shape. It follows RFC 7807 problem details, served as application/json because
API Gateway REST APIs base64 application/problem+json:
{
"type": "https://api.getreach.ai/errors/payment-declined",
"title": "Payment declined",
"status": 424,
"detail": "Your card has insufficient funds.",
"code": "payment_declined",
"retryable": false,
"request_id": "c0ffee",
"instance": "/stripe/subscription/4227/one-time-charge/price_1",
"provider": {"name": "stripe", "type": "card_error", "code": "card_declined", "decline_code": "insufficient_funds"}
}
detailis always a string a person can read;codeis what a client branches on.request_idis the API Gateway request id, logged with the error.providerappears on third-party failures,errors([{field, message}]) on validation.- The codes and their titles live in
api_errors.CODES; a service may add a domain code.
reach_commons.api_errors has no dependencies: ApiError, stripe_error(error_json),
provider_error(name), and lambda_response(error) for a Lambda without a framework.
reach_commons.api_errors_fastapi.install_error_handlers(app) (the [api] extra) renders
ApiError, HTTPException, validation errors and any unhandled exception in that shape.
An unhandled exception answers internal with a generic message and logs the traceback.
Voice contract
reach_commons/schemas/voice_agent.py is the relay <-> agent voice contract, versioned
by VOICE_CONTRACT_VERSION (currently "1"), which every model carries as
contract_version:
| Model | Direction | Route |
|---|---|---|
VoiceSetupRequest / VoiceSetup |
relay -> agent, answered synchronously | POST {agent}/voice/setup |
VoiceAgentRequest |
relay -> agent, fire-and-forget | POST {agent}/voice/agent-request |
VoiceAgentCallback |
agent -> relay, fire-and-forget | POST {relay}/reply |
Unknown fields are ignored and a missing contract_version reads as the current one,
so adding an optional field does not bump the version; a change an older peer cannot
ignore does. business_id is an int for a numeric tenant (a numeric string is read as
one, so that wire is unchanged) and a string for any other tenant id. VoiceSetup.handoff
carries what a screened transfer needs from the business (ADR 0002); without it the relay
reads the business's document.
Since 0.32.0 ReachAgentWorkerClient sends every VoiceAgentRequest through one
process-wide requests.Session, so consecutive utterances reuse an open TLS connection
instead of paying a handshake each (about 59 ms against 1-2 ms inside the VPC).
Local development
uv sync --all-extras # runtime + extras + dev group (Python from .python-version)
uv run pre-commit install --hook-type pre-commit --hook-type pre-push # one-time
uv run --all-extras pytest # full suite
uv run ruff check reach_commons tests
uv run ruff format --check reach_commons tests
uv run --all-extras pyright reach_commons tests
Python floor: >=3.12. CI runs on ghcr.io/astral-sh/uv:python3.13-bookworm-slim, and
uv.lock pins every dependency, so uv sync --frozen --all-extras reproduces CI locally.
Pre-commit hooks
.pre-commit-config.yaml installs three layers:
- On commit (fast): trailing-whitespace, end-of-file-fixer, check-yaml, check-toml, check-merge-conflict, check-added-large-files, ruff (lint + autofix), ruff-format.
- On push (slower): pyright with the runtime deps as
additional_dependencies.
Pyright runs only on push so day-to-day commits stay fast.
Release flow
GitLab CI publishes to PyPI automatically. Workflow:
- Bump the version with
uv version --bump patch(orminor), which updates bothpyproject.tomlanduv.lock; CI runs withUV_LOCKED, so a version edited by hand without relocking fails verify. - Open an MR against
main. CI runslint,typecheck,testandbuildon every push. - Merge to
main. - The
publish_pypijob compares theversioninpyproject.tomlagainst the latest version on PyPI:- If
pyproject.toml > PyPI: builds the wheel + sdist withuv buildand uploads viauv publish. - Otherwise: logs
::: skip — local X <= PyPI Yand exits cleanly. - If PyPI cannot be reached or the comparison fails, the job fails rather than skipping.
- If
So a release = uv version --bump, merge to main. Done.
Pipeline shape
verify ──► lint (ruff check + ruff format --check)
──► typecheck (pyright)
──► test (pytest)
──► build (uv build)
publish ──► publish_pypi (only on main, only when version bumped)
All jobs run on the self-hosted EC2 GitLab runner (tags: [ec2-instance]).
PyPI authentication
The token lives in the POETRY_PYPI_TOKEN_PYPI GitLab CI/CD Variable on the
project (Settings → CI/CD → Variables): masked, scope = All environments. The name
predates the move to uv; publish_pypi hands it to uv publish as UV_PUBLISH_TOKEN.
Rotation = generate a new project-scoped token at https://pypi.org/manage/account/token/
(scope = reach-commons), paste into the same CI/CD Variable, revoke the old.
No restart or SSH needed.
Branches
| Branch | Purpose |
|---|---|
main |
source of truth; merges here trigger PyPI publish when version bumped |
fix/*, feat/*, chore/* |
working branches; verify pipeline runs but no publish |
Architecture cheat-sheet
consumer Lambda
│
├─ os.environ[lambda_function_api_key] ──┐
│ ▼
│ reach_commons.clients._auth.reach_api_bearer_header()
│ │
├─ EventProcessorClient ────────────────┤
├─ CallbackProcessorClient ────────────────┤ "Authorization": "Bearer <token>"
├─ ReachOpsApiClient ────────────────┤
└─ ReachDataBridgeClient ────────────────┘
Four client classes share the same Bearer token via a single helper — drop the
env var on the Lambda and all four start sending Bearer (empty) → 401s.
Test layout
All test files in tests/ use @pytest.mark.parametrize. Adding a non-parametrized
def test_x is discouraged — collapse into parameters or split if behaviors truly
diverge.
| File | Coverage |
|---|---|
test_imports.py |
parametrized over every reach_commons.* module via pkgutil.walk_packages — auto-discovers new submodules |
test_sms_smart_encoding.py |
GSM-7 / UCS-2 detection, normalization map, segment math at length boundaries (160/161/306/307, 70/71) |
test_validations.py |
Twilio HTTP wrapper status-code → bool fork; env var precedence (uppercase / lowercase / unset) |
test_auth.py |
reach_api_bearer_header() with token set / empty / unset; REACH_INTERNAL_API_KEY over SSM |
test_voice_contract.py |
voice contract version default, JSON round trips, int / string business_id |
test_outscraper.py |
env var → constructor → empty fallback resolution; X-API-KEY header |
Migration history
- 2026-10-20 — Poetry replaced by uv (PEP 621 metadata,
uv.lock, hatchling build). FastAPI, pymongo/motor and redis moved to extras,requestsdeclared, Python floor raised to 3.12 (every consumer runs 3.13), loggers made to cooperate with the Lambda runtime handler, secrets removed from the KMS and HTTP request logs, deprecateddatetime.utcnow()calls replaced. Version 0.18.90 → 0.19.0. - 2026-05-12 — Migrated from AWS CodeCommit (
reach-commons→ renamed toreach-commons-MOVED-TO-GITLAB, read-only archive) to GitLab. Replaced manualpython build.pypublish with GitLab CI publish-on-version-bump. Removed hardcoded secrets from the wheel (Twilio creds, Bearer tokens shared across four internal-API clients, Outscraper token + webhook URL); all secrets now read from env vars sourced from/terraform/shared-config.tfSSM. Adopted ruff (replacing black + isort) and pyright; added parametrized test suite. Version 0.18.55 → 0.18.56.
Service ownership
Owner: Reach Engineering. Issues / MR reviews via the GitLab repo. The legacy
CodeCommit archive at reach-commons-MOVED-TO-GITLAB is read-only and kept
only for git archaeology.
Metadata
Release files for reach-commons 0.34.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 | Provenance | Actions |
|---|---|---|---|---|
| reach_commons-0.34.0.tar.gz | 61.8 kB | Without provenance | Details for reach_commons-0.34.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| reach_commons-0.34.0-py3-none-any.whl | Python 3 | none | any | Details for reach_commons-0.34.0-py3-none-any.whl |
Total release size: 143.7 kB
Release files / reach_commons-0.34.0.tar.gz
| Download URL | reach_commons-0.34.0.tar.gz |
|---|---|
| Size | 61.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
76e4476b25919de8631f9f4f583a3f6e8125346ce6949c23e7539701aea2cd49
|
|
BLAKE2b-256 checksum How to use checksums |
cd70d780a7ebf0a5cedb73b11c26b0e8539359d1da22e2fe1904792d760097dd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / reach_commons-0.34.0-py3-none-any.whl
| Download URL | reach_commons-0.34.0-py3-none-any.whl |
|---|---|
| Size | 81.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ddfcad40e987186b0d19a3714a3b1dd5fd3df4e9e6d4e68f93b1f6066b0107af
|
|
BLAKE2b-256 checksum How to use checksums |
fc21779232fdd51d7023196a73e852b7a999274649652c34375a546beec73487
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for reach-commons 0.34.0
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.