Skip to main content

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: 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_logger keeps 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 is LOG_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_logger adds 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_LEVEL or logger_level raises at import.
  • log_with_event caps the event at 4096 characters and renders nothing when the logger would drop the line.

Upgrading to 0.19.0

  • init_logger consumers in Lambda: Text lines change from asctime - name - LEVEL - msg to the runtime's tab-separated [LEVEL] timestamp request-id msg, and a traceback is one event.
  • setup_logger consumers in Lambda: each line was written once per setup_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.
  • HttpRequestLogger logs 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/
├── 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.

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.

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:

  1. Bump the version with uv version --bump patch (or minor), which updates both pyproject.toml and uv.lock; CI runs with UV_LOCKED, so a version edited by hand without relocking fails verify.
  2. Open an MR against main. CI runs lint, typecheck, test and build on every push.
  3. Merge to main.
  4. The publish_pypi job compares the version in pyproject.toml against the latest version on PyPI:
    • If pyproject.toml > PyPI: builds the wheel + sdist with uv build and uploads via uv publish.
    • Otherwise: logs ::: skip — local X <= PyPI Y and exits cleanly.
    • If PyPI cannot be reached or the comparison fails, the job fails rather than skipping.

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, requests declared, 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, deprecated datetime.utcnow() calls replaced. Version 0.18.90 → 0.19.0.
  • 2026-05-12 — Migrated from AWS CodeCommit (reach-commons → renamed to reach-commons-MOVED-TO-GITLAB, read-only archive) to GitLab. Replaced manual python build.py publish 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.tf SSM. 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.23.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for reach-commons 0.23.0
File Size Uploaded Provenance Actions
reach_commons-0.23.0.tar.gz 50.7 kB Without provenance Details for reach_commons-0.23.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for reach-commons 0.23.0
File Interpreter ABI Platform Actions
reach_commons-0.23.0-py3-none-any.whl Python 3 none any Details for reach_commons-0.23.0-py3-none-any.whl

Total release size: 118.9 kB

Release files / reach_commons-0.23.0.tar.gz

Download URL reach_commons-0.23.0.tar.gz
Size 50.7 kB
Tags Source
SHA-256 checksum
How to use checksums
7d347f3883b878488e54c38c1a21049e34567d8be1fcc37c7e4035353237fa91
BLAKE2b-256 checksum
How to use checksums
70da718eac57210fe1d7dfb8fe5ad89023e0df7941d20139d42c72c9e94521c6
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.23.0-py3-none-any.whl

Download URL reach_commons-0.23.0-py3-none-any.whl
Size 68.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c5ca8fda3668f1f33372e8a84d0a6bfad68a8e714701a8a55b64dd35148b0da2
BLAKE2b-256 checksum
How to use checksums
24e70baf305c5e5f1674057541360e6e1b1a5f9a1735530ff7d2e2282b59d56b
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.23.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.

Release history Release notifications | RSS feed

This release

0.23.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page