Skip to content

Commit

Permalink
merge main
Browse files Browse the repository at this point in the history
  • Loading branch information
leohoare committed Jan 12, 2025
2 parents 4ec15be + cbace6a commit 80f54f1
Show file tree
Hide file tree
Showing 21 changed files with 465 additions and 43 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ jobs:

- if: matrix.python-version == '3.11'
name: Upload coverage to Codecov
uses: codecov/codecov-action@v4.6.0
uses: codecov/codecov-action@v5.1.2
with:
flags: unittests # optional
name: coverage # optional
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,5 @@ jobs:
run: hatch build

- name: Publish a Python distribution to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
# pinning till fixed https://github.com/pypa/gh-action-pypi-publish/issues/300
uses: pypa/gh-action-pypi-publish@release/v1.11
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
default_stages: [commit]
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.2
rev: v0.9.1
hooks:
- id: ruff
args: [--fix]
Expand All @@ -16,7 +16,7 @@ repos:
- id: check-merge-conflict

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
rev: v1.14.1
hooks:
- id: mypy
files: openfeature
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{".":"0.7.2"}
{".":"0.7.4"}
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,33 @@
# Changelog

## [0.7.4](https://github.com/open-feature/python-sdk/compare/v0.7.3...v0.7.4) (2024-11-25)


### 🧹 Chore

* **deps:** update pre-commit hook astral-sh/ruff-pre-commit to v0.8.0 ([#395](https://github.com/open-feature/python-sdk/issues/395)) ([cd737a9](https://github.com/open-feature/python-sdk/commit/cd737a9a6aeb6ff64050f759749aab96e73a8c34))

## [0.7.3](https://github.com/open-feature/python-sdk/compare/v0.7.2...v0.7.3) (2024-11-24)


### ✨ New Features

* implement transaction context ([#389](https://github.com/open-feature/python-sdk/issues/389)) ([9b97130](https://github.com/open-feature/python-sdk/commit/9b97130908c5ec07580d66e0f2aad9adf1607f53))


### 🧹 Chore

* **deps:** update codecov/codecov-action action to v5 ([#386](https://github.com/open-feature/python-sdk/issues/386)) ([6cd570f](https://github.com/open-feature/python-sdk/commit/6cd570f64cb50473e0a046d5928e114157598d78))
* **deps:** update codecov/codecov-action action to v5.0.2 ([#388](https://github.com/open-feature/python-sdk/issues/388)) ([e72e329](https://github.com/open-feature/python-sdk/commit/e72e329a2acda0a0399ef2faa04c9b7f3b29bb65))
* **deps:** update codecov/codecov-action action to v5.0.3 ([#390](https://github.com/open-feature/python-sdk/issues/390)) ([3fb7cbc](https://github.com/open-feature/python-sdk/commit/3fb7cbc3ddcc9016ed51e890d9648f1f96284170))
* **deps:** update codecov/codecov-action action to v5.0.4 ([#391](https://github.com/open-feature/python-sdk/issues/391)) ([9759bfa](https://github.com/open-feature/python-sdk/commit/9759bfaa21ed6d6e5e84c5559304db9a49b61884))
* **deps:** update codecov/codecov-action action to v5.0.5 ([#392](https://github.com/open-feature/python-sdk/issues/392)) ([a652004](https://github.com/open-feature/python-sdk/commit/a652004fde72cb1dcf730f146db36d686589b642))
* **deps:** update codecov/codecov-action action to v5.0.6 ([#393](https://github.com/open-feature/python-sdk/issues/393)) ([24970b5](https://github.com/open-feature/python-sdk/commit/24970b5d0915f533d88e4cd0fb54bea8cd28cab0))
* **deps:** update codecov/codecov-action action to v5.0.7 ([#394](https://github.com/open-feature/python-sdk/issues/394)) ([f024a6f](https://github.com/open-feature/python-sdk/commit/f024a6f3407b3e3ce8ea16a80982a7642c9f2f20))
* **deps:** update pre-commit hook astral-sh/ruff-pre-commit to v0.7.2 ([#381](https://github.com/open-feature/python-sdk/issues/381)) ([2d8fadf](https://github.com/open-feature/python-sdk/commit/2d8fadf40afb98e2915b645278358fca367447d7))
* **deps:** update pre-commit hook astral-sh/ruff-pre-commit to v0.7.3 ([#384](https://github.com/open-feature/python-sdk/issues/384)) ([1eb6f4c](https://github.com/open-feature/python-sdk/commit/1eb6f4c6558f3dd20cb2389f9650a6476ca20fcb))
* **deps:** update pre-commit hook astral-sh/ruff-pre-commit to v0.7.4 ([#387](https://github.com/open-feature/python-sdk/issues/387)) ([3d77f24](https://github.com/open-feature/python-sdk/commit/3d77f2410751646380f58a77cad0fd5851da30b5))

## [0.7.2](https://github.com/open-feature/python-sdk/compare/v0.7.1...v0.7.2) (2024-10-24)


Expand Down
109 changes: 95 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

<!-- x-release-please-start-version -->

<a href="https://github.com/open-feature/python-sdk/releases/tag/v0.7.2">
<img alt="Latest version" src="https://img.shields.io/static/v1?label=release&message=v0.7.2&color=blue&style=for-the-badge" />
<a href="https://github.com/open-feature/python-sdk/releases/tag/v0.7.4">
<img alt="Latest version" src="https://img.shields.io/static/v1?label=release&message=v0.7.4&color=blue&style=for-the-badge" />
</a>

<!-- x-release-please-end -->
Expand Down Expand Up @@ -60,13 +60,13 @@
#### Pip install

```bash
pip install openfeature-sdk==0.7.2
pip install openfeature-sdk==0.7.4
```

#### requirements.txt

```bash
openfeature-sdk==0.7.2
openfeature-sdk==0.7.4
```

```python
Expand Down Expand Up @@ -99,16 +99,17 @@ print("Value: " + str(flag_value))

## 🌟 Features

| Status | Features | Description |
| ------ | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|| [Providers](#providers) | Integrate with a commercial, open source, or in-house feature management tool. |
|| [Targeting](#targeting) | Contextually-aware flag evaluation using [evaluation context](https://openfeature.dev/docs/reference/concepts/evaluation-context). |
|| [Hooks](#hooks) | Add functionality to various stages of the flag evaluation life-cycle. |
|| [Logging](#logging) | Integrate with popular logging packages. |
|| [Domains](#domains) | Logically bind clients with providers. |
|| [Eventing](#eventing) | React to state changes in the provider or flag management system. |
|| [Shutdown](#shutdown) | Gracefully clean up a provider during application shutdown. |
|| [Extending](#extending) | Extend OpenFeature with custom providers and hooks. |
| Status | Features | Description |
|--------|---------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------|
|| [Providers](#providers) | Integrate with a commercial, open source, or in-house feature management tool. |
|| [Targeting](#targeting) | Contextually-aware flag evaluation using [evaluation context](https://openfeature.dev/docs/reference/concepts/evaluation-context). |
|| [Hooks](#hooks) | Add functionality to various stages of the flag evaluation life-cycle. |
|| [Logging](#logging) | Integrate with popular logging packages. |
|| [Domains](#domains) | Logically bind clients with providers. |
|| [Eventing](#eventing) | React to state changes in the provider or flag management system. |
|| [Shutdown](#shutdown) | Gracefully clean up a provider during application shutdown. |
|| [Transaction Context Propagation](#transaction-context-propagation) | Set a specific [evaluation context](/docs/reference/concepts/evaluation-context) for a transaction (e.g. an HTTP request or a thread) |
|| [Extending](#extending) | Extend OpenFeature with custom providers and hooks. |

<sub>Implemented: ✅ | In-progress: ⚠️ | Not implemented yet: ❌</sub>

Expand Down Expand Up @@ -235,6 +236,86 @@ def on_provider_ready(event_details: EventDetails):
client.add_handler(ProviderEvent.PROVIDER_READY, on_provider_ready)
```

### Transaction Context Propagation

Transaction context is a container for transaction-specific evaluation context (e.g. user id, user agent, IP).
Transaction context can be set where specific data is available (e.g. an auth service or request handler) and by using the transaction context propagator it will automatically be applied to all flag evaluations within a transaction (e.g. a request or thread).

You can implement a different transaction context propagator by implementing the `TransactionContextPropagator` class exported by the OpenFeature SDK.
In most cases you can use `ContextVarsTransactionContextPropagator` as it works for `threads` and `asyncio` using [Context Variables](https://peps.python.org/pep-0567/).

The following example shows a **multithreaded** Flask application using transaction context propagation to propagate the request ip and user id into request scoped transaction context.

```python
from flask import Flask, request
from openfeature import api
from openfeature.evaluation_context import EvaluationContext
from openfeature.transaction_context import ContextVarsTransactionContextPropagator

# Initialize the Flask app
app = Flask(__name__)

# Set the transaction context propagator
api.set_transaction_context_propagator(ContextVarsTransactionContextPropagator())

# Middleware to set the transaction context
# You can call api.set_transaction_context anywhere you have information,
# you want to have available in the code-paths below the current one.
@app.before_request
def set_request_transaction_context():
ip = request.headers.get("X-Forwarded-For", request.remote_addr)
user_id = request.headers.get("User-Id") # Assuming we're getting the user ID from a header
evaluation_context = EvaluationContext(targeting_key=user_id, attributes={"ipAddress": ip})
api.set_transaction_context(evaluation_context)

def create_response() -> str:
# This method can be anywhere in our code.
# The feature flag evaluation will automatically contain the transaction context merged with other context
new_response = api.get_client().get_string_value("response-message", "Hello User!")
return f"Message from server: {new_response}"

# Example route where we use the transaction context
@app.route('/greeting')
def some_endpoint():
return create_response()
```

This also works for asyncio based implementations e.g. FastApi as seen in the following example:

```python
from fastapi import FastAPI, Request
from openfeature import api
from openfeature.evaluation_context import EvaluationContext
from openfeature.transaction_context import ContextVarsTransactionContextPropagator

# Initialize the FastAPI app
app = FastAPI()

# Set the transaction context propagator
api.set_transaction_context_propagator(ContextVarsTransactionContextPropagator())

# Middleware to set the transaction context
@app.middleware("http")
async def set_request_transaction_context(request: Request, call_next):
ip = request.headers.get("X-Forwarded-For", request.client.host)
user_id = request.headers.get("User-Id") # Assuming we're getting the user ID from a header
evaluation_context = EvaluationContext(targeting_key=user_id, attributes={"ipAddress": ip})
api.set_transaction_context(evaluation_context)
response = await call_next(request)
return response

def create_response() -> str:
# This method can be located anywhere in our code.
# The feature flag evaluation will automatically include the transaction context merged with other context.
new_response = api.get_client().get_string_value("response-message", "Hello User!")
return f"Message from server: {new_response}"

# Example route where we use the transaction context
@app.get('/greeting')
async def some_endpoint():
return create_response()
```

### Shutdown

The OpenFeature API provides a shutdown function to perform a cleanup of all registered providers. This should only be called when your application is in the process of shutting down.
Expand Down
44 changes: 36 additions & 8 deletions openfeature/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,33 @@
from openfeature.provider import FeatureProvider
from openfeature.provider._registry import provider_registry
from openfeature.provider.metadata import Metadata
from openfeature.transaction_context import TransactionContextPropagator
from openfeature.transaction_context.no_op_transaction_context_propagator import (
NoOpTransactionContextPropagator,
)

__all__ = [
"get_client",
"set_provider",
"clear_providers",
"get_provider_metadata",
"get_evaluation_context",
"set_evaluation_context",
"add_handler",
"add_hooks",
"clear_hooks",
"clear_providers",
"get_client",
"get_evaluation_context",
"get_hooks",
"shutdown",
"add_handler",
"get_provider_metadata",
"get_transaction_context",
"remove_handler",
"set_evaluation_context",
"set_provider",
"set_transaction_context",
"set_transaction_context_propagator",
"shutdown",
]

_evaluation_context = EvaluationContext()
_evaluation_transaction_context_propagator: TransactionContextPropagator = (
NoOpTransactionContextPropagator()
)

_hooks: typing.List[Hook] = []

Expand Down Expand Up @@ -68,6 +78,24 @@ def set_evaluation_context(evaluation_context: EvaluationContext) -> None:
_evaluation_context = evaluation_context


def set_transaction_context_propagator(
transaction_context_propagator: TransactionContextPropagator,
) -> None:
global _evaluation_transaction_context_propagator
_evaluation_transaction_context_propagator = transaction_context_propagator


def get_transaction_context() -> EvaluationContext:
return _evaluation_transaction_context_propagator.get_transaction_context()


def set_transaction_context(evaluation_context: EvaluationContext) -> None:
global _evaluation_transaction_context_propagator
_evaluation_transaction_context_propagator.set_transaction_context(
evaluation_context
)


def add_hooks(hooks: typing.List[Hook]) -> None:
global _hooks
_hooks = _hooks + hooks
Expand Down
7 changes: 5 additions & 2 deletions openfeature/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,9 +510,12 @@ def _before_hooks_and_merge_context(
if evaluation_context:
invocation_context = invocation_context.merge(ctx2=evaluation_context)

# Requirement 3.2.2 merge: API.context->client.context->invocation.context
# Requirement 3.2.2 merge: API.context->transaction.context->client.context->invocation.context
merged_context = (
api.get_evaluation_context().merge(self.context).merge(invocation_context)
api.get_evaluation_context()
.merge(api.get_transaction_context())
.merge(self.context)
.merge(invocation_context)
)
return merged_context

Expand Down
2 changes: 1 addition & 1 deletion openfeature/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from openfeature.exception import ErrorCode

__all__ = ["ProviderEvent", "ProviderEventDetails", "EventDetails", "EventHandler"]
__all__ = ["EventDetails", "EventHandler", "ProviderEvent", "ProviderEventDetails"]


class ProviderEvent(Enum):
Expand Down
12 changes: 6 additions & 6 deletions openfeature/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
from enum import Enum

__all__ = [
"OpenFeatureError",
"ProviderNotReadyError",
"ProviderFatalError",
"ErrorCode",
"FlagNotFoundError",
"GeneralError",
"InvalidContextError",
"OpenFeatureError",
"ParseError",
"TypeMismatchError",
"ProviderFatalError",
"ProviderNotReadyError",
"TargetingKeyMissingError",
"InvalidContextError",
"ErrorCode",
"TypeMismatchError",
]


Expand Down
6 changes: 3 additions & 3 deletions openfeature/flag_evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@


__all__ = [
"FlagType",
"Reason",
"FlagMetadata",
"FlagEvaluationDetails",
"FlagEvaluationOptions",
"FlagMetadata",
"FlagResolutionDetails",
"FlagType",
"Reason",
]


Expand Down
2 changes: 1 addition & 1 deletion openfeature/hook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from openfeature.client import ClientMetadata
from openfeature.provider.metadata import Metadata

__all__ = ["HookType", "HookContext", "HookHints", "Hook"]
__all__ = ["Hook", "HookContext", "HookHints", "HookType"]


class HookType(Enum):
Expand Down
11 changes: 11 additions & 0 deletions openfeature/transaction_context/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from openfeature.transaction_context.context_var_transaction_context_propagator import (
ContextVarsTransactionContextPropagator,
)
from openfeature.transaction_context.transaction_context_propagator import (
TransactionContextPropagator,
)

__all__ = [
"ContextVarsTransactionContextPropagator",
"TransactionContextPropagator",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from contextvars import ContextVar
from typing import Optional

from openfeature.evaluation_context import EvaluationContext
from openfeature.transaction_context.transaction_context_propagator import (
TransactionContextPropagator,
)


class ContextVarsTransactionContextPropagator(TransactionContextPropagator):
_transaction_context_var: ContextVar[Optional[EvaluationContext]] = ContextVar(
"transaction_context", default=None
)

def get_transaction_context(self) -> EvaluationContext:
context = self._transaction_context_var.get()
if context is None:
context = EvaluationContext()
self._transaction_context_var.set(context)

return context

def set_transaction_context(self, transaction_context: EvaluationContext) -> None:
self._transaction_context_var.set(transaction_context)
Loading

0 comments on commit 80f54f1

Please sign in to comment.