diff --git a/docs/understand/scenarios/parametric.md b/docs/understand/scenarios/parametric.md index 4f63f91a74d..97a43d8f141 100644 --- a/docs/understand/scenarios/parametric.md +++ b/docs/understand/scenarios/parametric.md @@ -234,6 +234,14 @@ Use `mocked_backend.client.ffe_set_response` or `mocked_backend.client.ffe_set_r The protobuf response IDs `selection_ignored_empty`, `selection_ignored_tag_load_failed`, and `selection_ignored_unknown` return the full rules fixture with a `DD-Flag-Selection-Ignored` header set to an empty string, `tag_load_failed`, or `future_reason`, respectively. Use these shared responses to test selection diagnostics without replacing the rules endpoint handler. The `valid` response omits the header. +#### Standalone Precomputation + +`test_library.ffe_precompute_configuration(payload)` calls `POST /ffe/precompute-configuration` (Node.js only). It starts a fresh process without tracer/provider initialization and calls the public `dd-trace/openfeature/rules-based` helpers. Supply either a serialized `wire` or `fetchOptions` (using the same custom transport as the rules-fetch endpoint), an array of `contexts`, and optional precomputation `options`. One configuration is reused for every context. No browser is initialized. + +Success returns `{ "results": [{ "wire": "...", "errors": [{ "flagKey": "...", "errorCode": "PARSE_ERROR" }] }], "httpRequests": 0, "exposureEvents": 0 }`. The error array contains omitted-flag diagnostics. Expected input/fetch failures return an `error` object with `name`, `code`, and `message`, plus the same counters; unexpected failures return HTTP 500. Input validation failures expect zero requests. HTTP fetch failures expect one request and include `error.status`; successful fetching followed by precomputation also expects one request. Local conversion expects zero requests. + +Counts observe Node's Undici/HTTP request diagnostics and the `ffe:exposure:submit` channel, from before import until child-process exit. They do not directly observe queued evaluation telemetry, which has no corresponding diagnostic channel. + #### Effective OpenTelemetry configuration Use `test_library.otel_effective_config()` to inspect resolved OTLP exporter timeouts. diff --git a/docs/understand/weblogs/parametric_weblog.md b/docs/understand/weblogs/parametric_weblog.md index 7a266ce1d25..e0e18c025f6 100644 --- a/docs/understand/weblogs/parametric_weblog.md +++ b/docs/understand/weblogs/parametric_weblog.md @@ -1001,6 +1001,12 @@ Called by `ParametricTestClientApi.ffe_fetch_rules_configuration()`. Fetch and s **Not implemented by the Python reference server**. The request body is the `options` object of the test: see [Standalone Rules Configuration](../scenarios/parametric.md#standalone-rules-configuration). +#### `POST /ffe/precompute-configuration` + +Called by `ParametricTestClientApi.ffe_precompute_configuration()`. Precompute portable rules for one or more contexts in a fresh process without tracer/provider initialization. + +**Not implemented by the Python reference server**. See [Standalone Precomputation](../scenarios/parametric.md#standalone-precomputation) for the request payload, typed errors, and observed request/exposure counts. Input validation failures expect zero requests; HTTP fetch failures expect one request and include `error.status`. + #### `POST /ffe/start` Called by `ParametricTestClientApi.ffe_start()`. Initialize the FFE (Feature Flagging & Experimentation) provider. diff --git a/manifests/nodejs.yml b/manifests/nodejs.yml index df5c34f0bf7..57a7fdae892 100644 --- a/manifests/nodejs.yml +++ b/manifests/nodejs.yml @@ -2755,6 +2755,7 @@ manifest: tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: *ref_6_25_0 tests/parametric/test_ffe/test_rules_configuration.py: 7.0.0-pre # Exact development version until the first containing release is confirmed. + tests/parametric/test_ffe/test_rules_configuration.py::Test_FFE_Rules_Configuration_Precompute: missing_feature (FFL-3536 requires the precomputation dependency and public exports in dd-trace-js) tests/parametric/test_ffe/test_rules_configuration.py::Test_FFE_Rules_Configuration_Selection: missing_feature (FFL-3364 requires the Node flag-selection dependency update in dd-trace-js) tests/parametric/test_ffe/test_serial_id_metadata.py: v6.18.0 tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/tests/ffe/README.md b/tests/ffe/README.md index bf46dcbf00a..6771134fcfe 100644 --- a/tests/ffe/README.md +++ b/tests/ffe/README.md @@ -63,7 +63,11 @@ configuration copies are needed. Standalone rules-configuration helpers are covered in `tests/parametric/test_ffe/test_rules_configuration.py` (Node.js only for now). These tests use `dd-trace/openfeature/rules-based` in a fresh process without initializing a tracer or provider, fetch protobuf over HTTP, and validate the portable wire output, channel credentials, typed errors, deadlines and cancellation during headers/body delivery, transport failures, invalid options, and redirect protection. They do not initialize a browser SDK or contact Datadog. -These tests report to [Offline initialization and portable configuration helpers (#562)](https://feature-parity.us1.prod.dog/?feature=562). Current coverage is limited to Node's rules-based fetching and serialization; precomputed helpers and provider offline initialization are not covered here. +These tests report to [Offline initialization and portable configuration helpers (#562)](https://feature-parity.us1.prod.dog/?feature=562). `Test_FFE_Rules_Configuration_Precompute` adds Node's local rules-to-precomputed conversion: context-specific assignments, metadata preservation, omitted failed/unassigned flags, sanitized input errors, and reuse of one fetch across multiple contexts. It observes Node HTTP diagnostics and the exposure channel through child-process exit to check that local precomputation adds no requests or exposure events. Queued evaluation telemetry is not directly observed. Provider offline initialization and browser handoff remain outside this coverage. + +The precomputation class requires [openfeature-js-client #448](https://github.com/DataDog/openfeature-js-client/pull/448) plus the dependency and public exports in `dd-trace/openfeature/rules-based`. It remains gated in the Node manifest until a containing build is available; other SDKs retain the existing file-level gate. + +To validate an unreleased build containing these changes, use the [custom Node tracer instructions](../../docs/execute/binaries.md#nodejs-library), select `tests/parametric/test_ffe/test_rules_configuration.py::Test_FFE_Rules_Configuration_Precompute`, and pass the same node ID to `-F`. The required new public exports are `configurationFromString`, `precomputeConfiguration`, and `ConfigurationPrecomputeError`. Once released, update the class gate and the existing file-level version restriction together. `Test_FFE_Rules_Configuration_Selection` covers tag/key-pattern query parameters on both distribution channels, invalid/URL-overflow selections dropped with diagnostics, quiet empty-selection omission, and retention of the full response when the backend ignores selection. It also checks diagnostics for nonempty `DD-Flag-Selection-Ignored` response headers, including unknown reasons. The mock does not implement backend filtering. These cases require [openfeature-js-client #445](https://github.com/DataDog/openfeature-js-client/pull/445) in the `dd-trace` dependency and remain gated in the Node manifest until a containing build is available. Other SDKs retain the existing file-level gate. @@ -79,7 +83,9 @@ PYTEST_XDIST_AUTO_NUM_WORKERS=1 TEST_LIBRARY=nodejs ./run.sh PARAMETRIC tests/pa Until the helpers are released, use a master build as described in the [custom Node.js binary instructions](../../docs/execute/binaries.md#nodejs-library). The Node manifest currently targets master's `7.0.0-pre` development version; update that gate to the actual release version once published. -The protobuf fixture `tests/parametric/test_ffe/rules-wire.json` comes from `openfeature-js-client/packages/browser/test/data/rules-v1-wire.json`. The test checks serialization without evaluating flags or depending on a browser package. +The protobuf fixture `tests/parametric/test_ffe/rules-wire.json` comes from `openfeature-js-client/packages/browser/test/data/rules-v1-wire.json`. Fetch-only tests check serialization without evaluation; the fetch-then-precompute case also resolves this fixture for two contexts. Neither path depends on a browser package. + +`precompute-rules.json` is the readable protobuf JSON source for `precompute-rules-wire.json`. It contains a US-targeted boolean, a false fallback with reason `DEFAULT`, a JSON-null assignment, an unassigned flag, and an unsupported-feature flag. The wire is encoded with `@bufbuild/protobuf`'s `fromJson`/`toBinary` and the `FlagsConfigurationSchema` from `flagging-core` at PR #448 commit `b2a42f26ce9ece08e5d317563b4246163d5d0acf`; it carries a deliberately distinct source ETag to check that precomputation does not forward it. ```bash ./run.sh FEATURE_FLAGGING_AND_EXPERIMENTATION --library diff --git a/tests/parametric/test_ffe/precompute-rules-wire.json b/tests/parametric/test_ffe/precompute-rules-wire.json new file mode 100644 index 00000000000..164a7d921b4 --- /dev/null +++ b/tests/parametric/test_ffe/precompute-rules-wire.json @@ -0,0 +1,7 @@ +{ + "version": 1, + "rules": { + "etag": "private-source-etag", + "response": "CgYIgPLWygYSBHRlc3QabwoIY2hlY2tvdXQSYxAEGgIoARoECAEoACJBCg11cy1hbGxvY2F0aW9uEAAiLBgqIAEqJgoKZXhwZXJpbWVudBIIY2hlY2tvdXQqBEhPT0sqCEVYUE9TVVJFKAEiEgoIZmFsbGJhY2siBhABGCsgBBorCgt1bnN1cHBvcnRlZBIcCOcHEAQaAigBIhEKC3Vuc3VwcG9ydGVkIgIgAxokCghudWxsYWJsZRIYEAUaBAgEMAAiDgoIbnVsbGFibGUiAiADGhQKCnVuYXNzaWduZWQSBhAEGgIoASIGEgQKAggDKgdlbmFibGVkKghkaXNhYmxlZCoCVVMqB2NvdW50cnkqCW51bGwtanNvbkIEbnVsbEoFKgMSAQJQAQ==" + } +} diff --git a/tests/parametric/test_ffe/precompute-rules.json b/tests/parametric/test_ffe/precompute-rules.json new file mode 100644 index 00000000000..d432987629e --- /dev/null +++ b/tests/parametric/test_ffe/precompute-rules.json @@ -0,0 +1,44 @@ +{ + "createdAt": "2026-01-01T00:00:00Z", + "environmentName": "test", + "observeFullEvaluationData": true, + "strings": ["enabled", "disabled", "US", "country", "null-json"], + "attributes": [{"attributePath": {"segments": [{"objectKeyStringIndex": 3}]}}], + "conditions": [{"stringMembership": {"stringIndexes": [2]}}], + "jsonStrings": ["null"], + "flags": { + "checkout": { + "variationType": "VARIATION_TYPE_BOOLEAN", + "variations": [ + {"keyStringIndex": 0, "booleanValue": true}, + {"keyStringIndex": 1, "booleanValue": false} + ], + "allocations": [ + { + "key": "us-allocation", + "targetingConditionIndex": 0, + "logExposureEvent": true, + "splits": [{ + "variationIndex": 0, + "reason": "REASON_TARGETING_MATCH", + "serialId": 42, + "features": [{"key": "experiment", "stringValue": "checkout", "destinations": ["HOOK", "EXPOSURE"]}] + }] + }, + {"key": "fallback", "splits": [{"variationIndex": 1, "reason": "REASON_DEFAULT", "serialId": 43}]} + ] + }, + "unsupported": { + "minimumFeatureLevel": 999, + "variationType": "VARIATION_TYPE_BOOLEAN", + "variations": [{"booleanValue": true}], + "allocations": [{"key": "unsupported", "splits": [{"reason": "REASON_STATIC"}]}] + }, + "nullable": { + "variationType": "VARIATION_TYPE_JSON", + "variations": [{"keyStringIndex": 4, "jsonStringIndex": 0}], + "allocations": [{"key": "nullable", "splits": [{"reason": "REASON_STATIC"}]}] + }, + "unassigned": {"variationType": "VARIATION_TYPE_BOOLEAN", "variations": [{"booleanValue": true}]} + } +} diff --git a/tests/parametric/test_ffe/test_rules_configuration.py b/tests/parametric/test_ffe/test_rules_configuration.py index 8a550f77344..f9ae5bc5397 100644 --- a/tests/parametric/test_ffe/test_rules_configuration.py +++ b/tests/parametric/test_ffe/test_rules_configuration.py @@ -1,6 +1,7 @@ """Standalone SSR producer contract; intentionally does not initialize a browser SDK.""" import base64 +from datetime import datetime import json from pathlib import Path from typing import Any @@ -16,6 +17,7 @@ API_KEY = "system-tests-api-key" CLIENT_OPTIONS = {"distributionChannel": "client", "clientToken": CLIENT_TOKEN, "env": "test env"} SELECTION_VECTORS_PATH = Path(__file__).parent / "ffe-system-test-data" / "flag-selection" / "selection-vectors.json" +PRECOMPUTE_WIRE = Path(__file__).with_name("precompute-rules-wire.json").read_text() @pytest.fixture @@ -402,3 +404,189 @@ def test_invalid_selection_is_not_sent(self, test_library: APMLibrary, mocked_ba case, url.query, ) + + +@scenarios.parametric +@features.feature_flags_portable_configuration +@slow +class Test_FFE_Rules_Configuration_Precompute: + def test_local_context_assignments_and_metadata( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + contexts = [ + {"targetingKey": "subject-us", "country": "US"}, + {"targetingKey": "subject-ca", "country": "CA"}, + ] + with test_library: + result = test_library.ffe_precompute_configuration({"wire": PRECOMPUTE_WIRE, "contexts": contexts}) + opted_out_context = {**contexts[0], "dd_experimentation_opt_out_at": "2026-10-01T00:00:00Z"} + opted_out = test_library.ffe_precompute_configuration( + { + "wire": PRECOMPUTE_WIRE, + "contexts": [opted_out_context], + "options": {"experimentationOptOutMode": "immediate"}, + } + ) + default_policy = test_library.ffe_precompute_configuration( + {"wire": PRECOMPUTE_WIRE, "contexts": [opted_out_context]} + ) + + assert "error" not in result, result + assert result["httpRequests"] == 0, result + assert result["exposureEvents"] == 0, result + assert mocked_backend.ffe_get_requests() == [] + assert len(result["results"]) == len(contexts), result + for context, output in zip(contexts, result["results"], strict=True): + wire = json.loads(output["wire"]) + assert set(wire) == {"version", "precomputed"}, wire + assert wire["version"] == 1 + snapshot = wire["precomputed"] + assert snapshot["context"] == context + assert "etag" not in snapshot + assert snapshot["fetchedAt"] > 0 + attributes = json.loads(snapshot["response"])["data"]["attributes"] + assert attributes["format"] == "PRECOMPUTED" + assert attributes["obfuscated"] is False + assert attributes["environment"] == {"name": "test"} + assert attributes["observeFullEvaluationData"] is True + assert "evaluation_options" not in attributes + assert datetime.fromisoformat(attributes["createdAt"]).timestamp() * 1000 == snapshot["fetchedAt"] + flags = attributes["flags"] + # No default assignment is invented for the unassigned or unsupported flags. + assert set(flags) == {"checkout", "nullable"}, flags + is_us = context["country"] == "US" + assert flags["checkout"] == { + "allocationKey": "us-allocation" if is_us else "fallback", + "variationKey": "enabled" if is_us else "disabled", + "variationType": "boolean", + "variationValue": is_us, + "reason": "TARGETING_MATCH" if is_us else "DEFAULT", + "doLog": is_us, + "serialId": 42 if is_us else 43, + **( + {"features": [{"key": "experiment", "value": "checkout", "destinations": ["HOOK", "EXPOSURE"]}]} + if is_us + else {} + ), + } + assert flags["checkout"]["variationValue"] is is_us + assert flags["checkout"]["doLog"] is is_us + assert flags["nullable"]["variationType"] == "object" + assert flags["nullable"]["variationValue"] is None + assert output["errors"] == [{"flagKey": "unsupported", "errorCode": "PARSE_ERROR"}] + assert "private-source-etag" not in output["wire"] + + assert "error" not in default_policy, default_policy + assert default_policy["httpRequests"] == 0, default_policy + assert default_policy["exposureEvents"] == 0, default_policy + assert len(default_policy["results"]) == 1, default_policy + default_snapshot = json.loads(default_policy["results"][0]["wire"])["precomputed"] + assert default_snapshot["context"] == opted_out_context + default_attributes = json.loads(default_snapshot["response"])["data"]["attributes"] + assert "evaluation_options" not in default_attributes + assert default_attributes["flags"]["checkout"]["allocationKey"] == "us-allocation" + assert default_attributes["flags"]["checkout"]["variationValue"] is True + + assert "error" not in opted_out, opted_out + assert opted_out["httpRequests"] == 0, opted_out + assert opted_out["exposureEvents"] == 0, opted_out + assert len(opted_out["results"]) == 1, opted_out + opted_out_result = opted_out["results"][0] + opted_out_snapshot = json.loads(opted_out_result["wire"])["precomputed"] + assert opted_out_snapshot["context"] == opted_out_context + opted_out_attributes = json.loads(opted_out_snapshot["response"])["data"]["attributes"] + assert opted_out_attributes["evaluation_options"] == {"experimentation_opt_out": True} + assert opted_out_attributes["evaluation_options"]["experimentation_opt_out"] is True + assert opted_out_attributes["flags"]["checkout"]["variationValue"] is False + assert opted_out_attributes["flags"]["checkout"]["allocationKey"] == "fallback" + assert opted_out_attributes["flags"]["checkout"]["reason"] == "DEFAULT" + assert opted_out_attributes["flags"]["checkout"]["doLog"] is False + assert opted_out_result["errors"] == [{"flagKey": "unsupported", "errorCode": "PARSE_ERROR"}] + + def test_fetch_once_precompute_multiple_contexts( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + contexts = [{"targetingKey": "subject", "country": country} for country in ("US", "CA")] + with test_library: + result = test_library.ffe_precompute_configuration({"fetchOptions": CLIENT_OPTIONS, "contexts": contexts}) + + assert "error" not in result, result + assert result["httpRequests"] == 1, result + assert result["exposureEvents"] == 0, result + requests = mocked_backend.ffe_get_requests() + assert len(requests) == 1, requests + assert urlsplit(requests[0]["path"]).path == f"{RULES_CONFIG_PATH}/client" + assert len(result["results"]) == 2, result + for context, output in zip(contexts, result["results"], strict=True): + wire = json.loads(output["wire"]) + assert set(wire) == {"version", "precomputed"}, wire + snapshot = wire["precomputed"] + assert snapshot["context"] == context + assert "etag" not in snapshot + flag = json.loads(snapshot["response"])["data"]["attributes"]["flags"]["test-flag"] + is_us = context["country"] == "US" + assert flag["variationValue"] is True + assert flag["variationKey"] == "on" + assert flag["reason"] == ("TARGETING_MATCH" if is_us else "SPLIT") + assert flag["allocationKey"] == ("allocation" if is_us else "fallback") + assert flag["doLog"] is is_us + assert flag["serialId"] == 7 + assert output["errors"] == [] + assert CLIENT_TOKEN not in output["wire"] + assert WIRE_FIXTURE["rules"]["etag"] not in output["wire"] + + def test_fetch_failure_before_precompute( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + mocked_backend.client.ffe_set_response("forbidden", response_format="protobuf") + with test_library: + result = test_library.ffe_precompute_configuration( + {"fetchOptions": CLIENT_OPTIONS, "contexts": [{"targetingKey": "subject", "country": "US"}]} + ) + + assert "results" not in result, result + assert result["error"]["name"] == "ConfigurationFetchError", result + assert result["error"]["code"] == "http", result + assert result["error"]["status"] == 403, result + assert result["httpRequests"] == 1, result + assert result["exposureEvents"] == 0, result + assert CLIENT_TOKEN not in json.dumps(result) + assert RESPONSE_SECRET not in json.dumps(result) + requests = mocked_backend.ffe_get_requests() + assert len(requests) == 1, requests + assert urlsplit(requests[0]["path"]).path == f"{RULES_CONFIG_PATH}/client" + + def test_invalid_precompute_inputs(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + cases: list[tuple[str, dict[str, Any], str]] = [ + ("malformed-wire", {"wire": "private-invalid-wire"}, "invalid_configuration"), + ("empty-configuration", {"wire": json.dumps({"version": 1})}, "invalid_configuration"), + ("null-context", {"contexts": [None]}, "invalid_context"), + ( + "invalid-targeting-key", + {"contexts": [{"targetingKey": 42, "private": "private-context"}]}, + "invalid_context", + ), + ("invalid-policy", {"options": {"experimentationOptOutMode": "private-policy"}}, "invalid_options"), + ( + "invalid-opt-out-timestamp", + { + "contexts": [ + {"targetingKey": "subject", "dd_experimentation_opt_out_at": "private-not-a-timestamp"} + ], + "options": {"experimentationOptOutMode": "immediate"}, + }, + "invalid_context", + ), + ] + with test_library: + for case, overrides, code in cases: + result = test_library.ffe_precompute_configuration( + {"wire": PRECOMPUTE_WIRE, "contexts": [{"targetingKey": "subject"}], **overrides} + ) + assert "results" not in result, (case, result) + assert result["error"]["name"] == "ConfigurationPrecomputeError", (case, result) + assert result["error"]["code"] == code, (case, result) + assert "private-" not in json.dumps(result), (case, result) + assert result["httpRequests"] == 0, (case, result) + assert result["exposureEvents"] == 0, (case, result) + assert mocked_backend.ffe_get_requests() == [], case diff --git a/utils/build/docker/nodejs/parametric/ffe-precompute-configuration.js b/utils/build/docker/nodejs/parametric/ffe-precompute-configuration.js new file mode 100644 index 00000000000..9f51dbe10d7 --- /dev/null +++ b/utils/build/docker/nodejs/parametric/ffe-precompute-configuration.js @@ -0,0 +1,66 @@ +'use strict' + +const { channel } = require('node:diagnostics_channel') +const { writeFileSync } = require('node:fs') + +async function main () { + const { wire, fetchOptions, contexts, options } = JSON.parse(process.argv[2]) + let httpRequests = 0 + let exposureEvents = 0 + let outcome + const observeHttp = () => { httpRequests++ } + const observeExposure = () => { exposureEvents++ } + const subscriptions = [ + ['undici:request:create', observeHttp], + ['http.client.request.start', observeHttp], + ['ffe:exposure:submit', observeExposure] + ] + for (const [name, listener] of subscriptions) channel(name).subscribe(listener) + + try { + const { + ConfigurationFetchError, + ConfigurationPrecomputeError, + configurationFromString, + configurationToString, + fetchRulesConfiguration, + precomputeConfiguration + } = require('dd-trace/openfeature/rules-based') + try { + const configuration = fetchOptions + ? await fetchRulesConfiguration({ + ...fetchOptions, + fetch: (url, init) => { + const { pathname, search } = new URL(url) + return fetch(`${process.env.SYSTEM_TESTS_FFE_RULES_BASE_URL}${pathname}${search}`, init) + } + }) + : configurationFromString(wire) + const results = contexts.map(context => { + const errors = [] + const precomputed = precomputeConfiguration(configuration, context, { + ...options, + onEvaluationError: error => errors.push(error) + }) + return { wire: configurationToString(precomputed), errors } + }) + outcome = { results } + } catch (error) { + const expected = [ConfigurationPrecomputeError, ConfigurationFetchError] + .some(type => typeof type === 'function' && error instanceof type) + if (!expected) throw error + outcome = { error: { name: error.name, code: error.code, message: error.message, status: error.status } } + } + } finally { + // Include deferred activity until the child exits; persistent work hits the parent timeout. + process.once('exit', () => { + if (outcome !== undefined) writeFileSync(1, JSON.stringify({ ...outcome, httpRequests, exposureEvents })) + for (const [name, listener] of subscriptions) channel(name).unsubscribe(listener) + }) + } +} + +main().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/utils/build/docker/nodejs/parametric/server.js b/utils/build/docker/nodejs/parametric/server.js index 0653a08d5b6..f7f68c28e44 100644 --- a/utils/build/docker/nodejs/parametric/server.js +++ b/utils/build/docker/nodejs/parametric/server.js @@ -611,27 +611,32 @@ app.post("/trace/otel/otel_set_baggage", (req, res) => { }); // Feature Flag & Experimentation endpoints -app.post('/ffe/fetch-rules-configuration', (req, res) => { - const { execFile } = require('node:child_process') - const path = require('node:path') - const env = { ...process.env } - // The helper must work without the parent server's tracer or preload hooks. - delete env.NODE_OPTIONS - execFile(process.execPath, [path.join(__dirname, 'ffe-rules-configuration.js'), JSON.stringify(req.body)], { - env, - timeout: 10000 - }, (error, stdout, stderr) => { - if (error) { - console.error('Standalone FFE helper failed:', stderr || error) - return res.status(500).json({ error: 'Standalone FFE helper failed' }) - } - try { - res.json(JSON.parse(stdout)) - } catch (error) { - res.status(500).json({ error: 'Invalid standalone FFE helper output' }) - } - }) -}) +function standaloneFfeHandler (script) { + return (req, res) => { + const { execFile } = require('node:child_process') + const path = require('node:path') + const env = { ...process.env } + // The helper must work without the parent server's tracer or preload hooks. + delete env.NODE_OPTIONS + execFile(process.execPath, [path.join(__dirname, script), JSON.stringify(req.body)], { + env, + timeout: 10000 + }, (error, stdout, stderr) => { + if (error) { + console.error('Standalone FFE helper failed:', stderr || error) + return res.status(500).json({ error: 'Standalone FFE helper failed' }) + } + try { + res.json(JSON.parse(stdout)) + } catch (error) { + res.status(500).json({ error: 'Invalid standalone FFE helper output' }) + } + }) + } +} + +app.post('/ffe/fetch-rules-configuration', standaloneFfeHandler('ffe-rules-configuration.js')) +app.post('/ffe/precompute-configuration', standaloneFfeHandler('ffe-precompute-configuration.js')) app.post('/ffe/start', async (req, res) => { const hasFeatureFlaggingConfiguration = [ diff --git a/utils/docker_fixtures/_test_clients/_test_client_parametric.py b/utils/docker_fixtures/_test_clients/_test_client_parametric.py index 36c1bec76e9..0eee4eaca2f 100644 --- a/utils/docker_fixtures/_test_clients/_test_client_parametric.py +++ b/utils/docker_fixtures/_test_clients/_test_client_parametric.py @@ -822,6 +822,12 @@ def ffe_fetch_rules_configuration(self, options: dict[str, Any]) -> dict[str, An response.raise_for_status() return cast("dict[str, Any]", response.json()) + def ffe_precompute_configuration(self, payload: dict[str, Any]) -> dict[str, Any]: + """Resolve portable rules for contexts in a process without tracer/provider initialization.""" + response = self._session.post(self._url("/ffe/precompute-configuration"), json=payload, timeout=15) + response.raise_for_status() + return cast("dict[str, Any]", response.json()) + def ffe_start( self, configuration: dict | None = None, *, flag_selection: dict[str, list[str]] | None = None ) -> bool: @@ -1319,6 +1325,10 @@ def ffe_fetch_rules_configuration(self, options: dict[str, Any]) -> dict[str, An """Fetch and serialize portable rules without initializing a tracer or provider.""" return self._client.ffe_fetch_rules_configuration(options) + def ffe_precompute_configuration(self, payload: dict[str, Any]) -> dict[str, Any]: + """Resolve portable rules without initializing a tracer or provider.""" + return self._client.ffe_precompute_configuration(payload) + def ffe_start( self, configuration: dict | None = None, *, flag_selection: dict[str, list[str]] | None = None ) -> bool: