Python implementation of OFA core utilities.
Project description
core-py
core-py is the Python foundation library implementing the OFA spec. It follows the recommended Python src/ layout. The OFA spec under docs/spec/ is the compatibility source of truth. core-go and other standard libraries implementing the OFA spec are useful references, but core-py does not aim to mechanically mirror any single implementation. Its public APIs should stay Pythonic while keeping semantics and recommended usage close to other standard OFA libraries.
API Conventions
docs/specis the authority for cross-language behavior, protocol fields, storage formats, and runtime compatibility.core-pyexposes Python-style APIs first, with public interfaces named insnake_case.- There is no requirement to preserve Go-style aliases, case-compatible entry points, or a one-to-one migration layer mirroring Go package names.
core-gois a useful reference implementation, but not the source of truth forcore-py.- When aligning with other OFA implementations, prioritize stable behavior, protocol fields, storage formats, runtime compatibility, and similar usage patterns over mechanically copying
core-gonaming or package layout.
Concurrency and IO Conventions
core-pyuses an async-first design for runtime IO modules. The default public path should be awaitable so upstream async services do not accidentally block the event loop.- Pure logic, pure data, and context-propagation modules stay synchronous. Do not turn non-IO capabilities into
async defpurely for consistency. - New modules involving networks, databases, caches, distributed locks, resource handles, or long-lived background tasks should expose async APIs first instead of wrapping a synchronous implementation in an async shell.
- When there is no compatibility burden from upstream integrations, do not keep sync compatibility layers for new async-first designs. If a breaking change is needed, prefer unifying the public interface directly rather than maintaining dual entry points long term.
- Do not use
asyncio.to_thread(), thread pools, or synchronous clients inside the library to disguise blocking implementations as async-first code paths. If bridging is necessary, scope it explicitly and keep it away from the default entry path. - Constructors, property access, and lightweight helpers must not perform runtime IO implicitly. Expose connection setup, initialization, stream opening, and background task startup through explicit
awaitorasync with. - Async resources must define explicit shutdown semantics such as
aclose(),async with, and cleanup guarantees after cancellation. Timeouts, cancellation, retries, and resource release should all be part of the API contract. - The async main path must not call
time.sleep(), synchronous socket/HTTP/DB APIs, or unmanaged background threads. These block the event loop and should be replaced with coroutine sleep, async clients, and cancellable tasks.
Modules
core_py.config: config loading, merge precedence, required-key validation, sensitive-key validation, redacted summaries, and stable hashingcore_py.context: cross-call context propagation with unifiedOFA_PASS_*andOFA_DIRECT_*keyscore_py.trace: trace/request header constants and ID generationcore_py.logging: unified logging facade carrying trace/request contextcore_py.httpx: HTTP client with trace propagation, timeout budgets, bounded retries, and pluggable service discoverycore_py.resource: unified resource identifier parsing plus async open, download, and upload supportcore_py.model: entities, paging, audit fields, and context-driven audit injectioncore_py.model.mongox: async repository implementation for Mongo collectionscore_py.data: business error codes, error types, and paging/sort inputscore_py.dkit: distributed primitive protocols, mutex helpers, default ID generation, and in-memory/Redis/MongoDB backends
Quick Start
from dataclasses import dataclass
from core_py import config
@dataclass
class DBConfig:
uri: str = ""
@dataclass
class AppConfig:
db: DBConfig
cfg, meta = config.load(AppConfig, config.Options(required_keys=["db.uri"]))
Config Behavior
- Hot reload is not supported. Config changes require a process restart.
- Standard config source precedence is: default config file < environment-specific config file < local override file < environment variables.
- The default config file is
configs/config.yaml. WhenAPP__ENV=dev,configs/config.dev.yamlis included as the environment-specific source. Ifconfigs/config.local.yamlexists, it participates as the local override source. Options.default_config_pathis the path to the base config file. When passed explicitly, the current implementation uses that file as the base source and keeps looking forconfig.{env}.yamlandconfig.local.yamlin the same directory.- Environment variables use the
APPprefix and__as the hierarchy separator by default. For example,APP__DB__URImaps to the canonical pathdb.uri. - The deployment environment selector also participates in final config overrides. With the defaults,
APP__ENV=devmaps toapp.env=dev. CustomizingOptions.env_prefix,Options.env_separator, orOptions.deploy_env_keychanges both the deployment environment variable name and the final config path, e.g.SERVICE__PROFILE=devmaps toservice.profile=dev. - Environment variable names must use uppercase ASCII letters, digits, and underscores. Names outside that rule are ignored.
Options.argsis acore-pyimplementation extension and not part of the standard config sources. The current implementation supports--group.key=valuewith precedence above environment variables, and it should only be used for local debugging, temporary diagnostics, and tests.- Command-line flags must not be used for secrets, passwords, tokens, or other sensitive config. In shared environments, sensitive config must come from environment variables or secure storage. Local development may use
config.local.yamlfor sensitive values. - Startup logs record
config sources, a redacted summary, and a stable hash to help diagnose the final config source and effective differences.
import asyncio
from core_py import context, httpx
async def main() -> None:
payload = {}
with context.use_context():
context.set_trace_id("trace-1")
context.set_operator("user-1")
await httpx.get(
"http://example.com/api",
httpx.json_resp(payload),
).do()
print(payload)
asyncio.run(main())
import asyncio
from core_py import resource
async def main() -> None:
manager = resource.Manager()
async with await manager.open("ofa-res#data:text/plain;base64,aGVsbG8=") as stream:
body = await stream.body.read()
print(body.decode())
asyncio.run(main())
import asyncio
from core_py import dkit
async def main() -> None:
atomic = dkit.InMemoryAtomic(default_ttl=1)
kit = await dkit.new_default_kit(atomic)
async def critical_section() -> None:
print(kit.get_snowflake_id())
await kit.mutex_do("job", critical_section)
await atomic.close()
asyncio.run(main())
import asyncio
from dataclasses import dataclass
from core_py import context, model
from core_py.model import mongox
@dataclass
class Item(model.CreateAudit, model.UpdateAudit, model.DeleteAudit, model.TenantAudit):
id: str = ""
name: str = ""
async def main(collection: object) -> None:
repo = mongox.CollectionRepository[str, Item](collection, Item).with_repo_opt(
model.RepoOpt(data_isolation=model.DATA_ISOLATION_TENANT)
)
with context.use_context():
context.set_operator("user-1")
context.set_tenant_id("tenant-1")
created = await repo.create(Item(id="i-1", name="first"))
loaded = await repo.get(created.id)
print(loaded.name)
asyncio.run(main(collection))
Async API Notes
- In the current version, runtime IO capabilities follow an async-first design by default. The primary paths for
httpx,resource,dkit, andmodel.mongoxshould be called withawait. - Pure-logic or startup-time modules such as
context,trace,logging,config, anddataremain synchronous and can be used directly from async functions. - Objects that own resources should be closed explicitly, such as
resource.Streamopened withasync with,httpx.StreamResponse, anddkit.Atomicinstances after use. - The examples in this README are the recommended usage patterns. No sync-compatibility variants are provided here.
Commands
This project uses uv to manage dependencies and the lockfile. Run the following when entering the project for the first time:
make sync
Common commands:
make lock # generate or update uv.lock
make fmt # format src and tests
make lint # run ruff check
make type # run mypy
make test # run pytest
make build # build sdist and wheel
Full local verification:
make sync fmt lint type test
Packaging and Publishing
Packaging and publishing also use uv:
make build
This generates the source distribution and wheel under dist/.
Publish to PyPI:
make publish-pip
Before running this command, prepare the credentials required by uv publish, for example by setting UV_PUBLISH_TOKEN or by configuring authentication the way uv expects.
Publish to a local debugging environment:
make publish-local
This command builds the wheel first, then installs it into the current Python environment with uv pip install --system --force-reinstall dist/*.whl, which is convenient for local integration debugging.
Remove from the local environment:
make unpublish-local
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ofa_core_py-0.1.0.tar.gz.
File metadata
- Download URL: ofa_core_py-0.1.0.tar.gz
- Upload date:
- Size: 174.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.20 {"installer":{"name":"uv","version":"0.11.20","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
54dbaa8109dfc82ce0d5b355e99f93ed79efb8e46c7910b232b040887406d2b6
|
|
| MD5 |
3ed37a950a5a6ea4d426b8d3b551f2d4
|
|
| BLAKE2b-256 |
eca1a90af345719bddbdb86f4e22f1ca93018bc112400ddeb1361ef7d3fee147
|
File details
Details for the file ofa_core_py-0.1.0-py3-none-any.whl.
File metadata
- Download URL: ofa_core_py-0.1.0-py3-none-any.whl
- Upload date:
- Size: 55.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.20 {"installer":{"name":"uv","version":"0.11.20","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
75e9bbefbae27c6254114541364a90dfa979ff7d7272a79686814f3530bd02b7
|
|
| MD5 |
a93908efe0ff09b41909679dbbe6cb2b
|
|
| BLAKE2b-256 |
a0b6d7d44977d17b0bd135b247a78505571180e293c3d811750987455e62098c
|