diff --git a/example-new-architecture/App.tsx b/example-new-architecture/App.tsx index f753110f7..9f2a7bb6a 100644 --- a/example-new-architecture/App.tsx +++ b/example-new-architecture/App.tsx @@ -95,10 +95,9 @@ import {APPLICATION_ID, CLIENT_TOKEN, ENVIRONMENT} from './ddCredentials'; })(); function AppWithProviders() { - // No OpenFeature.setContext here on purpose: the offline precomputed configuration is a - // single-subject snapshot served against the context it was computed for (see the wire's - // embedded context in flags/). Setting a different runtime context would put the provider into - // the OpenFeature ERROR state and fall back to coded defaults. + // setFlagsProvider gets a supported copy of the precomputed context and sets it on OpenFeature + // before provider registration. A later different context puts the offline provider into ERROR + // and evaluations use their coded defaults. return ( => { if (source === 'offline') { + const configuration = configurationFromString(buildSampleWire()); + const context = getPrecomputedContext(configuration); + + if (context !== undefined) { + await OpenFeature.setContext(context); + } + const provider = new DatadogOfflineOpenFeatureProvider({ clientName: 'offline', }); - provider.setConfiguration( - configurationFromString(buildSampleWire()), - ); + provider.setConfiguration(configuration); await OpenFeature.setProviderAndWait(provider); return; } diff --git a/example/src/flags/flagsProvider.ts b/example/src/flags/flagsProvider.ts index 70be0801d..7228345b4 100644 --- a/example/src/flags/flagsProvider.ts +++ b/example/src/flags/flagsProvider.ts @@ -1,7 +1,8 @@ import { DatadogOpenFeatureProvider, DatadogOfflineOpenFeatureProvider, - configurationFromString + configurationFromString, + getPrecomputedContext } from '@datadog/mobile-react-native-openfeature'; import { OpenFeature } from '@openfeature/react-sdk'; @@ -28,12 +29,19 @@ export const setFlagsProvider = async ( offlineContext?: OfflineWireContext ): Promise => { if (source === 'offline') { + const configuration = configurationFromString( + buildSampleWire(offlineContext) + ); + const context = getPrecomputedContext(configuration); + + if (context !== undefined) { + await OpenFeature.setContext(context); + } + const provider = new DatadogOfflineOpenFeatureProvider({ clientName: 'offline' }); - provider.setConfiguration( - configurationFromString(buildSampleWire(offlineContext)) - ); + provider.setConfiguration(configuration); await OpenFeature.setProviderAndWait(provider); return; } diff --git a/packages/core/src/flags/FlagsClient.ts b/packages/core/src/flags/FlagsClient.ts index 059493dde..869806ebf 100644 --- a/packages/core/src/flags/FlagsClient.ts +++ b/packages/core/src/flags/FlagsClient.ts @@ -205,11 +205,10 @@ export class FlagsClient { /** * Clear any externally-set evaluation context and reconcile. * - * This is the offline counterpart to clearing/omitting an OpenFeature context: it drops the - * external override so a loaded precomputed configuration is served against **its embedded - * context** again. Clearing the override (rather than skipping) matters so that a - * configuration loaded *after* a clear is not judged against a stale override. With no - * configuration loaded the result is `PROVIDER_NOT_READY`. + * This is an explicit low-level Datadog reset operation. It drops the external override so a + * loaded precomputed configuration is served against **its embedded context** again. It does + * not represent OpenFeature `clearContext()`, which supplies the resulting effective context + * to a provider. With no configuration loaded the result is `PROVIDER_NOT_READY`. */ resetEvaluationContextWithoutFetching = (): ConfigurationResult => { this.externalContext = undefined; diff --git a/packages/core/src/flags/__tests__/FlagsClient.test.ts b/packages/core/src/flags/__tests__/FlagsClient.test.ts index 7df650bf9..bfd5a224f 100644 --- a/packages/core/src/flags/__tests__/FlagsClient.test.ts +++ b/packages/core/src/flags/__tests__/FlagsClient.test.ts @@ -774,6 +774,33 @@ describe('FlagsClient', () => { ).not.toHaveBeenCalled(); }); + it('stores an empty context as an explicit override', () => { + const flagsClient = DdFlags.getClient(); + flagsClient.setConfiguration( + buildConfig(offlineFlags, { targetingKey: 'user-1' }) + ); + + const result = flagsClient.setEvaluationContextWithoutFetching({ + attributes: {} + } as never); + + expect(result).toEqual({ + status: 'error', + errorCode: 'INVALID_CONTEXT' + }); + + // Reloading the snapshot reconciles against the stored empty override. It does not + // silently restore the snapshot's embedded user-1 context. + expect( + flagsClient.setConfiguration( + buildConfig(offlineFlags, { targetingKey: 'user-1' }) + ) + ).toEqual({ + status: 'error', + errorCode: 'INVALID_CONTEXT' + }); + }); + it('recovers to ready when a matching context is set after a mismatch', () => { const flagsClient = DdFlags.getClient(); flagsClient.setConfiguration( diff --git a/packages/core/src/flags/configuration/__tests__/__utils__/rulesTestUtils.ts b/packages/core/src/flags/configuration/__tests__/__utils__/rulesTestUtils.ts new file mode 100644 index 000000000..81190c964 --- /dev/null +++ b/packages/core/src/flags/configuration/__tests__/__utils__/rulesTestUtils.ts @@ -0,0 +1,81 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://github.com/DataDog). + * Copyright 2016-Present Datadog, Inc. + */ + +import { OperatorType } from '@datadog/flagging-core'; +import type { UniversalFlagConfigurationV1 } from '@datadog/flagging-core'; + +import type { + RulesEngine, + RulesEvaluationDetails, + RulesEvaluationRequest, + RulesValueType +} from '../../rules'; + +export const buildRulesConfiguration = (): UniversalFlagConfigurationV1 => ({ + createdAt: '2026-07-23T12:00:00.000Z', + format: 'SERVER', + environment: { name: 'test' }, + flags: { + 'dynamic-flag': { + key: 'dynamic-flag', + enabled: true, + variationType: 'BOOLEAN', + variations: { + enabled: { key: 'enabled', value: true }, + disabled: { key: 'disabled', value: false } + }, + allocations: [ + { + key: 'allocation-1', + rules: [ + { + conditions: [ + { + operator: OperatorType.ONE_OF, + attribute: 'country', + value: ['US'] + } + ] + } + ], + splits: [ + { + variationKey: 'enabled', + serialId: 7, + shards: [ + { + salt: 'test-salt', + ranges: [{ start: 0, end: 100 }], + totalShards: 100 + } + ] + } + ], + doLog: false + } + ] + } + } +}); + +type FakeRulesEvaluation = RulesEvaluationDetails; + +export interface FakeRulesEngine extends RulesEngine { + evaluate: jest.Mock< + FakeRulesEvaluation, + [RulesEvaluationRequest] + >; +} + +// Client tests use this fake to control evaluation independently of the +// flagging-core implementation and its canonical integration vectors. +export const createFakeRulesEngine = ( + result: FakeRulesEvaluation +): FakeRulesEngine => { + return { + evaluate: jest.fn(() => result) + } as FakeRulesEngine; +}; diff --git a/packages/core/src/flags/configuration/__tests__/context.test.ts b/packages/core/src/flags/configuration/__tests__/context.test.ts index ec0155bad..e9654c4a4 100644 --- a/packages/core/src/flags/configuration/__tests__/context.test.ts +++ b/packages/core/src/flags/configuration/__tests__/context.test.ts @@ -28,9 +28,9 @@ describe('normalizeWireContext', () => { }); }); - it('defaults a missing targeting key to an empty string', () => { + it('preserves a missing targeting key', () => { expect(normalizeWireContext({ country: 'US' })).toEqual({ - targetingKey: '', + targetingKey: undefined, attributes: { country: 'US' } }); }); @@ -80,6 +80,14 @@ describe('contextMatchesConfiguration', () => { ).toBe(true); }); + it('matches empty contexts without inventing a targeting key', () => { + expect( + contextMatchesConfiguration({}, { + attributes: {} + } as EvaluationContext) + ).toBe(true); + }); + it('does not match a different targeting key', () => { expect( contextMatchesConfiguration( diff --git a/packages/core/src/flags/configuration/__tests__/rules.test.ts b/packages/core/src/flags/configuration/__tests__/rules.test.ts new file mode 100644 index 000000000..5bbf51a67 --- /dev/null +++ b/packages/core/src/flags/configuration/__tests__/rules.test.ts @@ -0,0 +1,487 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://github.com/DataDog). + * Copyright 2016-Present Datadog, Inc. + */ + +import { + flaggingCoreRulesEngine, + getNoopRulesLogger, + prepareRulesConfiguration, + toRulesEvaluationContext +} from '../rules'; + +import { + buildRulesConfiguration, + createFakeRulesEngine +} from './__utils__/rulesTestUtils'; + +describe('rules configuration', () => { + it('converts an SDK context to a flat rules context and reserves identifiers', () => { + expect( + toRulesEvaluationContext({ + targetingKey: 'user-1', + attributes: { + country: 'US', + id: 'customer-id', + targetingKey: 'attribute-key', + enabled: true + } + }) + ).toMatchObject({ + targetingKey: 'user-1', + country: 'US', + enabled: true + }); + }); + + it('preserves the difference between a missing and empty targeting key', () => { + expect(toRulesEvaluationContext({})).toHaveProperty( + 'targetingKey', + undefined + ); + expect(toRulesEvaluationContext({ targetingKey: '' })).toHaveProperty( + 'targetingKey', + '' + ); + }); + + it.each(['constructor', 'toString'])( + 'shadows an absent inherited %s context attribute', + attribute => { + const rulesContext = toRulesEvaluationContext({ + targetingKey: 'user-1' + }); + + expect(Object.getPrototypeOf(rulesContext)).toBeNull(); + expect( + Object.prototype.hasOwnProperty.call(rulesContext, attribute) + ).toBe(true); + expect(rulesContext[attribute]).toBeUndefined(); + + const configuration = buildRulesConfiguration(); + const condition = + configuration.flags['dynamic-flag'].allocations[0].rules?.[0] + .conditions[0]; + if (!condition) { + throw new Error('The fixture has no condition.'); + } + condition.attribute = attribute; + condition.value = [ + String(({} as Record)[attribute]) + ]; + + expect( + flaggingCoreRulesEngine.evaluate({ + configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: rulesContext, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ value: false, reason: 'DEFAULT' }); + } + ); + + it.each(['constructor', 'toString'])( + 'preserves an explicit own %s context attribute', + attribute => { + const attributes = Object.create(null) as Record; + attributes[attribute] = 'customer-value'; + + const rulesContext = toRulesEvaluationContext({ + targetingKey: 'user-1', + attributes + }); + expect( + Object.prototype.hasOwnProperty.call(rulesContext, attribute) + ).toBe(true); + expect(rulesContext[attribute]).toBe('customer-value'); + const configuration = buildRulesConfiguration(); + const condition = + configuration.flags['dynamic-flag'].allocations[0].rules?.[0] + .conditions[0]; + if (!condition) { + throw new Error('The fixture has no condition.'); + } + condition.attribute = attribute; + condition.value = ['customer-value']; + + expect( + flaggingCoreRulesEngine.evaluate({ + configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: rulesContext, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ value: true, reason: 'TARGETING_MATCH' }); + } + ); + + it('clones and freezes a valid rules configuration', () => { + const source = buildRulesConfiguration(); + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + + source.flags['dynamic-flag'].enabled = false; + + expect(prepared.configuration.flags['dynamic-flag'].enabled).toBe(true); + expect(Object.isFrozen(prepared.configuration)).toBe(true); + expect( + Object.isFrozen( + prepared.configuration.flags['dynamic-flag'].allocations[0] + ) + ).toBe(true); + }); + + it('preserves a flag with an unsupported operator and reports PARSE_ERROR', () => { + const source = buildRulesConfiguration(); + const condition = + source.flags['dynamic-flag'].allocations[0].rules?.[0] + .conditions[0]; + + if (!condition) { + throw new Error('The fixture has no condition.'); + } + (condition as { operator: string }).operator = 'FUTURE_OPERATOR'; + + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + expect(prepared.configuration.flags).toHaveProperty('dynamic-flag'); + expect( + flaggingCoreRulesEngine.evaluate({ + configuration: prepared.configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: { targetingKey: 'user-1' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ + value: false, + reason: 'ERROR', + errorCode: 'PARSE_ERROR', + errorMessage: + 'The rules configuration uses an unsupported operator.' + }); + }); + + it('reports PARSE_ERROR for a flag with an invalid regular expression', () => { + const source = buildRulesConfiguration(); + const conditions = + source.flags['dynamic-flag'].allocations[0].rules?.[0].conditions; + if (!conditions) { + throw new Error('The fixture has no conditions.'); + } + conditions[0] = { + operator: 'MATCHES', + attribute: 'country', + value: '[' + } as typeof conditions[number]; + + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + expect( + flaggingCoreRulesEngine.evaluate({ + configuration: prepared.configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: { targetingKey: 'user-1' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ + errorCode: 'PARSE_ERROR', + errorMessage: 'A regular expression condition is not valid.' + }); + }); + + it('reports PARSE_ERROR when a split points to an absent variation', () => { + const source = buildRulesConfiguration(); + source.flags['dynamic-flag'].allocations[0].splits[0].variationKey = + 'absent'; + + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + expect( + flaggingCoreRulesEngine.evaluate({ + configuration: prepared.configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: { targetingKey: 'user-1' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ + errorCode: 'PARSE_ERROR', + errorMessage: 'A split has an invalid variation key.' + }); + }); + + it('keeps valid flags usable when another flag has a parse error', () => { + const source = buildRulesConfiguration(); + const validFlag = buildRulesConfiguration().flags['dynamic-flag']; + validFlag.key = 'valid-flag'; + source.flags['valid-flag'] = validFlag; + + const condition = + source.flags['dynamic-flag'].allocations[0].rules?.[0] + .conditions[0]; + if (!condition) { + throw new Error('The fixture has no condition.'); + } + (condition as { operator: string }).operator = 'FUTURE_OPERATOR'; + + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + expect(Object.keys(prepared.configuration.flags)).toEqual([ + 'dynamic-flag', + 'valid-flag' + ]); + expect( + flaggingCoreRulesEngine.evaluate({ + configuration: prepared.configuration, + type: 'boolean', + flagKey: 'valid-flag', + defaultValue: false, + context: { targetingKey: 'user-1', country: 'US' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ value: true, errorCode: undefined }); + }); + + // TODO(FFL-2837): Replace this legacy JSON compatibility test with a + // generated protobuf fixture after a flagging-core release contains + // DataDog/openfeature-js-client#344 through `78a0c14`. Round-trip the + // generated fixture and confirm that serialization preserves the unknown field. + // Add a fixture with an unsupported minimum feature level and require a + // flag-scoped `PARSE_ERROR`, not `FLAG_NOT_FOUND`. Also cover unsorted + // string and SHA-256 membership indexes, invalid SHA digest lengths, and + // semantic-version components at and above the unsigned 64-bit limit. + // Cover supported primitive coercion, strict finite numeric strings, + // rejected arrays, objects, empty strings, hexadecimal strings and infinity, + // and string-only semantic-version operands. Add non-ASCII membership cases + // that distinguish UTF-8 code-point order from JavaScript UTF-16 order, and + // prove that one shared condition is evaluated once per flag resolution. + // Confirm that an absent inherited `__proto__` attribute does not match and + // that an explicit own `__proto__` context attribute remains usable. The + // legacy evaluator's compiled object spread cannot preserve that key. + it('keeps supported known data when an unknown field is present', () => { + const source = buildRulesConfiguration(); + (source.flags['dynamic-flag'] as typeof source.flags['dynamic-flag'] & { + futureField: string; + }).futureField = 'ignored'; + + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + expect( + flaggingCoreRulesEngine.evaluate({ + configuration: prepared.configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: { targetingKey: 'user-1', country: 'US' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ value: true, errorCode: undefined }); + }); + + // TODO(FFL-2837): Replace this unsafe JSON number with an out-of-range + // protobuf `int64` fixture after flagging-core contains PR #344 at or after + // `78a0c14`. The generated parser must preserve the source value as `bigint` + // where supported. Run the same evaluation with + // global `BigInt` unavailable and require `PARSE_ERROR`, not `GENERAL`. + it('returns PARSE_ERROR instead of serving an unsafe integer', () => { + const source = buildRulesConfiguration(); + const flag = source.flags['dynamic-flag']; + flag.variationType = 'INTEGER'; + flag.variations.enabled.value = Number.MAX_SAFE_INTEGER + 1; + flag.variations.disabled.value = 0; + + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + expect( + prepared.configuration.flags['dynamic-flag'].variations.enabled + .value + ).toBe(Number.MAX_SAFE_INTEGER + 1); + expect( + flaggingCoreRulesEngine.evaluate({ + configuration: prepared.configuration, + type: 'number', + flagKey: 'dynamic-flag', + defaultValue: 0, + context: { targetingKey: 'user-1', country: 'US' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ + value: 0, + reason: 'ERROR', + errorCode: 'PARSE_ERROR', + errorMessage: + 'Integer variation value cannot be represented safely as a JavaScript number' + }); + }); + + it('returns PARSE_ERROR for an unsafe shard integer', () => { + const source = buildRulesConfiguration(); + source.flags[ + 'dynamic-flag' + ].allocations[0].splits[0].shards[0].totalShards = + Number.MAX_SAFE_INTEGER + 1; + + const prepared = prepareRulesConfiguration(source); + + expect(prepared.status).toBe('ready'); + if (prepared.status !== 'ready') { + throw new Error(prepared.errorMessage); + } + expect( + flaggingCoreRulesEngine.evaluate({ + configuration: prepared.configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: { targetingKey: 'user-1', country: 'US' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ + value: false, + reason: 'ERROR', + errorCode: 'PARSE_ERROR', + errorMessage: + 'Protobuf uint64 cannot be represented safely as a JavaScript number' + }); + }); + + it('normalizes a real flagging-core evaluation', () => { + const configuration = buildRulesConfiguration(); + + const result = flaggingCoreRulesEngine.evaluate({ + configuration, + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: { + targetingKey: 'user-1', + country: 'US' + }, + logger: getNoopRulesLogger() + }); + + expect(result).toMatchObject({ + value: true, + variant: 'enabled', + reason: 'TARGETING_MATCH', + metadata: { + allocationKey: 'allocation-1', + variationType: 'boolean', + doLog: false + } + }); + }); + + it.each([ + ['INTEGER', 42], + ['NUMERIC', 1.5] + ] as const)( + 'normalizes %s variation metadata to number', + (variationType, variationValue) => { + const configuration = buildRulesConfiguration(); + const flag = configuration.flags['dynamic-flag']; + flag.variationType = variationType; + flag.variations.enabled.value = variationValue; + flag.variations.disabled.value = 0; + + const result = flaggingCoreRulesEngine.evaluate({ + configuration, + type: 'number', + flagKey: 'dynamic-flag', + defaultValue: 0, + context: { + targetingKey: 'user-1', + country: 'US' + }, + logger: getNoopRulesLogger() + }); + + expect(result).toMatchObject({ + value: variationValue, + metadata: { + variationType: 'number' + } + }); + } + ); + + it.each(['toString', 'constructor', '__proto__'])( + 'checks own properties before it evaluates %s', + flagKey => { + const result = flaggingCoreRulesEngine.evaluate({ + configuration: buildRulesConfiguration(), + type: 'boolean', + flagKey, + defaultValue: false, + context: { targetingKey: 'user-1' }, + logger: getNoopRulesLogger() + }); + + expect(result).toEqual({ + value: false, + reason: 'ERROR', + errorCode: 'FLAG_NOT_FOUND', + metadata: {} + }); + } + ); + + it('provides a deterministic fake engine for client tests', () => { + const fake = createFakeRulesEngine({ + value: true, + variant: 'fake', + reason: 'TARGETING_MATCH', + metadata: {} + }); + + expect( + fake.evaluate({ + configuration: buildRulesConfiguration(), + type: 'boolean', + flagKey: 'dynamic-flag', + defaultValue: false, + context: { targetingKey: 'user-1' }, + logger: getNoopRulesLogger() + }) + ).toMatchObject({ value: true, variant: 'fake' }); + }); +}); diff --git a/packages/core/src/flags/configuration/__tests__/wire.test.ts b/packages/core/src/flags/configuration/__tests__/wire.test.ts index 23f1d359b..d2e8b3dbb 100644 --- a/packages/core/src/flags/configuration/__tests__/wire.test.ts +++ b/packages/core/src/flags/configuration/__tests__/wire.test.ts @@ -7,6 +7,8 @@ import type { ParsedFlagsConfiguration } from '../types'; import { configurationFromString, configurationToString } from '../wire'; +import { buildRulesConfiguration } from './__utils__/rulesTestUtils'; + const buildResponse = () => ({ data: { id: '2', @@ -77,17 +79,39 @@ describe('configurationFromString', () => { ).toBe(true); }); - it('returns an empty config for an unsupported version', () => { + it('preserves a configuration error for an unsupported version', () => { const wire = JSON.stringify({ version: 2, precomputed: { response: JSON.stringify(buildResponse()) } }); - expect(configurationFromString(wire)).toEqual({}); + expect(configurationFromString(wire)).toEqual({ + configurationError: 'Invalid flags configuration wire format' + }); + }); + + it('preserves a configuration error for invalid JSON', () => { + expect(configurationFromString('not json')).toEqual({ + configurationError: 'Invalid flags configuration wire format' + }); }); - it('returns an empty config for invalid JSON', () => { - expect(configurationFromString('not json')).toEqual({}); + it('does not treat a raw protobuf response as a portable wire', () => { + // A service or distribution layer must put one base64 encoding of + // these bytes in a version 1 `rules.response` JSON envelope. + const rawProtobufAsBase64 = 'CgR0ZXN0'; + + expect(configurationFromString(rawProtobufAsBase64)).toEqual({ + configurationError: 'Invalid flags configuration wire format' + }); + }); + + it('does not treat the legacy UFC JSON response as a portable wire', () => { + const legacyServiceResponse = JSON.stringify(buildRulesConfiguration()); + + expect(configurationFromString(legacyServiceResponse)).toEqual({ + configurationError: 'Invalid flags configuration wire format' + }); }); it('returns an empty config when the inner response is invalid JSON', () => { @@ -125,3 +149,100 @@ describe('configurationToString round-trip', () => { ); }); }); + +describe('temporary rules configuration wire compatibility', () => { + it('parses a legacy rules configuration', () => { + const rulesBased = { + response: buildRulesConfiguration(), + fetchedAt: 123, + etag: 'rules-etag' + }; + const wire = JSON.stringify({ + version: 1, + rulesBased: { + ...rulesBased, + response: JSON.stringify(rulesBased.response) + } + }); + + const parsed = configurationFromString(wire) as { + rulesBased?: typeof rulesBased; + }; + + expect(parsed.rulesBased).toEqual(rulesBased); + }); + + it('round-trips a legacy rules configuration', () => { + const response = buildRulesConfiguration() as ReturnType< + typeof buildRulesConfiguration + > & { + futureField?: { value: number }; + }; + response.futureField = { value: 7 }; + const original = { + rulesBased: { + response, + fetchedAt: 123, + etag: 'rules-etag' + } + }; + + const restored = configurationFromString( + configurationToString( + (original as unknown) as ParsedFlagsConfiguration + ) + ) as { + rulesBased?: typeof original.rulesBased; + }; + + expect(restored.rulesBased).toEqual(original.rulesBased); + }); + + it('keeps both branches in a mixed configuration', () => { + const mixedWire = buildWire({ + rulesBased: { + response: JSON.stringify(buildRulesConfiguration()) + } + }); + + const parsed = configurationFromString(mixedWire) as { + precomputed?: unknown; + rulesBased?: unknown; + }; + + expect(parsed.precomputed).toBeDefined(); + expect(parsed.rulesBased).toBeDefined(); + }); + + it('keeps a valid precomputed branch when rules JSON is malformed', () => { + const parsed = configurationFromString( + buildWire({ + rulesBased: { response: '{' } + }) + ) as { + precomputed?: unknown; + rulesBased?: unknown; + rulesError?: string; + }; + + expect(parsed.precomputed).toBeDefined(); + expect(parsed.rulesBased).toBeUndefined(); + expect(parsed.rulesError).toBe( + 'Rules configuration response could not be decoded' + ); + }); + + it('preserves an invalid rules entry error', () => { + const parsed = configurationFromString( + buildWire({ rulesBased: { response: 42 } }) + ) as { + precomputed?: unknown; + rulesError?: string; + }; + + expect(parsed.precomputed).toBeDefined(); + expect(parsed.rulesError).toBe( + 'Invalid rules configuration wire entry' + ); + }); +}); diff --git a/packages/core/src/flags/configuration/context.ts b/packages/core/src/flags/configuration/context.ts index 436ad96b5..1810d937c 100644 --- a/packages/core/src/flags/configuration/context.ts +++ b/packages/core/src/flags/configuration/context.ts @@ -19,14 +19,18 @@ export const normalizeWireContext = ( wireContext: WireEvaluationContext ): EvaluationContext => { const { targetingKey, ...attributes } = wireContext; - - return processEvaluationContext({ - // The wire is untrusted, so a non-string targetingKey is treated as absent. - targetingKey: typeof targetingKey === 'string' ? targetingKey : '', - // `processEvaluationContext` drops non-primitive attributes; casting here mirrors - // how the active context's attributes are typed before that same processing. + const context = { + // `processEvaluationContext` removes unsupported nested values from the attributes. attributes: attributes as Record - }); + } as EvaluationContext; + + // The wire is untrusted. Preserve a string (including an empty string), but do not invent a + // targeting key when it is absent or invalid. + if (typeof targetingKey === 'string') { + context.targetingKey = targetingKey; + } + + return processEvaluationContext(context); }; /** diff --git a/packages/core/src/flags/configuration/index.ts b/packages/core/src/flags/configuration/index.ts index 8078428e2..0cadf111d 100644 --- a/packages/core/src/flags/configuration/index.ts +++ b/packages/core/src/flags/configuration/index.ts @@ -10,6 +10,12 @@ // the decoder and other helpers stay internal to this boundary. Keeping the surface contained // here makes a future "port -> depend on a shared core" swap easier. +// TODO(FFL-2837): Re-export `getPrecomputedContext` from +// `@datadog/flagging-core` here after a flagging-core release contains +// DataDog/openfeature-js-client#344 through `78a0c14`, including merged PR #353. +// Also expose it from the +// public React Native SDK entry point for the OpenFeature package to consume. + export { configurationFromString, configurationToString } from './wire'; export { decodePrecomputedFlags, diff --git a/packages/core/src/flags/configuration/rules.ts b/packages/core/src/flags/configuration/rules.ts new file mode 100644 index 000000000..279e0cbcb --- /dev/null +++ b/packages/core/src/flags/configuration/rules.ts @@ -0,0 +1,628 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import { + evaluateRulesBasedConfiguration, + OperatorType +} from '@datadog/flagging-core'; +import type { UniversalFlagConfigurationV1 } from '@datadog/flagging-core'; + +import type { EvaluationContext, JsonValue, PrimitiveValue } from '../types'; + +// TODO(FFL-2837): Replace this legacy UFC v1 alias with +// `NonNullable['response']` after a flagging-core +// release contains DataDog/openfeature-js-client#344 through `78a0c14`. +// Keep the `FlagsConfiguration` type +// import on the flagging-core package root. PR #344 preserves protobuf integers +// as `bigint`, does not call global `BigInt` during safe conversion, and reports +// unsafe conversions and malformed SHA digests as deterministic per-flag +// `PARSE_ERROR` results. +type RulesConfigurationResponse = UniversalFlagConfigurationV1; + +export type RulesValueType = 'boolean' | 'string' | 'number' | 'object'; + +type RulesValueByType = { + boolean: boolean; + string: string; + number: number; + object: JsonValue; +}; + +export interface RulesLogger { + debug: (message: string, ...args: unknown[]) => void; + info: (message: string, ...args: unknown[]) => void; + warn: (message: string, ...args: unknown[]) => void; + error: (message: string, ...args: unknown[]) => void; +} + +export interface RulesEvaluationContext { + targetingKey?: string; + [key: string]: PrimitiveValue | undefined; +} + +export interface RulesEvaluationMetadata { + allocationKey?: string; + variationType?: RulesValueType; + doLog?: boolean; +} + +export interface RulesEvaluationDetails { + value: T; + reason?: string; + variant?: string; + errorCode?: string; + errorMessage?: string; + metadata: RulesEvaluationMetadata; +} + +export interface RulesEvaluationRequest { + configuration: RulesConfigurationResponse; + type: T; + flagKey: string; + defaultValue: RulesValueByType[T]; + context: RulesEvaluationContext; + logger: RulesLogger; +} + +export interface RulesEngine { + evaluate( + request: RulesEvaluationRequest + ): RulesEvaluationDetails; +} + +type RawEvaluationDetails = { + value: T; + reason?: string; + variant?: string; + errorCode?: string; + errorMessage?: string; + flagMetadata?: Record; +}; + +type EvaluateRules = ( + configuration: RulesConfigurationResponse, + type: T, + flagKey: string, + defaultValue: RulesValueByType[T], + context: RulesEvaluationContext, + logger: RulesLogger +) => RawEvaluationDetails; + +const evaluateRules = evaluateRulesBasedConfiguration as EvaluateRules; + +const NOOP_LOGGER: RulesLogger = { + debug: () => {}, + info: () => {}, + warn: () => {}, + error: () => {} +}; + +export const getNoopRulesLogger = (): RulesLogger => NOOP_LOGGER; + +/** + * Convert the SDK context to the flat context that flagging-core uses. + * + * `id` and `targetingKey` are reserved. The adapter always derives them from + * `EvaluationContext.targetingKey`. + */ +export const toRulesEvaluationContext = ( + context: EvaluationContext +): RulesEvaluationContext => { + const attributes = new Map(); + + for (const [key, value] of Object.entries(context.attributes ?? {})) { + if (key === 'id' || key === 'targetingKey' || value === undefined) { + continue; + } + attributes.set(key, value); + } + + // TODO(FFL-2837): Delete the inherited-name shadows after a flagging-core + // release contains DataDog/openfeature-js-client#344 through `78a0c14` and + // this adapter uses its generated protobuf evaluator. That evaluator uses + // own-property lookup for condition and shard context attributes. + const rulesContext = Object.create(null) as RulesEvaluationContext; + for (const key of Object.getOwnPropertyNames(Object.prototype)) { + rulesContext[key] = undefined; + } + for (const [key, value] of attributes) { + rulesContext[key] = value; + } + rulesContext.targetingKey = context.targetingKey; + + return rulesContext; +}; + +const hasOwn = (value: object, key: PropertyKey): boolean => + Object.prototype.hasOwnProperty.call(value, key); + +// TODO(FFL-2837): Delete this compatibility error store after a flagging-core +// release contains DataDog/openfeature-js-client#344 through `78a0c14`. +// The generated protobuf evaluator validates the requested flag and the data +// that evaluation reaches. It does not build this error map during parsing. +// It returns deterministic `PARSE_ERROR` results, including for an integer that +// is not a safe JavaScript number. Its protobuf conditions also use stricter +// primitive coercion than this temporary legacy JSON evaluator; do not copy that +// operator logic into this compatibility layer. +const errorsByConfiguration = new WeakMap< + RulesConfigurationResponse, + ReadonlyMap +>(); + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +const isJsonValue = (value: unknown): value is JsonValue => { + if ( + value === null || + typeof value === 'string' || + typeof value === 'boolean' + ) { + return true; + } + if (typeof value === 'number') { + return Number.isFinite(value); + } + if (Array.isArray(value)) { + return value.every(isJsonValue); + } + if (isRecord(value)) { + return Object.values(value).every(isJsonValue); + } + return false; +}; + +const variationValueIsValid = ( + variationType: string, + value: unknown +): boolean => { + switch (variationType) { + case 'BOOLEAN': + return typeof value === 'boolean'; + case 'STRING': + return typeof value === 'string'; + case 'INTEGER': + return typeof value === 'number' && Number.isSafeInteger(value); + case 'NUMERIC': + return typeof value === 'number' && Number.isFinite(value); + case 'JSON': + return isJsonValue(value); + default: + return false; + } +}; + +const SUPPORTED_OPERATORS: ReadonlySet = new Set( + Object.values(OperatorType) +); + +const validateCondition = (value: unknown): string | undefined => { + if ( + !isRecord(value) || + typeof value.attribute !== 'string' || + typeof value.operator !== 'string' + ) { + return 'A rule condition has an invalid shape.'; + } + + if (!SUPPORTED_OPERATORS.has(value.operator)) { + return 'The rules configuration uses an unsupported operator.'; + } + + switch (value.operator) { + case OperatorType.MATCHES: + case OperatorType.NOT_MATCHES: + if (typeof value.value !== 'string') { + return 'A regular expression condition must contain a string.'; + } + try { + // TODO(FFL-2837): Define a bounded regular expression policy before + // dynamic offline rules leave draft state. Upstream PR #344 through + // `78a0c14` compiles protobuf regular expressions lazily and caches + // them by configuration and index. It also memoizes a condition result + // during one flag evaluation, but it does not limit patterns. + RegExp(value.value); // dd-iac-scan ignore-line + } catch { + return 'A regular expression condition is not valid.'; + } + return undefined; + case OperatorType.ONE_OF: + case OperatorType.NOT_ONE_OF: + return Array.isArray(value.value) && + value.value.every(item => typeof item === 'string') + ? undefined + : 'A membership condition must contain a string array.'; + case OperatorType.GTE: + case OperatorType.GT: + case OperatorType.LTE: + case OperatorType.LT: + return typeof value.value === 'number' && + Number.isFinite(value.value) + ? undefined + : 'A numeric condition must contain a finite number.'; + case OperatorType.IS_NULL: + return typeof value.value === 'boolean' + ? undefined + : 'A null condition must contain a boolean.'; + default: + return 'The rules configuration uses an unsupported operator.'; + } +}; + +const validateRules = (value: unknown): string | undefined => { + if (value === undefined) { + return undefined; + } + if (!Array.isArray(value)) { + return 'An allocation rules field must be an array.'; + } + + for (const rule of value) { + if (!isRecord(rule) || !Array.isArray(rule.conditions)) { + return 'A rule has an invalid shape.'; + } + for (const condition of rule.conditions) { + const error = validateCondition(condition); + if (error) { + return error; + } + } + } + + return undefined; +}; + +const validateShards = (value: unknown): string | undefined => { + if (!Array.isArray(value)) { + return 'A split shards field must be an array.'; + } + + for (const shard of value) { + if ( + !isRecord(shard) || + typeof shard.salt !== 'string' || + !Number.isInteger(shard.totalShards) || + (shard.totalShards as number) <= 0 || + !Array.isArray(shard.ranges) + ) { + return 'A shard has an invalid shape.'; + } + if (!Number.isSafeInteger(shard.totalShards)) { + return 'Protobuf uint64 cannot be represented safely as a JavaScript number'; + } + + for (const range of shard.ranges) { + if ( + !isRecord(range) || + !Number.isInteger(range.start) || + !Number.isInteger(range.end) || + (range.start as number) < 0 || + (range.end as number) <= (range.start as number) || + (range.end as number) > (shard.totalShards as number) + ) { + return 'A shard range is not valid.'; + } + if ( + !Number.isSafeInteger(range.start) || + !Number.isSafeInteger(range.end) + ) { + return 'Protobuf uint64 cannot be represented safely as a JavaScript number'; + } + } + } + + return undefined; +}; + +const isValidDate = (value: unknown): boolean => + value instanceof Date + ? !Number.isNaN(value.getTime()) + : typeof value === 'string' && !Number.isNaN(Date.parse(value)); + +const validateAllocation = ( + value: unknown, + variations: Record +): string | undefined => { + if ( + !isRecord(value) || + typeof value.key !== 'string' || + !Array.isArray(value.splits) + ) { + return 'An allocation has an invalid shape.'; + } + + if (value.startAt !== undefined && !isValidDate(value.startAt)) { + return 'An allocation start time is not valid.'; + } + if (value.endAt !== undefined && !isValidDate(value.endAt)) { + return 'An allocation end time is not valid.'; + } + + const rulesError = validateRules(value.rules); + if (rulesError) { + return rulesError; + } + + for (const split of value.splits) { + if ( + !isRecord(split) || + typeof split.variationKey !== 'string' || + !hasOwn(variations, split.variationKey) + ) { + return 'A split has an invalid variation key.'; + } + if (split.serialId !== undefined && !Number.isInteger(split.serialId)) { + return 'A split serial ID is not valid.'; + } + + const shardsError = validateShards(split.shards); + if (shardsError) { + return shardsError; + } + } + + return undefined; +}; + +const validateFlag = (value: unknown): string | undefined => { + if ( + !isRecord(value) || + typeof value.key !== 'string' || + typeof value.enabled !== 'boolean' || + typeof value.variationType !== 'string' || + !isRecord(value.variations) || + !Array.isArray(value.allocations) + ) { + return 'A flag has an invalid shape.'; + } + + if ( + !['BOOLEAN', 'INTEGER', 'NUMERIC', 'STRING', 'JSON'].includes( + value.variationType + ) + ) { + return `A flag uses the unsupported variation type "${value.variationType}".`; + } + + for (const variation of Object.values(value.variations)) { + if ( + value.variationType === 'INTEGER' && + isRecord(variation) && + typeof variation.value === 'number' && + !Number.isSafeInteger(variation.value) + ) { + return 'Integer variation value cannot be represented safely as a JavaScript number'; + } + if ( + !isRecord(variation) || + typeof variation.key !== 'string' || + !variationValueIsValid(value.variationType, variation.value) + ) { + return 'A variation has an invalid shape or value.'; + } + } + + for (const allocation of value.allocations) { + const error = validateAllocation(allocation, value.variations); + if (error) { + return error; + } + } + + return undefined; +}; + +const validateRulesConfigurationEnvelope = ( + value: unknown +): string | undefined => { + if ( + !isRecord(value) || + typeof value.createdAt !== 'string' || + typeof value.format !== 'string' || + !isRecord(value.environment) || + typeof value.environment.name !== 'string' || + !isRecord(value.flags) + ) { + return 'The rules configuration has an invalid envelope.'; + } + + return undefined; +}; + +const cloneValue = (value: unknown): unknown => { + if (value instanceof Date) { + return new Date(value.getTime()); + } + if (Array.isArray(value)) { + return value.map(cloneValue); + } + if (isRecord(value)) { + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [key, cloneValue(item)]) + ); + } + return value; +}; + +const freezeValue = (value: unknown): void => { + if (typeof value !== 'object' || value === null || Object.isFrozen(value)) { + return; + } + + Object.freeze(value); + for (const item of Object.values(value)) { + freezeValue(item); + } +}; + +export type PreparedRulesConfiguration = + | { + status: 'ready'; + configuration: RulesConfigurationResponse; + } + | { + status: 'error'; + errorMessage: string; + }; + +/** + * Clone and validate untrusted rules before `FlagsClient` stores them. + */ +export const prepareRulesConfiguration = ( + value: unknown +): PreparedRulesConfiguration => { + const clone = cloneValue(value); + + // TODO(FFL-2837): Delete this legacy JSON clone and validator after a + // flagging-core release contains upstream PR #344 through `78a0c14`. That + // implementation preserves protobuf integers as `bigint` and validates only + // the requested flag data that evaluation reaches. It does not call global + // `BigInt` when it returns a deterministic per-flag error for an unsafe number. + // Do not adapt this validator to the generated response type. + const errorMessage = validateRulesConfigurationEnvelope(clone); + if (errorMessage) { + return { status: 'error', errorMessage }; + } + + const configuration = clone as RulesConfigurationResponse; + const flags = configuration.flags; + const errors = new Map(); + for (const [flagKey, flag] of Object.entries(flags)) { + const flagError = validateFlag(flag); + if (flagError) { + errors.set(flagKey, flagError); + } + } + + freezeValue(clone); + if (errors.size > 0) { + errorsByConfiguration.set(configuration, errors); + } + return { + status: 'ready', + configuration + }; +}; + +const normalizeVariationType = ( + variationType: unknown +): RulesValueType | undefined => { + switch (variationType) { + case 'boolean': + case 'string': + case 'number': + case 'object': + return variationType; + case 'BOOLEAN': + return 'boolean'; + case 'STRING': + return 'string'; + case 'INTEGER': + case 'NUMERIC': + return 'number'; + case 'JSON': + return 'object'; + default: + return undefined; + } +}; + +// TODO(FFL-2837): Delete this legacy UFC v1 metadata fallback after the +// flagging-core dependency contains DataDog/openfeature-js-client#344 through +// `78a0c14`. The protobuf evaluator maps only safely represented integer +// variations, and all numeric variations, to the OpenFeature type `number`. +const recoverVariationType = ( + configuration: RulesConfigurationResponse, + flagKey: string +): RulesValueType | undefined => { + const flags = configuration.flags as Record; + if (!hasOwn(flags, flagKey)) { + return undefined; + } + + const flag = flags[flagKey]; + if (!isRecord(flag)) { + return undefined; + } + + return normalizeVariationType(flag.variationType); +}; + +export const flaggingCoreRulesEngine: RulesEngine = { + evaluate( + request: RulesEvaluationRequest + ): RulesEvaluationDetails { + const flags = request.configuration.flags as Record; + + // TODO(FFL-2837): Delete this local compatibility guard after the + // flagging-core dependency contains DataDog/openfeature-js-client#344 + // through `78a0c14`. Keep the reserved-name contract tests. + if (!hasOwn(flags, request.flagKey)) { + return { + value: request.defaultValue, + reason: 'ERROR', + errorCode: 'FLAG_NOT_FOUND', + metadata: {} + }; + } + + // TODO(FFL-2837): Delete this compatibility check with the local error + // store after the published PR #344 evaluator through `78a0c14` validates + // reached flag data and reports deterministic flag-scoped errors, including + // unsupported feature levels and unsafe integer conversions with and + // without global `BigInt` when supported. + const configurationError = errorsByConfiguration + .get(request.configuration) + ?.get(request.flagKey); + if (configurationError) { + return { + value: request.defaultValue, + reason: 'ERROR', + errorCode: 'PARSE_ERROR', + errorMessage: configurationError, + metadata: {} + }; + } + + const result = evaluateRules( + request.configuration, + request.type, + request.flagKey, + request.defaultValue, + request.context, + request.logger + ); + const rawMetadata = result.flagMetadata ?? {}; + const allocationKey = + typeof rawMetadata.allocationKey === 'string' + ? rawMetadata.allocationKey + : typeof rawMetadata.__dd_allocation_key === 'string' + ? rawMetadata.__dd_allocation_key + : undefined; + return { + value: result.value, + reason: result.reason, + variant: result.variant, + errorCode: result.errorCode, + errorMessage: result.errorMessage, + metadata: { + allocationKey, + variationType: + normalizeVariationType(rawMetadata.variationType) ?? + recoverVariationType( + request.configuration, + request.flagKey + ), + doLog: + typeof rawMetadata.doLog === 'boolean' + ? rawMetadata.doLog + : typeof rawMetadata.__dd_do_log === 'boolean' + ? rawMetadata.__dd_do_log + : undefined + } + }; + } +}; diff --git a/packages/core/src/flags/configuration/wire.ts b/packages/core/src/flags/configuration/wire.ts index 952636fd0..748ed9a9d 100644 --- a/packages/core/src/flags/configuration/wire.ts +++ b/packages/core/src/flags/configuration/wire.ts @@ -4,12 +4,169 @@ * Copyright 2016-Present Datadog, Inc. */ -// Wire (de)serialization is reused from `@datadog/flagging-core` (the canonical -// implementation) rather than reimplemented here. `configurationFromString` is lenient: -// it returns an empty configuration (`{}`) for malformed input or an unsupported wire -// version rather than throwing. `configurationToString` is the inverse (its fix from +// Published flagging-core 2.0.2 exports wire conversion from its package root. PR #344 keeps +// precomputed-only conversion on the protobuf-free package root and exposes complete conversion +// from `@datadog/flagging-core/rules-based`. In both versions, the input is the complete portable +// JSON envelope. It is not the raw protobuf or legacy JSON response from the UFC service. +// Published `configurationFromString` is lenient: it returns an empty configuration +// (`{}`) for malformed input or an unsupported wire version rather than throwing. +// PR #344 preserves that failure as `configurationError` instead. +// `configurationToString` is the inverse (its fix from // https://github.com/DataDog/openfeature-js-client/pull/331 shipped in flagging-core 2.0.0). -export { - configurationFromString, - configurationToString +import { + configurationFromString as coreConfigurationFromString, + configurationToString as coreConfigurationToString } from '@datadog/flagging-core'; +import type { + FlagsConfiguration, + UniversalFlagConfigurationV1 +} from '@datadog/flagging-core'; + +// TODO(FFL-2837): Delete the pending `rulesBased` types, reader, and wrappers +// after a flagging-core release contains DataDog/openfeature-js-client#344 +// through `78a0c14`. +// Import and re-export the wire functions and `FlagsConfigurationWire` type from +// `@datadog/flagging-core/rules-based`. Do not use the package-root parser for +// rules because it parses precomputed data only and ignores rules. Keep +// `FlagsConfiguration` and the rules evaluator on the package root. The +// package-root parser is protobuf-free and is not the parser for this module. +// PR #336 through `9fd61c4` adds browser providers and shared lifecycle error +// selection. It uses the same `/rules-based` parser boundary. Do not import +// `@datadog/openfeature-browser` in React Native. +// Use `FlagsConfiguration.rules`. The distribution layer must put one base64 +// encoding of the raw dd-source#34959 protobuf response in the version 1 +// `rules.response` field. Record dd-source#40304 commit `071c4ad` as the schema +// revision and dd-source#34959 as the service producer path. Do not add that +// service transport or envelope construction here. PR #344 preserves decoded +// protobuf flags and integers. Its evaluator reports invalid reached data, +// unsupported feature levels, and unsafe integer conversion as deterministic +// flag-scoped `PARSE_ERROR` results. It also validates membership ordering, +// semantic-version bounds, and 32-byte SHA-256 digests. +type PendingRulesConfiguration = FlagsConfiguration & { + configurationError?: string; + rulesError?: string; + rulesBased?: { + response: UniversalFlagConfigurationV1; + fetchedAt?: number; + etag?: string; + }; +}; + +const INVALID_CONFIGURATION_WIRE_ERROR = + 'Invalid flags configuration wire format'; +const INVALID_RULES_WIRE_ENTRY_ERROR = 'Invalid rules configuration wire entry'; +const INVALID_RULES_RESPONSE_ERROR = + 'Rules configuration response could not be decoded'; + +type PendingRulesWire = { + version: 1; + rulesBased?: { + response: string; + fetchedAt?: number; + etag?: string; + }; +}; + +type PendingRulesWireResult = + | { status: 'invalid-configuration' } + | { status: 'no-rules' } + | { status: 'invalid-rules' } + | { + status: 'rules'; + rules: NonNullable; + }; + +const readPendingRulesWire = (source: string): PendingRulesWireResult => { + try { + const wire = JSON.parse(source) as Partial | null; + if ( + !wire || + typeof wire !== 'object' || + Array.isArray(wire) || + wire.version !== 1 + ) { + return { status: 'invalid-configuration' }; + } + if (wire.rulesBased === undefined) { + return { status: 'no-rules' }; + } + if ( + !wire.rulesBased || + typeof wire.rulesBased !== 'object' || + Array.isArray(wire.rulesBased) || + typeof wire.rulesBased.response !== 'string' + ) { + return { status: 'invalid-rules' }; + } + + return { status: 'rules', rules: wire.rulesBased }; + } catch { + return { status: 'invalid-configuration' }; + } +}; + +/** + * Use flagging-core to parse a configuration wire. + */ +export const configurationFromString = (source: string): FlagsConfiguration => { + const configuration = coreConfigurationFromString( + source + ) as PendingRulesConfiguration; + + // TODO(FFL-2837): Delete this legacy JSON compatibility shim with the + // pending types above. The upstream parser decodes `rules.response` as a + // generated Protobuf-ES message. Do not adapt this shim to decode a raw + // service response or to add a base64 layer. Do not copy the strict base64 + // validator that PR #344 removed in favor of the Protobuf-ES decoder. The + // published parser must also include PR #344's unknown-field tolerance, + // unknown-field serialization, and lossless integer parsing through + // `78a0c14`. Its safe-integer conversion does not require global `BigInt`. + // TODO(FFL-2837): Delete this parse-error compatibility behavior when the + // dependency contains PR #344 through `78a0c14`. The upstream parser uses + // `configurationError` for an invalid envelope and `rulesError` for an + // invalid rules entry or response. It keeps a valid sibling branch. + const pendingRules = readPendingRulesWire(source); + if (pendingRules.status === 'invalid-configuration') { + configuration.configurationError = INVALID_CONFIGURATION_WIRE_ERROR; + } else if (pendingRules.status === 'invalid-rules') { + configuration.rulesError = INVALID_RULES_WIRE_ENTRY_ERROR; + } else if (pendingRules.status === 'rules') { + try { + configuration.rulesBased = { + ...pendingRules.rules, + response: JSON.parse(pendingRules.rules.response) + }; + } catch { + configuration.rulesError = INVALID_RULES_RESPONSE_ERROR; + } + } + + return configuration; +}; + +/** + * Use flagging-core to serialize a parsed configuration. + */ +export const configurationToString = ( + configuration: FlagsConfiguration +): string => { + const pendingConfiguration = configuration as PendingRulesConfiguration; + + // TODO(FFL-2837): Delete this legacy serialization wrapper with the pending + // types above after the dependency contains PR #344 through `78a0c14`. + // The upstream serializer encodes generated protobuf + // rules back to base64 and preserves unknown protobuf fields. + // This temporary UFC v1 shim serializes its legacy JSON response instead. + if (pendingConfiguration.rulesBased) { + const serialized = JSON.parse( + coreConfigurationToString(configuration) + ) as PendingRulesWire; + serialized.rulesBased = { + ...pendingConfiguration.rulesBased, + response: JSON.stringify(pendingConfiguration.rulesBased.response) + }; + return JSON.stringify(serialized); + } + + return coreConfigurationToString(configuration); +}; diff --git a/packages/react-native-openfeature/README.md b/packages/react-native-openfeature/README.md index 5fd9cca9a..285cae248 100644 --- a/packages/react-native-openfeature/README.md +++ b/packages/react-native-openfeature/README.md @@ -124,58 +124,65 @@ the network** — you supply it with `setConfiguration`. import { DdFlags } from '@datadog/mobile-react-native'; import { DatadogOfflineOpenFeatureProvider, - configurationFromString + configurationFromString, + getPrecomputedContext } from '@datadog/mobile-react-native-openfeature'; import { OpenFeature } from '@openfeature/react-sdk'; await DdFlags.enable(); -const provider = new DatadogOfflineOpenFeatureProvider(); +const domain = 'offline-flags'; +const configuration = configurationFromString(wire); +const context = getPrecomputedContext(configuration); + +// A context-specific precomputed configuration must use its matching OpenFeature context. +if (context !== undefined) { + await OpenFeature.setContext(domain, context); +} -// `wire` is a ConfigurationWire string you fetched yourself. -provider.setConfiguration(configurationFromString(wire)); +const provider = new DatadogOfflineOpenFeatureProvider(); +provider.setConfiguration(configuration); // Set the provider after loading the configuration so it is ready with real flag values. -await OpenFeature.setProviderAndWait(provider); +await OpenFeature.setProviderAndWait(domain, provider); // Evaluate flags — no network request is made. -const client = OpenFeature.getClient(); -const isNewFeatureEnabled = client.getBooleanValue('new-feature-enabled', false); +const client = OpenFeature.getClient(domain); +const isNewFeatureEnabled = client.getBooleanValue( + 'new-feature-enabled', + false +); ``` -The configuration carries the evaluation context it was computed for, and the provider adopts it -automatically. A precomputed configuration is a **single-subject snapshot**: it can only be served -against the context it was computed for. Per-context evaluation is a future (rules-based) capability. +A context-specific precomputed configuration is a **single-subject snapshot**. The effective +OpenFeature context must match the context that was used to compute the snapshot. Use +`getPrecomputedContext(configuration)` to get a detached copy through a supported API. Do not inspect +the parsed configuration or wire format. The helper does not call OpenFeature and does not change +provider state. + +If a context-specific snapshot does not match the effective context, the provider enters the +OpenFeature **`ERROR`** state. Evaluations return their coded default values with +`errorCode: INVALID_CONTEXT`. Set the matching context to recover the provider to `READY`. -> **Warning:** Do **not** call `OpenFeature.setContext` with a _different_ context for the offline -> precomputed flow. A runtime context that does not match the configuration's embedded context -> (compared after the SDK's context normalization, not raw deep-equality) cannot be served (offline -> never fetches), so the provider enters the OpenFeature **`ERROR`** state and evaluations fall back -> to your **coded default values** (evaluation `errorCode: INVALID_CONTEXT`). The provider recovers to -> `READY` once the effective context is empty or matches the snapshot again. Note that a blank -> `{ targetingKey: '' }` is **not** "empty" — an empty string is a real (anonymous) targeting key, a -> distinct subject that must match the snapshot; use `clearContext()` (or omit context) to fall back -> to the embedded context. +An empty context (`{}`) is a real OpenFeature context. It does not restore the context in the +configuration. An empty targeting key (`{ targetingKey: '' }`) is also a real context and is +different from a missing targeting key. A context-agnostic precomputed configuration has no +embedded context. `getPrecomputedContext` returns `undefined` for that configuration, and it can be +used with any effective context. Recommended setup for a hybrid app that also uses other OpenFeature providers, hooks, or domains: -- **Bind the offline provider to a dedicated OpenFeature domain, and give that domain an explicit - empty context** at registration (`OpenFeature.setContext(domain, {})`) — which this provider reads - as "no override, use the embedded context". A domain with no context of its own **inherits the - global context**, so a global `OpenFeature.setContext` (or a mismatching global context) would - otherwise reach the provider and force it into `ERROR`. +- **Bind the offline provider to a dedicated OpenFeature domain.** Set the helper context on that + domain before provider registration. A domain with no context of its own inherits the global + context. - **Use a unique Datadog `clientName`** (`new DatadogOfflineOpenFeatureProvider({ clientName })`): separate OpenFeature domains otherwise share the same underlying `DdFlags.getClient('default')`, and an online provider on that shared client would discard the offline configuration. -Because you do not set an OpenFeature context, note the **context split**: OpenFeature hooks observe -the OpenFeature evaluation context (`{}` when unset), while Datadog exposure tracking attributes -evaluations to the configuration's embedded context. - -> **Note (recovery caveat):** "clearing context recovers" holds only when the resulting *effective* -> context is empty or matches the snapshot. `OpenFeature.clearContext(domain)` removes the domain -> context and **falls back to the global context** — if that global context is non-empty and does not -> match, the provider stays in `ERROR`. +`OpenFeature.clearContext(domain)` removes the domain context and uses the global context. If the +global context is empty or does not match a context-specific snapshot, the provider enters `ERROR`. +Call `OpenFeature.setContext(domain, matchingContext)` to recover. A global `clearContext()` supplies +`{}` to the provider; it does not restore the context in the configuration. > **Note (startup order):** Load the configuration with `setConfiguration` _before_ > `setProviderAndWait`, as shown above. If you register the provider before any successful diff --git a/packages/react-native-openfeature/src/__tests__/configuration.test.ts b/packages/react-native-openfeature/src/__tests__/configuration.test.ts new file mode 100644 index 000000000..00565c195 --- /dev/null +++ b/packages/react-native-openfeature/src/__tests__/configuration.test.ts @@ -0,0 +1,119 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import type { ParsedFlagsConfiguration } from '@datadog/mobile-react-native'; +import type { EvaluationContext } from '@openfeature/web-sdk'; + +import { getPrecomputedContext } from '../configuration'; + +const configurationWithContext = ( + context?: EvaluationContext +): ParsedFlagsConfiguration => { + return { + precomputed: { + response: { + data: { + attributes: { + createdAt: '2026-08-05T00:00:00.000Z', + flags: {} + } + } + }, + ...(context === undefined ? {} : { context }) + } + }; +}; + +describe('getPrecomputedContext', () => { + it('returns the context from a precomputed configuration', () => { + const configuration = configurationWithContext({ + targetingKey: 'user-1', + country: 'US' + }); + + expect(getPrecomputedContext(configuration)).toEqual({ + targetingKey: 'user-1', + country: 'US' + }); + }); + + it('preserves an explicit empty context and an empty targeting key', () => { + expect(getPrecomputedContext(configurationWithContext({}))).toEqual({}); + expect( + getPrecomputedContext( + configurationWithContext({ targetingKey: '' }) + ) + ).toEqual({ targetingKey: '' }); + }); + + it('returns a deep copy of the context', () => { + const date = new Date('2026-08-05T00:00:00.000Z'); + const configuration = configurationWithContext({ + targetingKey: 'user-1', + profile: { + groups: ['beta', { name: 'mobile' }], + enrolledAt: date + } + }); + + const first = getPrecomputedContext(configuration) as EvaluationContext; + const firstProfile = first.profile as { + groups: Array; + enrolledAt: Date; + }; + firstProfile.groups[1] = { name: 'changed' }; + firstProfile.enrolledAt.setUTCFullYear(2030); + + const second = getPrecomputedContext(configuration); + expect(second).toEqual({ + targetingKey: 'user-1', + profile: { + groups: ['beta', { name: 'mobile' }], + enrolledAt: date + } + }); + expect(second).not.toBe(first); + expect((second?.profile as { groups: unknown[] }).groups).not.toBe( + firstProfile.groups + ); + expect((second?.profile as { enrolledAt: Date }).enrolledAt).not.toBe( + date + ); + }); + + it.each([ + ['an empty configuration', {}], + ['a rules-only configuration', { rulesBased: { response: {} } }], + [ + 'an invalid precomputed branch with valid rules', + { + precomputedError: new Error('invalid precomputed branch'), + rulesBased: { response: {} } + } + ] + ])('returns undefined for %s', (_name, configuration) => { + expect( + getPrecomputedContext(configuration as ParsedFlagsConfiguration) + ).toBeUndefined(); + }); + + it('returns undefined for context-agnostic precomputed configuration', () => { + expect( + getPrecomputedContext(configurationWithContext()) + ).toBeUndefined(); + }); + + it('returns the precomputed context from a mixed configuration', () => { + const configuration = { + ...configurationWithContext({ targetingKey: 'user-1' }), + rulesBased: { response: {} } + } as ParsedFlagsConfiguration; + + expect(getPrecomputedContext(configuration)).toEqual({ + targetingKey: 'user-1' + }); + }); +}); diff --git a/packages/react-native-openfeature/src/__tests__/offlineProvider.integration.test.ts b/packages/react-native-openfeature/src/__tests__/offlineProvider.integration.test.ts index 6c5d2d4d2..08ff5b726 100644 --- a/packages/react-native-openfeature/src/__tests__/offlineProvider.integration.test.ts +++ b/packages/react-native-openfeature/src/__tests__/offlineProvider.integration.test.ts @@ -13,7 +13,9 @@ import { configurationFromString } from '@datadog/mobile-react-native'; import { ErrorCode, OpenFeature, ProviderStatus } from '@openfeature/web-sdk'; +import type { EvaluationContext } from '@openfeature/web-sdk'; +import { getPrecomputedContext } from '../configuration'; import { DatadogOfflineOpenFeatureProvider } from '../offlineProvider'; // Stub the native flags TurboModule (TurboModuleRegistry.get returns null under jest), so @@ -27,7 +29,7 @@ jest.mock('../../../core/src/specs/NativeDdFlags', () => ({ } })); -const wireFor = (targetingKey: string): string => +const wireFor = (context?: EvaluationContext): string => JSON.stringify({ version: 1, precomputed: { @@ -49,7 +51,7 @@ const wireFor = (targetingKey: string): string => } } }), - context: { targetingKey } + ...(context === undefined ? {} : { context }) } }); @@ -61,6 +63,20 @@ const freshNames = () => { return { domain: `offline-int-${seq}`, clientName: `offline-int-${seq}` }; }; +const requiredPrecomputedContext = ( + configuration: ReturnType +): EvaluationContext => { + const context = getPrecomputedContext(configuration); + + if (context === undefined) { + throw new Error( + 'Expected a context-specific precomputed configuration.' + ); + } + + return context; +}; + describe('DatadogOfflineOpenFeatureProvider (integration, real FlagsClient + OpenFeature)', () => { afterEach(async () => { await OpenFeature.clearProviders(); @@ -68,49 +84,95 @@ describe('DatadogOfflineOpenFeatureProvider (integration, real FlagsClient + Ope await OpenFeature.clearContext(); }); - it('is READY when a matching configuration is loaded before registration', async () => { + it('uses the helper context to start READY with a precomputed configuration', async () => { const { domain, clientName } = freshNames(); + const configuration = configurationFromString( + wireFor({ targetingKey: 'user-123' }) + ); + const context = getPrecomputedContext(configuration); + + expect(context).toEqual({ targetingKey: 'user-123' }); + await OpenFeature.setContext( + domain, + requiredPrecomputedContext(configuration) + ); + const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - provider.setConfiguration(configurationFromString(wireFor('user-123'))); + provider.setConfiguration(configuration); await OpenFeature.setProviderAndWait(domain, provider); const client = OpenFeature.getClient(domain); expect(client.providerStatus).toBe(ProviderStatus.READY); expect(client.getBooleanValue('new-feature', false)).toBe(true); + expect( + jest.requireMock('../../../core/src/specs/NativeDdFlags').default + .setEvaluationContext + ).not.toHaveBeenCalled(); }); - it('enters ERROR and serves defaults on a mismatching setContext, then recovers on a matching one', async () => { + it('starts in ERROR when a context-specific configuration has no OpenFeature context', async () => { const { domain, clientName } = freshNames(); const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - provider.setConfiguration(configurationFromString(wireFor('user-123'))); + provider.setConfiguration( + configurationFromString(wireFor({ targetingKey: 'user-123' })) + ); + + await expect( + OpenFeature.setProviderAndWait(domain, provider) + ).rejects.toThrow(); + + const client = OpenFeature.getClient(domain); + expect(client.providerStatus).toBe(ProviderStatus.ERROR); + expect(client.getBooleanDetails('new-feature', false)).toMatchObject({ + value: false, + errorCode: ErrorCode.INVALID_CONTEXT + }); + }); + + it('enters ERROR on a mismatching context and recovers on a matching context', async () => { + const { domain, clientName } = freshNames(); + const configuration = configurationFromString( + wireFor({ targetingKey: 'user-123' }) + ); + await OpenFeature.setContext( + domain, + requiredPrecomputedContext(configuration) + ); + const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); + provider.setConfiguration(configuration); await OpenFeature.setProviderAndWait(domain, provider); - // A runtime context that does not match the snapshot cannot be served. await OpenFeature.setContext(domain, { targetingKey: 'someone-else' }); const client = OpenFeature.getClient(domain); expect(client.providerStatus).toBe(ProviderStatus.ERROR); - // Serving the coded default, with the precise error code. const details = client.getBooleanDetails('new-feature', false); expect(details.value).toBe(false); expect(details.errorCode).toBe(ErrorCode.INVALID_CONTEXT); - // Setting the matching context again recovers automatically and serves the retained value. await OpenFeature.setContext(domain, { targetingKey: 'user-123' }); expect(client.providerStatus).toBe(ProviderStatus.READY); expect(client.getBooleanValue('new-feature', false)).toBe(true); }); - it('errors on an explicit empty-string targeting key (a real anonymous subject, not "cleared")', async () => { + it.each([ + ['an empty context', {}], + ['an empty targeting key', { targetingKey: '' }] + ])('treats %s as a real context', async (_label, nextContext) => { const { domain, clientName } = freshNames(); + const configuration = configurationFromString( + wireFor({ targetingKey: 'user-123' }) + ); + await OpenFeature.setContext( + domain, + requiredPrecomputedContext(configuration) + ); const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - provider.setConfiguration(configurationFromString(wireFor('user-123'))); + provider.setConfiguration(configuration); await OpenFeature.setProviderAndWait(domain, provider); - // `{ targetingKey: '' }` is an anonymous subject, distinct from the user-123 snapshot — not - // the same as clearing context. It must error rather than silently serve user-123's flags. - await OpenFeature.setContext(domain, { targetingKey: '' }); + await OpenFeature.setContext(domain, nextContext); const client = OpenFeature.getClient(domain); expect(client.providerStatus).toBe(ProviderStatus.ERROR); @@ -119,47 +181,67 @@ describe('DatadogOfflineOpenFeatureProvider (integration, real FlagsClient + Ope ); }); - it('stays READY when the context is cleared (empty = re-adopt embedded)', async () => { - const { domain, clientName } = freshNames(); - const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - provider.setConfiguration(configurationFromString(wireFor('user-123'))); - await OpenFeature.setProviderAndWait(domain, provider); + it.each([ + ['context-agnostic', undefined, undefined], + ['explicitly empty', {}, {}] + ])( + 'starts READY with a %s precomputed context', + async (_label, wireContext, expectedHelperContext) => { + const { domain, clientName } = freshNames(); + const configuration = configurationFromString( + wireFor(wireContext as EvaluationContext | undefined) + ); + expect(getPrecomputedContext(configuration)).toEqual( + expectedHelperContext + ); - await OpenFeature.setContext(domain, { targetingKey: 'user-123' }); - expect(OpenFeature.getClient(domain).providerStatus).toBe( - ProviderStatus.READY - ); + const provider = new DatadogOfflineOpenFeatureProvider({ + clientName + }); + provider.setConfiguration(configuration); + await OpenFeature.setProviderAndWait(domain, provider); - // clearContext(domain) falls back to the empty global context; empty means "no override", so - // the embedded context is re-adopted and the provider stays READY. - await OpenFeature.clearContext(domain); - expect(OpenFeature.getClient(domain).providerStatus).toBe( - ProviderStatus.READY - ); - }); + expect(OpenFeature.getClient(domain).providerStatus).toBe( + ProviderStatus.READY + ); + } + ); - it('starts in ERROR when registered before any configuration, then recovers via setConfiguration', async () => { + it('recovers a provider-first setup after the application sets the helper context', async () => { const { domain, clientName } = freshNames(); const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - // Provider-first: initialize rejects (no usable configuration), so registration surfaces - // an error and the provider is ERROR rather than a misleading READY. await expect( OpenFeature.setProviderAndWait(domain, provider) ).rejects.toThrow(); const client = OpenFeature.getClient(domain); expect(client.providerStatus).toBe(ProviderStatus.ERROR); - // Loading a valid configuration recovers via the emitted PROVIDER_READY. - provider.setConfiguration(configurationFromString(wireFor('user-123'))); + const configuration = configurationFromString( + wireFor({ targetingKey: 'user-123' }) + ); + provider.setConfiguration(configuration); + expect(client.providerStatus).toBe(ProviderStatus.ERROR); + + await OpenFeature.setContext( + domain, + requiredPrecomputedContext(configuration) + ); expect(client.providerStatus).toBe(ProviderStatus.READY); expect(client.getBooleanValue('new-feature', false)).toBe(true); }); it('recovers via setConfiguration when a config matching the current context is loaded', async () => { const { domain, clientName } = freshNames(); + const configuration = configurationFromString( + wireFor({ targetingKey: 'user-123' }) + ); + await OpenFeature.setContext( + domain, + requiredPrecomputedContext(configuration) + ); const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - provider.setConfiguration(configurationFromString(wireFor('user-123'))); + provider.setConfiguration(configuration); await OpenFeature.setProviderAndWait(domain, provider); await OpenFeature.setContext(domain, { targetingKey: 'someone-else' }); @@ -169,26 +251,22 @@ describe('DatadogOfflineOpenFeatureProvider (integration, real FlagsClient + Ope // Load a configuration computed for the now-current context: it reconciles to ready and // setConfiguration emits PROVIDER_READY. provider.setConfiguration( - configurationFromString(wireFor('someone-else')) + configurationFromString(wireFor({ targetingKey: 'someone-else' })) ); expect(client.providerStatus).toBe(ProviderStatus.READY); }); describe('domain / global-context isolation', () => { - it('stays READY with the documented setup: global mismatch set, explicit empty domain context, then register', async () => { + it('inherits a matching global context when the domain has no context', async () => { const { domain, clientName } = freshNames(); const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); provider.setConfiguration( - configurationFromString(wireFor('user-123')) + configurationFromString(wireFor({ targetingKey: 'user-123' })) ); - // The documented order: a mismatching GLOBAL context is already in place, the dedicated - // domain is given an explicit empty context (isolating it), and only then is the provider - // registered. It initializes against the empty domain context → embedded → READY. - await OpenFeature.setContext({ targetingKey: 'global-user' }); - await OpenFeature.setContext(domain, {}); + await OpenFeature.setContext({ targetingKey: 'user-123' }); await OpenFeature.setProviderAndWait(domain, provider); expect(OpenFeature.getClient(domain).providerStatus).toBe( @@ -196,45 +274,44 @@ describe('DatadogOfflineOpenFeatureProvider (integration, real FlagsClient + Ope ); }); - it('inherits a mismatching global context when the domain has none, entering ERROR', async () => { + it('enters ERROR when a cleared domain inherits an empty global context', async () => { const { domain, clientName } = freshNames(); + const configuration = configurationFromString( + wireFor({ targetingKey: 'user-123' }) + ); + await OpenFeature.setContext( + domain, + requiredPrecomputedContext(configuration) + ); const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - provider.setConfiguration( - configurationFromString(wireFor('user-123')) - ); + provider.setConfiguration(configuration); + await OpenFeature.setProviderAndWait(domain, provider); - // A global (non-domain) context is set; the domain has no context of its own, so it - // inherits the global one at registration → mismatch → ERROR. - await OpenFeature.setContext({ targetingKey: 'global-user' }); - await expect( - OpenFeature.setProviderAndWait(domain, provider) - ).rejects.toThrow(); + await OpenFeature.clearContext(domain); expect(OpenFeature.getClient(domain).providerStatus).toBe( ProviderStatus.ERROR ); }); - it('ignores later global context changes once the domain has an explicit empty context', async () => { + it('stays READY when a cleared domain inherits a matching global context', async () => { const { domain, clientName } = freshNames(); + const configuration = configurationFromString( + wireFor({ targetingKey: 'user-123' }) + ); + await OpenFeature.setContext({ targetingKey: 'user-123' }); + await OpenFeature.setContext(domain, { + targetingKey: 'user-123' + }); const provider = new DatadogOfflineOpenFeatureProvider({ clientName }); - provider.setConfiguration( - configurationFromString(wireFor('user-123')) - ); + provider.setConfiguration(configuration); await OpenFeature.setProviderAndWait(domain, provider); - // Give the domain its own (empty) context: this provider reads it as "no override". - await OpenFeature.setContext(domain, {}); - expect(OpenFeature.getClient(domain).providerStatus).toBe( - ProviderStatus.READY - ); - - // A later mismatching GLOBAL context does not reach a domain that has its own context. - await OpenFeature.setContext({ targetingKey: 'global-mismatch' }); + await OpenFeature.clearContext(domain); expect(OpenFeature.getClient(domain).providerStatus).toBe( ProviderStatus.READY ); @@ -246,22 +323,20 @@ describe('DatadogOfflineOpenFeatureProvider (integration, real FlagsClient + Ope clientName }); provider.setConfiguration( - configurationFromString(wireFor('user-123')) + configurationFromString(wireFor({ targetingKey: 'user-123' })) ); - await OpenFeature.setProviderAndWait(domain, provider); await OpenFeature.setContext(domain, { targetingKey: 'user-123' }); + await OpenFeature.setProviderAndWait(domain, provider); expect(OpenFeature.getClient(domain).providerStatus).toBe( ProviderStatus.READY ); - // A mismatching global context does not reach the domain while it has its own context. await OpenFeature.setContext({ targetingKey: 'global-mismatch' }); expect(OpenFeature.getClient(domain).providerStatus).toBe( ProviderStatus.READY ); - // Clearing the domain context falls back to the (mismatching) global context → ERROR. await OpenFeature.clearContext(domain); expect(OpenFeature.getClient(domain).providerStatus).toBe( ProviderStatus.ERROR diff --git a/packages/react-native-openfeature/src/__tests__/offlineProvider.test.ts b/packages/react-native-openfeature/src/__tests__/offlineProvider.test.ts index 7a60b331e..78c5f096d 100644 --- a/packages/react-native-openfeature/src/__tests__/offlineProvider.test.ts +++ b/packages/react-native-openfeature/src/__tests__/offlineProvider.test.ts @@ -57,18 +57,16 @@ describe('DatadogOfflineOpenFeatureProvider', () => { ); }); - it('re-adopts the embedded context on an empty initialize context', async () => { + it('records an empty initialize context without fetching', async () => { const provider = new DatadogOfflineOpenFeatureProvider(); await provider.initialize({}); - // An empty context means "no external override": reset to the embedded context rather - // than setting an (empty) override. - expect( - mockFlagsClient.resetEvaluationContextWithoutFetching - ).toHaveBeenCalled(); expect( mockFlagsClient.setEvaluationContextWithoutFetching + ).toHaveBeenCalledWith({ attributes: {} }); + expect( + mockFlagsClient.resetEvaluationContextWithoutFetching ).not.toHaveBeenCalled(); expect(mockFlagsClient.setEvaluationContext).not.toHaveBeenCalled(); }); @@ -99,7 +97,7 @@ describe('DatadogOfflineOpenFeatureProvider', () => { it('rejects initialize when no configuration is loaded (provider-first)', async () => { const provider = new DatadogOfflineOpenFeatureProvider(); - mockFlagsClient.resetEvaluationContextWithoutFetching.mockReturnValueOnce( + mockFlagsClient.setEvaluationContextWithoutFetching.mockReturnValueOnce( notReady ); @@ -140,32 +138,40 @@ describe('DatadogOfflineOpenFeatureProvider', () => { ).toThrow(InvalidContextError); }); - it('re-adopts the embedded context on clearContext / empty context change', () => { + it('treats a cleared or empty context as the effective context', () => { const provider = new DatadogOfflineOpenFeatureProvider(); provider.onContextChange({ targetingKey: 'user-1' }, {}); - // Clearing context is not a mismatch: it re-adopts the embedded context and does not throw. - expect( - mockFlagsClient.resetEvaluationContextWithoutFetching - ).toHaveBeenCalled(); expect( mockFlagsClient.setEvaluationContextWithoutFetching + ).toHaveBeenCalledWith({ attributes: {} }); + expect( + mockFlagsClient.resetEvaluationContextWithoutFetching ).not.toHaveBeenCalled(); }); - it('treats a context with only an undefined targetingKey as empty', () => { + it('does not invent a targeting key when it is undefined', () => { const provider = new DatadogOfflineOpenFeatureProvider(); provider.onContextChange({}, { targetingKey: undefined }); - // `{ targetingKey: undefined }` carries no information: reset to the embedded context. + expect( + mockFlagsClient.setEvaluationContextWithoutFetching + ).toHaveBeenCalledWith({ attributes: {} }); expect( mockFlagsClient.resetEvaluationContextWithoutFetching - ).toHaveBeenCalled(); + ).not.toHaveBeenCalled(); + }); + + it('preserves an explicit empty targeting key', () => { + const provider = new DatadogOfflineOpenFeatureProvider(); + + provider.onContextChange({}, { targetingKey: '' }); + expect( mockFlagsClient.setEvaluationContextWithoutFetching - ).not.toHaveBeenCalled(); + ).toHaveBeenCalledWith({ targetingKey: '', attributes: {} }); }); it('delegates setConfiguration to the client and emits CONFIGURATION_CHANGED', () => { @@ -226,7 +232,7 @@ describe('DatadogOfflineOpenFeatureProvider', () => { // A pre-registration setConfiguration error had no listeners, and the empty initialize // context reconciles to the same error, so initialize rejects -> the Web SDK starts the // provider in ERROR rather than a misleading READY. - mockFlagsClient.resetEvaluationContextWithoutFetching.mockReturnValueOnce( + mockFlagsClient.setEvaluationContextWithoutFetching.mockReturnValueOnce( generalError ); await expect(provider.initialize({})).rejects.toThrow(GeneralError); diff --git a/packages/react-native-openfeature/src/configuration.ts b/packages/react-native-openfeature/src/configuration.ts new file mode 100644 index 000000000..ffd64a09c --- /dev/null +++ b/packages/react-native-openfeature/src/configuration.ts @@ -0,0 +1,72 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import type { ParsedFlagsConfiguration } from '@datadog/mobile-react-native'; +import type { + EvaluationContext, + EvaluationContextValue +} from '@openfeature/web-sdk'; + +// TODO(FFL-2837): Delete this local helper and its clone-semantics tests after a +// flagging-core release contains DataDog/openfeature-js-client#344 through +// `78a0c14`, including merged PR #353, and `@datadog/mobile-react-native` +// re-exports the upstream package-root helper. +// Import and re-export `getPrecomputedContext` from the React Native SDK instead. +// Raise the React Native SDK peer and development dependency minimums to the first +// release that exports it. Replace these semantic tests with one package-root +// forwarding test. Keep the provider and bootstrap integration tests. +const cloneContextValue = ( + value: EvaluationContextValue +): EvaluationContextValue => { + if (value instanceof Date) { + return new Date(value.getTime()); + } + + if (Array.isArray(value)) { + return value.map(cloneContextValue); + } + + if (value !== null && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value).map(([key, nestedValue]) => [ + key, + cloneContextValue(nestedValue) + ]) + ); + } + + return value; +}; + +const cloneEvaluationContext = ( + context: EvaluationContext +): EvaluationContext => { + return Object.fromEntries( + Object.entries(context).map(([key, value]) => [ + key, + cloneContextValue(value) + ]) + ); +}; + +/** + * Return the evaluation context from a precomputed configuration. + * + * The returned context is a detached copy. Setting it as the OpenFeature context is an explicit + * application operation; this function does not modify OpenFeature or provider state. It returns + * `undefined` when the configuration has no context-specific precomputed branch. + */ +export const getPrecomputedContext = ( + configuration: ParsedFlagsConfiguration +): EvaluationContext | undefined => { + const context = configuration.precomputed?.context; + + if (context === undefined) { + return undefined; + } + + return cloneEvaluationContext(context); +}; diff --git a/packages/react-native-openfeature/src/index.ts b/packages/react-native-openfeature/src/index.ts index 55c571c9e..c9614768e 100644 --- a/packages/react-native-openfeature/src/index.ts +++ b/packages/react-native-openfeature/src/index.ts @@ -6,6 +6,7 @@ import { configurationFromString } from '@datadog/mobile-react-native'; +import { getPrecomputedContext } from './configuration'; import { DatadogOfflineOpenFeatureProvider } from './offlineProvider'; import { DatadogOpenFeatureProvider } from './provider'; import type { DatadogOpenFeatureProviderOptions } from './provider'; @@ -13,6 +14,7 @@ import type { DatadogOpenFeatureProviderOptions } from './provider'; export { DatadogOpenFeatureProvider, DatadogOfflineOpenFeatureProvider, - configurationFromString + configurationFromString, + getPrecomputedContext }; export type { DatadogOpenFeatureProviderOptions }; diff --git a/packages/react-native-openfeature/src/mappers.ts b/packages/react-native-openfeature/src/mappers.ts index ecc7d03b8..80651ed9d 100644 --- a/packages/react-native-openfeature/src/mappers.ts +++ b/packages/react-native-openfeature/src/mappers.ts @@ -31,17 +31,20 @@ export const toDdContext = ( }; /** - * Whether an OpenFeature evaluation context carries no information — no targeting key and no - * attributes with a defined value (so `{}` and `{ targetingKey: undefined }` are both empty). - * Used by the offline provider to avoid overwriting a configuration's embedded context with an - * empty context stamped by the OpenFeature lifecycle. - * - * Note: an explicit `targetingKey: ''` is **not** empty. An empty string is a real (anonymous) - * targeting key — a distinct subject — not the absence of a context. Only a genuinely absent - * context (`{}` / `clearContext()`) re-adopts the configuration's embedded context; `{ targetingKey: - * '' }` is reconciled as a real context, so it must match the precomputed snapshot or the provider - * enters `ERROR` (serving coded defaults) rather than silently serving another subject's flags. + * Convert an OpenFeature context for offline evaluation without inventing a targeting key. + * Rules distinguish a missing targeting key from an empty targeting key. */ -export const isEmptyContext = (context: OFEvaluationContext): boolean => { - return Object.values(context).every(value => value === undefined); +export const toDdContextPreservingTargetingKey = ( + context: OFEvaluationContext +): DdEvaluationContext => { + const { targetingKey, ...attributes } = context; + const ddContext = { + attributes: attributes as Record + } as DdEvaluationContext; + + if (targetingKey !== undefined) { + ddContext.targetingKey = targetingKey; + } + + return ddContext; }; diff --git a/packages/react-native-openfeature/src/offlineProvider.ts b/packages/react-native-openfeature/src/offlineProvider.ts index aa4f868a7..f0aec033b 100644 --- a/packages/react-native-openfeature/src/offlineProvider.ts +++ b/packages/react-native-openfeature/src/offlineProvider.ts @@ -22,7 +22,7 @@ import type { } from '@openfeature/web-sdk'; import { DatadogCoreOpenFeatureProvider } from './coreProvider'; -import { isEmptyContext, toDdContext } from './mappers'; +import { toDdContextPreservingTargetingKey } from './mappers'; // The outcome of a `FlagsClient` reconcile. Derived from the client so the provider maps it to // OpenFeature transitions; not part of the package's public API. @@ -49,28 +49,33 @@ const OF_ERROR_CODE: Record = { * It behaves like the online `DatadogOpenFeatureProvider` — same flag evaluation and * exposure/RUM tracking — **except it never fetches configuration from the network**. * Instead of fetching on `initialize`/`onContextChange`, it evaluates against a configuration - * supplied via {@link DatadogOfflineOpenFeatureProvider.setConfiguration}. A precomputed - * configuration carries the evaluation context it was computed for, so you should **not** call - * `OpenFeature.setContext` for the offline precomputed flow — see the class remarks. + * supplied via {@link DatadogOfflineOpenFeatureProvider.setConfiguration}. * * A runtime context that does not match the configuration's embedded context (compared after * normalization) cannot be served (offline never fetches), so it puts the provider into the * OpenFeature `ERROR` state and evaluations fall back to your coded defaults (`INVALID_CONTEXT`). - * An empty *effective* context re-adopts the embedded context and recovers — but note that - * `clearContext(domain)` falls back to the global context, which may itself be non-empty and - * mismatching (and would keep the provider in `ERROR`). Load the configuration before setting the - * provider so it is ready with real flag values from the start: + * An empty context is a real context. It does not select the embedded context. Use + * `getPrecomputedContext` to get a supported copy of the embedded context, and set it on + * OpenFeature before provider registration. Load the configuration before setting the provider so + * it is ready with real flag values from the start: * * @example * ```ts * import { OpenFeature } from '@openfeature/web-sdk'; * import { * DatadogOfflineOpenFeatureProvider, - * configurationFromString + * configurationFromString, + * getPrecomputedContext * } from '@datadog/mobile-react-native-openfeature'; * + * const configuration = configurationFromString(wire); + * const context = getPrecomputedContext(configuration); + * if (context !== undefined) { + * await OpenFeature.setContext(context); + * } + * * const provider = new DatadogOfflineOpenFeatureProvider(); - * provider.setConfiguration(configurationFromString(wire)); // no network + * provider.setConfiguration(configuration); // no network * await OpenFeature.setProviderAndWait(provider); * * const client = OpenFeature.getClient(); @@ -145,15 +150,11 @@ export class DatadogOfflineOpenFeatureProvider extends DatadogCoreOpenFeaturePro } private applyContext(context: OFEvaluationContext): ConfigurationResult { - // An empty context means "no external override": clear it so a loaded precomputed - // configuration is served against its embedded context. Order-independent — the synthetic - // `initialize({})`, `setContext({})`, and `clearContext()` all re-adopt the embedded - // context rather than being treated as a mismatch. - const result = isEmptyContext(context) - ? this.flagsClient.resetEvaluationContextWithoutFetching() - : this.flagsClient.setEvaluationContextWithoutFetching( - toDdContext(context) - ); + // OpenFeature gives the provider only the effective context. It uses `{}` for an unset or + // cleared global context, so the provider must treat `{}` as the real effective context. + const result = this.flagsClient.setEvaluationContextWithoutFetching( + toDdContextPreservingTargetingKey(context) + ); this.configurationInError = result.status === 'error';