Metadata-Version: 2.4
Name: opteryx-shared-services
Version: 0.2.1
Summary: Shared capabilities for Opteryx platform services
Author-email: joocer <justin.joyce@joocer.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2025 Justin Joyce (@joocer)
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
Project-URL: Homepage, https://github.com/mabel-dev/opteryx-shared-services
Keywords: opteryx,config,logging,preflight,healthcheck
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: google-cloud-firestore==2.*
Provides-Extra: storage
Requires-Dist: google-cloud-storage==3.*; extra == "storage"
Provides-Extra: secrets
Requires-Dist: google-cloud-secret-manager==2.*; extra == "secrets"
Provides-Extra: web
Requires-Dist: starlette>=0.37; extra == "web"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: starlette>=0.37; extra == "test"
Requires-Dist: httpx; extra == "test"
Dynamic: license-file

# opteryx-shared-services

Capabilities every Opteryx service needs, in one package.

```bash
pip install opteryx-shared-services
```

Three seed capabilities, each of which was previously copied into eight service
repos and had silently diverged there:

| module | provides |
| --- | --- |
| `opteryx_shared_services.config` | the platform configuration client |
| `opteryx_shared_services.logging` | structured logging, and the audit wire format the fleet's log ingestion selects on |
| `opteryx_shared_services.preflight` | startup dependency checks that fail a Cloud Run revision rather than letting an instance that cannot serve replace one that can |
| `opteryx_shared_services.audit` | request audit middleware, and the payload shape the fleet's log ingestion reads |

Nothing is imported by the top-level package. A service that needs only
configuration must not pay for a Firestore, GCS or Secret Manager import it
never uses, so each capability is imported by name.

## Why a package, not vendored copies

The previous mechanism was copy-by-`vendor.sh`. It does not hold. At the point
this package was created, `config_client.py` existed in **four different
versions** across eight repos, and **five of the eight** were missing
`promote_to_environ` — the function that copies the configuration document into
`os.environ`, which is the only way `opteryx.config` and `opteryx_catalog` (both
of which read `os.environ` directly) ever see it. One repo had been re-vendored
two days earlier and *still* lacked it, because it was synced from a stale
checkout.

Nothing could detect that, because a copy carries no version. A pinned
dependency answers "which version is this service on?" by reading
`pyproject.toml`.

## `config`

```python
from opteryx_shared_services.config import get_config

AUTH_URL = get_config("AUTH_URL", default="https://authenticate.opteryx.app")
```

Configuration lives in Firestore at `(default)/config/<environment>`, one
document per environment. Resolution order is process environment → the
configuration document → the caller's default, so a value set in the service's
ENVVARs always wins.

The document is read once at import and every value copied into `os.environ`
without overwriting anything already there — that is what reaches code which
cannot call `get_config` (`opteryx.config`, `opteryx_catalog`). The client is
deliberately fail-open: if Firestore is unreachable it serves last-known values
and otherwise the caller's default, so a Firestore blip cannot take down the
fleet.

`OPTERYX_CONFIG_EAGER=false` skips the read at import;
`OPTERYX_CONFIG_PROMOTE=false` skips the copy into `os.environ`.

## `logging`

```python
from opteryx_shared_services.logging import get_logger, set_log_name

set_log_name("opteryx.worker")
logger = get_logger()
```

**The audit wire format is a cross-service contract.** `xb500.opteryx`'s
`transform_audit_logs` ingests Cloud Logging entries whose
`jsonPayload.severity` is `"AUDIT"` into `ops.audit_log`;
`transform_billing_logs` selects `"BILLING"` the same way. That imposes three
requirements on every `logger.audit(...)` call:

1. the line must be **valid JSON on its own** — Cloud Logging only parses a
   stdout line into `jsonPayload` when the whole line is JSON, so a
   `time | LEVEL | name | {...}` prefix makes it opaque `textPayload`;
2. the payload must carry **`severity` itself** — the LogEntry's GCP-assigned
   severity is not what the transform selects on;
3. a caller-supplied severity must **survive verbatim** — billing events pass
   `severity="BILLING"` and are ingested by a different transform.

So audit and alert records get their own stdout handler with no formatter
prefix, and their payload is passed through untouched. Ordinary records go to a
separate handler that never sees them.

Ordinary records are JSON with a mapped `severity` under `K_SERVICE` (every
Cloud Run deployment), because formatted text lands as `textPayload` at DEFAULT
severity where severity-based alerting cannot see even an ERROR. Everywhere else
they stay human-readable. `LOG_FORMAT=json` / `LOG_FORMAT=text` overrides either
way.

Also included: `set_trace_context()` for request correlation, `extra=` fields
riding along as their own `jsonPayload` fields, tracebacks folded into `message`
so Error Reporting groups them, `propagate = False` so uvicorn does not
duplicate every line, and third-party loggers (`opteryx.config_client`,
`opteryx_catalog`) adopted at WARNING so a broken alert sink cannot present as
a channel simply being quiet.

### What this fixed

At the point of consolidation, five of eight services emitted audit records the
audit pipeline could not see:

| service | was | now |
| --- | --- | --- |
| control, register | correct | unchanged |
| xb500 | bypassed logging via `opteryx_catalog.audit` | either route works |
| worker | JSON, but AUDIT mapped to severity `"NOTICE"` | `"AUDIT"` |
| jobs, upload, authenticate | text formatter → `textPayload` | raw JSON on stdout |
| odata | no handler at all → root logger | raw JSON on stdout |

Adopting this module therefore **starts new records flowing** into
`ops.audit_log` from five services. Validate their payloads against
`AUDIT_LOG_SCHEMA` before rolling out.

## `audit`

```python
from opteryx_shared_services.audit import AuditMiddleware

service.add_middleware(AuditMiddleware)
```

Ten fields, the same for every service — `method`, `path`, `status`,
`duration_ms`, `from`, `timestamp`, `detail`, `jwt_present`/`jwt_sub`, and
`client_ip`/`user_agent`/`host`. The eight implementations this replaces had
diverged into eight payload shapes with only the first six in common, so
`ops.audit_log` could be joined on very little.

`from` is `x-forwarded-for` — what a proxy claims. `client_ip` is the peer the
server actually saw. They differ exactly when it matters.

### Why pure ASGI, not `BaseHTTPMiddleware`

`BaseHTTPMiddleware.call_next()` returns as soon as the status and headers are
captured — it cannot see whether the body finished streaming. A response that
started as a clean 200 and then died mid-stream (compression crash, worker OOM,
dropped connection) was audited as a plain `200 okay`, indistinguishable from a
full success, because the record was written before the body was ever sent.
**Seven of the eight services had that defect.**

This wraps `send` directly, tracking bytes actually written and whether the
stream was cleanly terminated, and reports a distinct detail when it was not.
It also re-raises rather than swallowing exceptions into a synthetic empty
Response, so Starlette's `ServerErrorMiddleware` produces a real error.

An exception reaching the middleware is *not* by itself a truncation —
`ServerErrorMiddleware` renders a complete 500 and then re-raises, and calling
that a transport failure would misdescribe a client that got a whole, correct
error response. Only an unterminated stream is reported as one.

### Extension points

Rather than forking the payload:

- `request.state.audit_extra = {...}` — any route may set this while handling
  the request; it is merged into the record. This is how a handler reports what
  it did without the middleware knowing anything about that route.
- `AuditMiddleware(app, extra_fields=fn)` — a callable taking the `Request`,
  for values derived from the request or environment.

Neither may overwrite a standard field, and a raising `extra_fields` is logged
and ignored: an incomplete audit record beats no record, and beats a 500 caused
by the auditing itself.

Needs the `web` extra (`starlette`).

## `preflight`

Each service keeps a small `app/preflight.py` that declares what it needs:

```python
import sys

from opteryx_shared_services.preflight import Preflight
from opteryx_shared_services.preflight import firestore_read
from opteryx_shared_services.preflight import gcs_list
from opteryx_shared_services.preflight import gcs_write
from opteryx_shared_services.preflight import secret_manager

preflight = Preflight(
    component="worker",
    checks=(
        secret_manager(),
        firestore_read("firestore-jobs", collection="jobs"),
        firestore_read(
            "firestore-catalog",
            collection="$catalog",
            database_key="FIRESTORE_DATABASE",
            covered_by="firestore-jobs",
        ),
        gcs_list("gcs-data", bucket_key="GCS_BUCKET"),
        gcs_write("gcs-results", bucket_key="RESULTS_BUCKET"),
    ),
)

if __name__ == "__main__":
    sys.exit(preflight.main())
```

Then run it *before* the server, with `&&` so a non-zero preflight means the
server is never `exec`'d:

```dockerfile
CMD python -m app.preflight && exec python -m uvicorn app.main:service --host 0.0.0.0 --port ${PORT:-8080}
```

`app/main.py`'s lifespan calls `preflight.run_startup_checks()`; the health route
calls `preflight.readiness()` and answers 503 when it is false. Keep
`/health/live` as a separate dependency-free ping, so a transient Firestore blip
does not get a busy instance killed mid-request.

### Why a separate process, not just the ASGI lifespan

A container running `uvicorn --workers N` has a supervisor that binds the
listening socket in the **parent** and respawns any child that dies. A lifespan
that raises kills one child, the parent starts another, and the port stays open
throughout — the revision looks alive while no worker can serve a thing.

`python -m app.preflight` runs before uvicorn exists. Its exit code is what fails
the revision. Keep the lifespan check too, as a second line of defence, but it is
not what makes the container fail.

### Probe builders

| builder | proves | use for |
| --- | --- | --- |
| `secret_manager(name=…, secret_key=…)` | Secret Manager reachable; reads a named secret when one is configured | any service that resolves secrets |
| `firestore_read(name, collection=…, database_key=…, covered_by=…)` | a collection is readable | every Firestore-backed service |
| `gcs_list(name, bucket_key=…)` | a bucket is listable | buckets the service **reads** |
| `gcs_write(name, bucket_key=…)` | an object can be created (and is then removed) | buckets the service **writes** |
| `custom(name, body)` | whatever `body` returns a `CheckResult` for | Cloud Tasks queues, Valkey, another service's `/health` |

Builders take **configuration keys**, not values. The name is resolved when the
probe runs, because configuration is promoted into `os.environ` during startup —
a value captured at import can be older than the one the rest of the process is
using.

**Declare the direction the service uses, not both.** A LIST is not a substitute
for a CREATE and vice versa: a service account holding `objectCreator` on a
results bucket (enough to serve every request) fails a read probe, and one
holding only `objectViewer` sails through a read probe and then fails at the
first upload. `bucket.exists()` is worse than either — it needs
`storage.buckets.get`, which `objectViewer` does not carry.

### Cost and safety

Probes make real RPCs, one of them a write, and `/health` is usually
unauthenticated — so results are cached for 30 seconds. Without that the endpoint
would be a way to bill the project by curl loop. Alerts are raised only when the
probes actually run, so a cached failure does not re-report.

Each probe is bounded at 5s and the whole set at 15s — the latter because a
client that hangs *before* it makes an RPC (ADC discovery, metadata server) never
reaches the per-call timeout. The write probe puts its object under
`_healthcheck/`, so a bucket lifecycle rule can mop up if the service account
cannot delete what it creates.

`HEALTH_DEPENDENCY_CHECKS=false` turns the probes off everywhere — both the
startup gate and `/health`. It is for running a service somewhere its
dependencies genuinely are not reachable (a laptop, a unit test), not a way to
keep a broken deployment serving.

## Optional extras

Only the config client's Firestore dependency is unconditional. The preflight
probes import their clients lazily, inside the probe that needs them:

```bash
pip install "opteryx-shared-services[storage,secrets,web]"
```

`web` is `starlette`, needed only by `audit`.

## Releasing

Tag `version-<pyproject version>`. The workflow gates on the full test matrix
(3.11–3.14) and refuses a tag that does not match `pyproject.toml`.

## Tests

```bash
python -m pip install -e ".[test,storage,secrets,web]"
python -m pytest tests -q
```
