Skip to content

Commit fa6eec1

Browse files
fix: Convert datetime attributes to ISO-8601 strings (#61)
Evaluation context attributes are now converted to values the LaunchDarkly context model can represent, instead of being passed through as-is. - A `datetime` attribute previously reached the LaunchDarkly context unchanged, so the context could not be serialized: `json.dumps` on it raises `TypeError: Object of type datetime is not JSON serializable`, which breaks analytics event delivery for that context. - `datetime` values now become their ISO-8601 representation in UTC, which is the format the LaunchDarkly date targeting operators accept. A naive `datetime` is treated as UTC. - The conversion recurses into lists and dictionaries, so a nested `datetime` is converted too. - A value of a type which cannot be represented becomes `None` and logs an error, rather than producing an unusable context. This aligns the Python provider with the Java, .NET, and JavaScript providers, which already convert their SDK's date values, and with the `date or instant` row of the OpenFeature provider behavior spec's value conversion table. Found during the weekly OpenFeature provider audit. <details> <summary>Implementation details</summary> **Requirements** - [x] I have added test coverage for new or changed functionality - [x] I have followed the repository's [pull request submission guidelines](../blob/main/CONTRIBUTING.md#submitting-pull-requests) - [x] I have validated my changes against all supported platform versions **Related issues** None. **Describe the solution you've provided** `_to_ld_value` in the context converter handles the OpenFeature value types: scalars pass through, a `datetime` is converted with `astimezone(timezone.utc).isoformat()` (with the `+00:00` offset written as `Z`), mappings and sequences are converted item by item, and anything else becomes `None` with an error log. Custom attributes are set through it; `name`, `anonymous`, and `privateAttributes` keep their existing type-specific handling. `datetime` is one of the types the OpenFeature Python SDK's `EvaluationContextAttribute` alias allows, so an application following the OpenFeature specification can supply one. **Describe alternatives you've considered** Rejecting a `datetime` attribute and logging an error: that loses targeting information the application intended to send, and date targeting operators exist precisely for this case. Treating a naive `datetime` as local time: the local zone of a server is incidental, so the same context would convert differently depending on where it ran. **Additional context** Testing: `make lint` (mypy) and `make test` (86 tests). The new tests cover an aware `datetime`, a non-UTC offset, a naive `datetime`, a `datetime` nested inside a dictionary and list, JSON serializability of the resulting context, and an unconvertible value. The README's OpenFeature specific considerations section documents the conversion. </details> Link to Devin session: https://app.devin.ai/sessions/fe1eb757fe694ef79f3d09f6307d4b47 Open in Devin Desktop: https://app.devin.ai/desktop/session/fe1eb757fe694ef79f3d09f6307d4b47?variant=devin Requested by: @kinyoklion <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Overview** > **Evaluation context attributes are normalized before they are set on LaunchDarkly contexts**, fixing cases where a `datetime` on the context broke JSON serialization (e.g. analytics events). > > Custom attributes now pass through `_to_ld_value`: `datetime` values become ISO-8601 strings in UTC (naive datetimes treated as UTC, `+00:00` rendered as `Z`), with the same conversion applied inside nested lists and dicts. Scalars pass through unchanged; types the LD model cannot represent are logged and stored as `None`. Special handling for `name`, `anonymous`, and `privateAttributes` is unchanged. > > The README documents this behavior. New tests cover aware/offset/naive datetimes, nesting, JSON serializability, and unsupported types. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 847f090. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-authored-by: Devin AI <devin-ai-integration[bot]@users.noreply.github.com>
1 parent 1584451 commit fa6eec1

3 files changed

Lines changed: 63 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,8 @@ There are several other attributes which have special functionality within a sin
9595
- A key of `anonymous`. Must be a boolean value. [Equivalent to the 'anonymous' builder method in the SDK.](https://launchdarkly-python-sdk.readthedocs.io/en/latest/api-main.html#ldclient.ContextBuilder.anonymous)
9696
- A key of `name`. Must be a string. [Equivalent to the 'name' builder method in the SDK.](https://launchdarkly-python-sdk.readthedocs.io/en/latest/api-main.html#ldclient.ContextBuilder.name)
9797

98+
The LaunchDarkly context model has no date type, so a `datetime` attribute is converted to a string containing its ISO-8601 representation in UTC, which is the format the LaunchDarkly date targeting operators accept. A `datetime` without a timezone is treated as UTC. This conversion is applied to `datetime` values nested in lists and dictionaries as well.
99+
98100
### Examples
99101

100102
#### A single user context

‎ld_openfeature/impl/context_converter.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
from datetime import datetime, timezone
12
from logging import getLogger
2-
from typing import Any, Dict, List, Mapping, Optional
3+
from typing import Any, Dict, List, Mapping, Optional, Sequence
34

45
from ldclient.context import Context, ContextBuilder, ContextMultiBuilder
56
from openfeature.evaluation_context import EvaluationContext, EvaluationContextAttribute
@@ -8,6 +9,33 @@
89
logger = getLogger("launchdarkly-openfeature-server")
910

1011

12+
def _to_ld_value(value: Any) -> Any:
13+
"""
14+
Convert an OpenFeature attribute value into a value the LaunchDarkly SDK can represent.
15+
16+
A datetime becomes its ISO-8601 representation in UTC, because the LaunchDarkly value model has
17+
no date type. A datetime without a timezone is treated as UTC. A value which cannot be
18+
converted becomes None.
19+
"""
20+
if value is None or isinstance(value, (bool, int, float, str)):
21+
return value
22+
23+
if isinstance(value, datetime):
24+
if value.tzinfo is None:
25+
value = value.replace(tzinfo=timezone.utc)
26+
27+
return value.astimezone(timezone.utc).isoformat().replace('+00:00', 'Z')
28+
29+
if isinstance(value, Mapping):
30+
return {str(k): _to_ld_value(v) for k, v in value.items()}
31+
32+
if isinstance(value, Sequence):
33+
return [_to_ld_value(item) for item in value]
34+
35+
logger.error("The attribute value of type %s could not be converted; using None instead", type(value).__name__)
36+
return None
37+
38+
1139
class EvaluationContextConverter:
1240
def to_ld_context(self, context: EvaluationContext) -> Context:
1341
"""
@@ -108,6 +136,6 @@ def __build_single_context(self, attributes: Mapping[str, EvaluationContextAttri
108136
elif k == 'privateAttributes':
109137
logger.error("The attribute 'privateAttributes' must be an array")
110138
else:
111-
builder.set(k, v)
139+
builder.set(k, _to_ld_value(v))
112140

113141
return builder.build()

‎tests/impl/test_context_converter.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
import json
2+
from datetime import datetime, timedelta, timezone
13
from typing import Mapping
4+
25
import pytest
36
from openfeature.evaluation_context import EvaluationContext, EvaluationContextAttribute
47

@@ -219,3 +222,31 @@ def test_handles_invalid_nested_contexts(context_converter: EvaluationContextCon
219222

220223
assert ld_context.valid is False
221224
assert ld_context.multiple is False
225+
226+
def test_converts_datetime_attributes_to_iso_8601(context_converter: EvaluationContextConverter):
227+
attributes: Mapping[str, EvaluationContextAttribute] = {
228+
'signupDate': datetime(2024, 3, 1, 12, 30, 45, tzinfo=timezone.utc),
229+
'offsetDate': datetime(2024, 3, 1, 7, 30, 45, tzinfo=timezone(timedelta(hours=-5))),
230+
'naiveDate': datetime(2024, 3, 1, 12, 30, 45),
231+
'nested': {'dates': [datetime(2024, 3, 1, 12, 30, 45, tzinfo=timezone.utc)]},
232+
}
233+
context = EvaluationContext('user-key', attributes)
234+
ld_context = context_converter.to_ld_context(context)
235+
236+
assert ld_context.valid is True
237+
assert ld_context.get('signupDate') == '2024-03-01T12:30:45Z'
238+
assert ld_context.get('offsetDate') == '2024-03-01T12:30:45Z'
239+
assert ld_context.get('naiveDate') == '2024-03-01T12:30:45Z'
240+
assert ld_context.get('nested') == {'dates': ['2024-03-01T12:30:45Z']}
241+
242+
assert json.dumps(ld_context.to_dict())
243+
244+
245+
def test_uses_none_for_a_value_which_cannot_be_converted(context_converter: EvaluationContextConverter, caplog):
246+
context = EvaluationContext('user-key', {'unsupported': object()}) # type: ignore[dict-item]
247+
ld_context = context_converter.to_ld_context(context)
248+
249+
assert ld_context.valid is True
250+
assert ld_context.get('unsupported') is None
251+
252+
assert caplog.records[0].message == 'The attribute value of type object could not be converted; using None instead'

0 commit comments

Comments
 (0)