Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ if client.get_boolean_value("to-the-moon-feature", False):

Octopus feature flags are boolean, so evaluate them with `get_boolean_value` or `get_boolean_details`. Evaluating a flag as a string, integer, float or object returns your default value with an error code.

If the provider can't fetch your flags, for example because the client identifier is wrong or Octopus is unreachable, it still reports itself ready, and keeps trying every `cache_duration`. Until a fetch succeeds, every evaluation returns your default value with the `PROVIDER_NOT_READY` error code.

Call `api.shutdown()` when your application stops, so the provider releases its resources.

For more on evaluating flags, see the [OpenFeature evaluation API documentation](https://openfeature.dev/docs/reference/concepts/evaluation-api/).
Expand All @@ -65,9 +67,9 @@ For more on evaluating flags, see the [OpenFeature evaluation API documentation]
| `cache_duration` | No | A `timedelta` for how often the provider checks for changed flags. Defaults to one minute. Must be positive. |
| `request_timeout` | No | A `timedelta` for how long a request to Octopus may take in total before it's abandoned. Defaults to 10 seconds. Must be positive. |
| `release_version_override` | No | Overrides the release version embedded in the client identifier. |
| `http_client` | No | An `httpx.Client` for requests to Octopus, for example to configure a proxy, TLS or instrumentation. The provider never closes a client you supply. If the client has its own timeouts, the shorter of those and `request_timeout` applies. By default, the provider creates and manages its own client. |
| `http_client` | No | An `httpx.Client` (not an `httpx.AsyncClient`) for requests to Octopus, for example to configure a proxy, TLS or instrumentation. The provider never closes a client you supply. If the client has its own timeouts, the shorter of those and `request_timeout` applies. By default, the provider creates and manages its own client. |

The provider takes a copy of the configuration when it's created, so later changes to the configuration don't affect it. It raises `ValueError` or `TypeError` if `client_identifier` is empty or isn't a string, or if `cache_duration` or `request_timeout` isn't a positive `timedelta`. `ProductMetadata` removes characters that aren't valid in an HTTP header token, and raises `ValueError` if the name, or a version you supply, has none left.
The provider takes a copy of the configuration when it's created, so later changes to the configuration don't affect it. It removes leading and trailing whitespace, such as a newline from a file or mounted secret, from `client_identifier` and `release_version_override`. It raises `ValueError` or `TypeError` if either of those is empty, isn't a string, or contains characters other than printable ASCII, if `cache_duration` or `request_timeout` isn't a positive `timedelta`, or if `http_client` isn't an `httpx.Client`. `ProductMetadata` removes characters that aren't valid in an HTTP header token, and raises `ValueError` if the name, or a version you supply, has none left.

### Logging

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ class FeatureFlagEvaluatorCache:
"""Holds the evaluator the provider resolves flags against, and keeps it
updated by polling the feature flags service.

Until a fetch succeeds it holds an empty evaluator, so every flag is
missing. A failed refresh keeps the last good evaluator.
Until a fetch succeeds it holds an empty evaluator with no content hash,
which the provider treats as not ready. A failed refresh keeps the last
good evaluator.
"""

def __init__(
Expand Down
102 changes: 79 additions & 23 deletions src/octopus_openfeature_provider/_octopus_feature_provider.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import copy
import re
import threading
from collections.abc import Mapping, Sequence
from datetime import timedelta

import httpx
from openfeature.evaluation_context import EvaluationContext
from openfeature.exception import FlagNotFoundError, TypeMismatchError
from openfeature.exception import (
FlagNotFoundError,
ProviderNotReadyError,
TypeMismatchError,
)
from openfeature.flag_evaluation import FlagResolutionDetails, FlagValueType
from openfeature.provider import AbstractProvider, Metadata

from octopus_openfeature_provider._feature_flag_api_client import FeatureFlagApiClient
from octopus_openfeature_provider._feature_flag_evaluator import FLAG_NOT_FOUND_MESSAGE
from octopus_openfeature_provider._feature_flag_evaluator import (
FLAG_NOT_FOUND_MESSAGE,
FeatureFlagEvaluator,
)
from octopus_openfeature_provider._feature_flag_evaluator_cache import (
FeatureFlagEvaluatorCache,
)
Expand All @@ -19,35 +28,51 @@

MAX_CACHE_DURATION = timedelta(seconds=threading.TIMEOUT_MAX)

PROVIDER_NOT_READY_MESSAGE = "No Octopus feature flags are available. The provider failed to initialize, or was used before initializing."

# httpx sends header values as ASCII, and rejects control characters in them.
_INVALID_HEADER_VALUE_CHARACTERS = re.compile(r"[^\x20-\x7e]")


class OctopusFeatureProvider(AbstractProvider):
"""An OpenFeature provider for Octopus feature flags.

Register it with the OpenFeature SDK, for example with
`openfeature.api.set_provider`. Octopus feature flags are booleans only.

Until the provider has fetched the flags, every evaluation returns the
default value with the `PROVIDER_NOT_READY` error code.

Leading and trailing whitespace, such as the newline at the end of a value
read from a file, is removed from the client identifier and the release
version override.

Raises:
ValueError: If the configuration's client identifier is empty, or its
`cache_duration` or `request_timeout` isn't positive, or its
`cache_duration` is longer than `threading.TIMEOUT_MAX` seconds.
TypeError: If the configuration's client identifier isn't a `str`,
or its `cache_duration` or `request_timeout` isn't a `timedelta`.
ValueError: If the configuration's client identifier or release
version override is empty or contains characters that aren't valid
in an HTTP header, or its `cache_duration` or `request_timeout`
isn't positive, or its `cache_duration` is longer than
`threading.TIMEOUT_MAX` seconds.
TypeError: If the configuration's client identifier or release version
override isn't a `str`, its `cache_duration` or `request_timeout`
isn't a `timedelta`, or its `http_client` isn't an `httpx.Client`.
"""

def __init__(self, configuration: OctopusFeatureConfiguration) -> None:
super().__init__()
# A shallow copy, so the provider is unaffected by later changes to the
# configuration but still uses the caller's HTTP client.
self._configuration = copy.copy(configuration)
_validate(self._configuration)
_validate_and_clean(self._configuration)
self._evaluator_cache = FeatureFlagEvaluatorCache(
FeatureFlagApiClient(self._configuration),
self._configuration.cache_duration,
)

def initialize(self, evaluation_context: EvaluationContext) -> None:
# Never raises, so the SDK reports the provider as ready even when the
# fetch fails. Every flag is then missing until a refresh succeeds.
# fetch fails. Every evaluation then reports PROVIDER_NOT_READY until
# a refresh succeeds.
self._evaluator_cache.initialize()

def shutdown(self) -> None:
Expand All @@ -62,9 +87,7 @@ def resolve_boolean_details(
default_value: bool,
evaluation_context: EvaluationContext | None = None,
) -> FlagResolutionDetails[bool]:
return self._evaluator_cache.get_evaluator().evaluate(
flag_key, evaluation_context
)
return self._require_evaluator().evaluate(flag_key, evaluation_context)

def resolve_string_details(
self,
Expand Down Expand Up @@ -99,22 +122,31 @@ def resolve_object_details(
raise self._reject_non_boolean_evaluation(flag_key)

def _reject_non_boolean_evaluation(self, flag_key: str) -> Exception:
evaluator = self._evaluator_cache.get_evaluator()
evaluator = self._require_evaluator()
if evaluator.find_evaluation_by_slug(flag_key) is None:
return FlagNotFoundError(FLAG_NOT_FOUND_MESSAGE)
return TypeMismatchError("Octopus only supports boolean flags.")


def _validate(configuration: OctopusFeatureConfiguration) -> None:
client_identifier = configuration.client_identifier
# Callers without a type checker may pass None, for example from an unset
# environment variable.
if not isinstance(client_identifier, str):
raise TypeError(
f"client_identifier must be a str, but was {type(client_identifier).__name__}."
def _require_evaluator(self) -> FeatureFlagEvaluator:
"""Without any evaluations, an unknown slug can't be told apart from
one that was never received, so report PROVIDER_NOT_READY rather than
masking the failure as FLAG_NOT_FOUND."""
evaluator = self._evaluator_cache.get_evaluator()
# Every successful fetch has a content hash, so an empty one means no
# fetch has succeeded yet.
if not evaluator.content_hash:
raise ProviderNotReadyError(PROVIDER_NOT_READY_MESSAGE)
return evaluator


def _validate_and_clean(configuration: OctopusFeatureConfiguration) -> None:
configuration.client_identifier = _clean_header_value(
"client_identifier", configuration.client_identifier
)
if configuration.release_version_override is not None:
configuration.release_version_override = _clean_header_value(
"release_version_override", configuration.release_version_override
)
if not client_identifier.strip():
raise ValueError("client_identifier must not be empty.")
_validate_positive_duration("cache_duration", configuration.cache_duration)
# The polling thread waits this long between checks, and a longer wait
# raises OverflowError there, which would stop polling without a log.
Expand All @@ -123,6 +155,30 @@ def _validate(configuration: OctopusFeatureConfiguration) -> None:
f"cache_duration must be at most {MAX_CACHE_DURATION}, but was {configuration.cache_duration}."
)
_validate_positive_duration("request_timeout", configuration.request_timeout)
http_client = configuration.http_client
# An httpx.AsyncClient would otherwise fail every request, because its
# methods return coroutines that are never awaited.
if http_client is not None and not isinstance(http_client, httpx.Client):
raise TypeError(
f"http_client must be an httpx.Client, but was {type(http_client).__name__}."
)


def _clean_header_value(name: str, value: str) -> str:
# Callers without a type checker may pass None, for example from an unset
# environment variable.
if not isinstance(value, str):
raise TypeError(f"{name} must be a str, but was {type(value).__name__}.")
# Values read from a file or a mounted secret often end with a newline,
# which httpx would reject on every request.
cleaned = value.strip()
if not cleaned:
raise ValueError(f"{name} must not be empty.")
if _INVALID_HEADER_VALUE_CHARACTERS.search(cleaned):
raise ValueError(
f"{name} must contain only printable ASCII characters, so it can be sent in an HTTP header."
)
return cleaned


def _validate_positive_duration(name: str, value: timedelta) -> None:
Expand Down
Loading