Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Adds support for client-side prerequisite events #172

Merged
merged 4 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ class TestApiImpl extends SdkTestApi {
'client-independence',
'context-comparison',
'inline-context',
'anonymous-redaction'
'anonymous-redaction',
'client-prereq-events',
];

static const clientUrlPrefix = '/client/';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ final class DefaultEventProcessor implements EventProcessor {

DefaultEventProcessor(
{required LDLogger logger,
bool indexEvents = false,
required bool indexEvents,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For reviewers: I was trying to find a way to not have to tweak this, but the typedef of EventProcessorFactory was not handling the optional named parameter with default well.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure I see why the type here needs to change, it seems like it would just get redundantly passed, which should be fine. Like required at the factory level, but not at the constructor level.

That said I am indifferent to the change.

required int eventCapacity,
required Duration flushInterval,
required HttpClient client,
Expand Down
4 changes: 4 additions & 0 deletions packages/common/lib/src/ld_evaluation_result.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ final class LDEvaluationResult {
/// True if a client SDK should track reasons for this flag.
final bool trackReason;

/// List of prerequisite flags that were evaluated as part of determining this [LDEvaluationResult]
final List<String>? prerequisites;

/// A millisecond timestamp, which if the current time is before, a client SDK
/// should send debug events for the flag.
final int? debugEventsUntilDate;
Expand All @@ -31,6 +34,7 @@ final class LDEvaluationResult {
required this.detail,
this.trackEvents = false,
this.trackReason = false,
this.prerequisites,
this.debugEventsUntilDate});

@override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ final class LDEvaluationResultSerialization {
final flagVersion = json['flagVersion'] as num?;
final trackEvents = (json['trackEvents'] ?? false) as bool;
final trackReason = (json['trackReason'] ?? false) as bool;
final prerequisites = (json['prerequisites'] as List<dynamic>?)
?.map((e) => e as String)
.toList();
final debugEventsUntilDateRaw = json['debugEventsUntilDate'] as num?;
final value = LDValueSerialization.fromJson(json['value']);
final jsonReason = json['reason'];
Expand All @@ -24,6 +27,7 @@ final class LDEvaluationResultSerialization {
detail: LDEvaluationDetail(value, variationIndex, reason),
trackEvents: trackEvents,
trackReason: trackReason,
prerequisites: prerequisites,
debugEventsUntilDate: debugEventsUntilDateRaw?.toInt());
}

Expand All @@ -37,6 +41,9 @@ final class LDEvaluationResultSerialization {
if (evaluationResult.trackReason) {
result['trackReason'] = evaluationResult.trackReason;
}
if (evaluationResult.prerequisites?.isNotEmpty ?? false) {
result['prerequisites'] = evaluationResult.prerequisites;
}
if (evaluationResult.debugEventsUntilDate != null) {
result['debugEventsUntilDate'] = evaluationResult.debugEventsUntilDate;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/common/test/events/event_processor_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import '../logging_test.dart';
return (
DefaultEventProcessor(
logger: LDLogger(adapter: adapter),
indexEvents: false,
eventCapacity: 100,
flushInterval: Duration(milliseconds: 100),
client: client,
Expand All @@ -47,6 +48,7 @@ import '../logging_test.dart';
return (
DefaultEventProcessor(
logger: LDLogger(adapter: adapter),
indexEvents: false,
eventCapacity: 100,
flushInterval: Duration(milliseconds: 100),
client: client,
Expand Down
58 changes: 56 additions & 2 deletions packages/common_client/lib/src/ld_common_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,48 @@ Map<ConnectionMode, DataSourceFactory> _defaultFactories(
};
}

typedef EventProcessorFactory = EventProcessor Function(
{required LDLogger logger,
required bool indexEvents,
required int eventCapacity,
required Duration flushInterval,
required HttpClient client,
required String analyticsEventsPath,
required String diagnosticEventsPath,
required ServiceEndpoints endpoints,
required Duration diagnosticRecordingInterval,
required bool allAttributesPrivate,
required Set<AttributeReference> globalPrivateAttributes,
DiagnosticsManager? diagnosticsManager});

EventProcessor _defaultEventProcessorFactory(
{required LDLogger logger,
required bool indexEvents,
required int eventCapacity,
required Duration flushInterval,
required HttpClient client,
required String analyticsEventsPath,
required String diagnosticEventsPath,
required ServiceEndpoints endpoints,
required Duration diagnosticRecordingInterval,
required bool allAttributesPrivate,
required Set<AttributeReference> globalPrivateAttributes,
DiagnosticsManager? diagnosticsManager}) {
return DefaultEventProcessor(
logger: logger,
indexEvents: indexEvents,
eventCapacity: eventCapacity,
flushInterval: flushInterval,
client: client,
analyticsEventsPath: analyticsEventsPath,
diagnosticEventsPath: diagnosticEventsPath,
diagnosticsManager: diagnosticsManager,
endpoints: endpoints,
allAttributesPrivate: allAttributesPrivate,
globalPrivateAttributes: globalPrivateAttributes,
diagnosticRecordingInterval: diagnosticRecordingInterval);
}

final class LDCommonClient {
final LDCommonConfig _config;
final Persistence _persistence;
Expand All @@ -96,6 +138,8 @@ final class LDCommonClient {
// If there are cross-dependent modifiers, then this must be considered.
late final List<ContextModifier> _modifiers;

final EventProcessorFactory _eventProcessorFactory;

/// The event processor is not constructed during LDCommonClient construction
/// because it requires the HTTP properties which must be determined
/// asynchronously.
Expand Down Expand Up @@ -127,7 +171,8 @@ final class LDCommonClient {

LDCommonClient(LDCommonConfig commonConfig, CommonPlatform platform,
LDContext context, DiagnosticSdkData sdkData,
{DataSourceFactoriesFn? dataSourceFactories})
{DataSourceFactoriesFn? dataSourceFactories,
EventProcessorFactory? eventProcessorFactory})
: _config = commonConfig,
_platform = platform,
_persistence = ValidatingPersistence(
Expand All @@ -143,6 +188,8 @@ final class LDCommonClient {
_initialUndecoratedContext = context,
// Data source factories is primarily a mechanism for testing.
_dataSourceFactories = dataSourceFactories ?? _defaultFactories,
_eventProcessorFactory =
eventProcessorFactory ?? _defaultEventProcessorFactory,
_sdkData = sdkData {
final dataSourceEventHandler = DataSourceEventHandler(
flagManager: _flagManager,
Expand Down Expand Up @@ -273,8 +320,9 @@ final class LDCommonClient {
final osInfo = _envReport.osInfo;
DiagnosticsManager? diagnosticsManager = _makeDiagnosticsManager(osInfo);

_eventProcessor = DefaultEventProcessor(
_eventProcessor = _eventProcessorFactory(
logger: _logger,
indexEvents: false,
eventCapacity: _config.events.eventCapacity,
flushInterval: _config.events.flushInterval,
client: HttpClient(httpProperties: httpProperties),
Expand Down Expand Up @@ -528,6 +576,12 @@ final class LDCommonClient {
LDEvaluationDetail<LDValue> detail;

if (evalResult != null && evalResult.flag != null) {
if (evalResult.flag?.prerequisites != null) {
tanderson-ld marked this conversation as resolved.
Show resolved Hide resolved
evalResult.flag?.prerequisites?.forEach((prereq) {
_variationInternal(prereq, LDValue.ofNull(), isDetailed: isDetailed);
});
}

if (type == null || type == evalResult.flag!.detail.value.type) {
detail = evalResult.flag!.detail;
} else {
Expand Down
63 changes: 63 additions & 0 deletions packages/common_client/test/ld_dart_client_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:launchdarkly_common_client/launchdarkly_common_client.dart';
import 'package:launchdarkly_common_client/src/data_sources/data_source.dart';
import 'package:test/test.dart';

import 'mock_eventprocessor.dart';
import 'mock_persistence.dart';

final class TestConfig extends LDCommonConfig {
Expand Down Expand Up @@ -284,4 +285,66 @@ void main() {
expect(res, 'datasource');
});
});

group('given mock flag data with prerequisites', () {
late LDCommonClient client;
late MockPersistence mockPersistence;
late MockEventProcessor mockEventProcessor;
final sdkKey = 'the-sdk-key';
final sdkKeyPersistence =
'LaunchDarkly_${sha256.convert(utf8.encode(sdkKey))}';

setUp(() {
mockPersistence = MockPersistence();
mockEventProcessor = MockEventProcessor();
client = LDCommonClient(
TestConfig(sdkKey, AutoEnvAttributes.disabled),
CommonPlatform(persistence: mockPersistence),
LDContextBuilder().kind('user', 'bob').build(),
DiagnosticSdkData(name: '', version: ''),
dataSourceFactories: (LDCommonConfig config, LDLogger logger,
HttpProperties properties) {
return {
ConnectionMode.streaming: (LDContext context) {
return TestDataSource();
},
ConnectionMode.polling: (LDContext context) {
return TestDataSource();
},
};
},
eventProcessorFactory: (
{required allAttributesPrivate,
required analyticsEventsPath,
required client,
required diagnosticEventsPath,
required diagnosticRecordingInterval,
diagnosticsManager,
required endpoints,
required eventCapacity,
required flushInterval,
required globalPrivateAttributes,
required indexEvents,
required logger}) =>
mockEventProcessor,
);
});

test('it includes reports events for each prerequisite', () async {
final contextPersistenceKey =
sha256.convert(utf8.encode('bob')).toString();
mockPersistence.storage[sdkKeyPersistence] = {
contextPersistenceKey:
'{"flagA":{"version":1,"value":"storage","variation":0,"reason":{"kind":"OFF"},"prerequisites":["flagAB"]},"flagAB":{"version":1,"value":"storage","variation":0,"reason":{"kind":"OFF"}}}'
};

await client
.start(); // note no call to wait for network results here so we get the storage values
final res = client.stringVariation('flagA', 'default');
expect(res, 'storage');
expect(mockEventProcessor.evalEvents.length, 2);
expect(mockEventProcessor.evalEvents[0].flagKey, 'flagAB');
expect(mockEventProcessor.evalEvents[1].flagKey, 'flagA');
});
});
}
37 changes: 37 additions & 0 deletions packages/common_client/test/mock_eventprocessor.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import 'package:launchdarkly_dart_common/launchdarkly_dart_common.dart';

final class MockEventProcessor implements EventProcessor {
final customEvents = <CustomEvent>[];
final evalEvents = <EvalEvent>[];
final identifyEvents = <IdentifyEvent>[];

@override
Future<void> flush() async {
// no-op in this mock
}

@override
void processCustomEvent(CustomEvent event) {
customEvents.add(event);
}

@override
void processEvalEvent(EvalEvent event) {
evalEvents.add(event);
}

@override
void processIdentifyEvent(IdentifyEvent event) {
identifyEvents.add(event);
}

@override
void start() {
// no-op in this mock
}

@override
void stop() {
// no-op in this mock
}
}
Loading