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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,15 @@ reserved. The event name is case-sensitive and must match the metric's configure

### Flushing

Events are buffered and posted to `eventsURI` every `eventsFlushInterval` ms (10 s) or when `eventsMaxBuffer` (1000)
events are queued. `close()` flushes best-effort; await `flushEvents()` when you need the POST to complete, e.g. before
the app is torn down. Network failures are retried once, then logged and dropped; they never throw.
Events are buffered and posted to `eventsURI` every `eventsFlushInterval` ms (10 s), when `eventsMaxBuffer` (1000)
events are queued, and when the app goes to the background (`hidden`, `paused` or `detached`). The background flush
needs the Flutter binding initialised before the client is created, and is best effort: iOS may suspend the app before
the POST completes, and nothing is sent on force-quit or web page unload. Network failures are retried once, then
logged and dropped; they never throw.

`await close()` stops the client and returns once the final POST completes or the timeout (10 s by default) passes. To
send events without closing the client, await `flushEvents()`. `close()` now returns `Future<void>`, so subclasses that
override it must update their signature.

## Contributing

Expand Down
9 changes: 5 additions & 4 deletions lib/src/core/events/event_processor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import '../../version.dart';

/// Batches experimentation events to `{eventsURI}v1/events`.
///
/// Flushes on a timer, at [maxBuffer], on [flush] and best-effort on [stop].
/// Flushes on a timer, at [maxBuffer], on [flush] and on [stop].
/// Exposures dedupe within a flush window; a failed POST retries once then drops.
class EventProcessor {
static const String flagExposureEvent = r'$flag_exposure';
Expand Down Expand Up @@ -156,13 +156,14 @@ class EventProcessor {
}
}

/// Cancels the timer and flushes without awaiting; await [flush] for teardown.
/// Cancels the timer and flushes. The returned future completes once every
/// upload in flight has finished, and never throws.
/// Events tracked after this are dropped until [start] is called again.
void stop() {
Future<void> stop() {
_stopped = true;
_timer?.cancel();
_timer = null;
unawaited(flush());
return flush();
}

Future<void> _postBatch(
Expand Down
73 changes: 70 additions & 3 deletions lib/src/flagsmith_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import 'dart:convert';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/widgets.dart'
show AppLifecycleState, WidgetsBinding, WidgetsBindingObserver;
import 'package:flutter_client_sse/constants/sse_request_type_enum.dart';
import 'package:flutter_client_sse/flutter_client_sse.dart';
import 'package:rxdart/subjects.dart';
Expand Down Expand Up @@ -49,6 +51,7 @@ class FlagsmithClient {
Timer? _analyticsTimer;

EventProcessor? _eventProcessor;
_EventsLifecycleObserver? _lifecycleObserver;

/// Internal events pipeline; exposed for tests only.
@visibleForTesting
Expand Down Expand Up @@ -90,12 +93,38 @@ class FlagsmithClient {
maxBuffer: config.eventsMaxBuffer,
log: log,
)..start();
_observeLifecycle();
}
if (config.enableRealtimeUpdates) {
_setupRealtimeUpdates(config.realtimeUpdatesBaseURI);
}
}

/// Flushes events when the app goes to the background. Skipped when the
/// client is created before the Flutter binding is initialised.
void _observeLifecycle() {
final binding = _widgetsBindingOrNull();
if (binding == null) {
log('Events: Flutter binding not initialised, so events will not be '
'flushed when the app goes to the background');
return;
}
final observer = _EventsLifecycleObserver(
() => unawaited(_eventProcessor?.flush()));
binding.addObserver(observer);
_lifecycleObserver = observer;
}

static WidgetsBinding? _widgetsBindingOrNull() {
// The getter throws until runApp() or ensureInitialized() has run: a
// FlutterError in debug builds, a TypeError in release builds.
try {
return WidgetsBinding.instance;
} catch (_) {
return null;
}
}

Future<void> _setupAnalyticsTimer(int analyticsInterval) async {
_analyticsTimer?.cancel();
// Failures are logged, and the analytics are resent on the next tick.
Expand Down Expand Up @@ -717,11 +746,29 @@ class FlagsmithClient {
// Loading from API
Stream<FlagsmithLoading> get loading => _loading.stream;

void close() {
/// Stops the client and flushes buffered events. The returned future
/// completes once the final POST finishes or [timeout] passes, whichever
/// comes first; it never throws. On timeout the POST carries on in the
/// background. Events tracked after this are dropped.
Future<void> close({Duration timeout = const Duration(seconds: 10)}) async {
final flushing = _eventProcessor?.stop();
_analyticsTimer?.cancel();
_eventProcessor?.stop();
final observer = _lifecycleObserver;
if (observer != null) {
_widgetsBindingOrNull()?.removeObserver(observer);
_lifecycleObserver = null;
}
SSEClient.unsubscribeFromSSE();
_loading.close();
unawaited(_loading.close());
if (flushing == null) {
return;
}
try {
await flushing.timeout(timeout);
} on TimeoutException {
log('Events: close() timed out after ${timeout.inMilliseconds} ms; '
'the final POST continues in the background');
}
Comment thread
Zaimwa9 marked this conversation as resolved.
Resolved
Comment thread
Zaimwa9 marked this conversation as resolved.
Resolved
}

/// test toggle feature
Expand All @@ -737,3 +784,23 @@ class FlagsmithClient {
return result;
}
}

class _EventsLifecycleObserver with WidgetsBindingObserver {
_EventsLifecycleObserver(this._onBackground);

final void Function() _onBackground;

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
// hidden is the only signal on web; paused and detached on mobile.
case AppLifecycleState.hidden:
case AppLifecycleState.paused:
case AppLifecycleState.detached:
_onBackground();
case AppLifecycleState.resumed:
case AppLifecycleState.inactive:
break;
}
}
}
86 changes: 85 additions & 1 deletion test/fg/flagsmith_experiments_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import 'package:dio/dio.dart';
import 'package:flagsmith/flagsmith.dart';
import 'package:flagsmith/src/core/events/event_processor.dart';
import 'package:flagsmith/src/version.dart';
import 'package:flutter/widgets.dart' show AppLifecycleState;
import 'package:flutter_test/flutter_test.dart' show TestWidgetsFlutterBinding;
import 'package:http_mock_adapter/http_mock_adapter.dart';
import 'package:test/test.dart';

Expand Down Expand Up @@ -33,6 +35,7 @@ Future<(FlagsmithClient, EventsCapture)> buildClient({
int flushInterval = 60000,
int maxBuffer = 1000,
bool eventsFail = false,
Duration eventsDelay = Duration.zero,
bool loadUserFlags = true,
}) async {
final fs = FlagsmithClient(
Expand All @@ -57,7 +60,7 @@ Future<(FlagsmithClient, EventsCapture)> buildClient({
DioException(requestOptions: RequestOptions(path: eventsEndpoint)));
return;
}
server.reply(200, <String, dynamic>{});
server.reply(200, <String, dynamic>{}, delay: eventsDelay);
}, data: Matchers.any);
});
await fs.initialize();
Expand Down Expand Up @@ -510,6 +513,36 @@ void main() {
expect(fs.eventProcessor!.buffer, isEmpty);
});

test('When close is awaited, then it returns after the final POST',
() async {
final (fs, capture) =
await buildClient(eventsDelay: const Duration(milliseconds: 50));
var responses = 0;
fs.client.interceptors.add(InterceptorsWrapper(onResponse: (r, h) {
responses++;
h.next(r);
}));
fs.trackEvent('purchase');

await fs.close();

expect(capture.events.single['event'], 'purchase');
expect(responses, 1);
});

test('When final POST outlasts the timeout, then close returns anyway',
() async {
final (fs, capture) =
await buildClient(eventsDelay: const Duration(seconds: 2));
fs.trackEvent('purchase');
final watch = Stopwatch()..start();

await fs.close(timeout: const Duration(milliseconds: 50));

expect(watch.elapsedMilliseconds, lessThan(1000));
expect(capture.requests.length, 1, reason: 'POST was started');
});

test('When client is closed, then later events are dropped', () async {
final (fs, capture) = await buildClient();
fs.close();
Expand Down Expand Up @@ -537,6 +570,57 @@ void main() {
});
});

group('[Experiments] app lifecycle', () {
late TestWidgetsFlutterBinding binding;
setUpAll(() => binding = TestWidgetsFlutterBinding.ensureInitialized());
tearDown(() =>
binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed));

for (final state in [
AppLifecycleState.hidden,
AppLifecycleState.paused,
AppLifecycleState.detached,
]) {
test('When app becomes ${state.name}, then buffered events are flushed',
() async {
final (fs, capture) = await buildClient();
addTearDown(fs.close);
fs.trackEvent('purchase');

binding.handleAppLifecycleStateChanged(state);

expect(fs.eventProcessor!.buffer, isEmpty);
await fs.flushEvents();
expect(capture.events.single['event'], 'purchase');
});
}

test('When app becomes inactive, then events stay buffered', () async {
final (fs, capture) = await buildClient();
addTearDown(fs.close);
fs.trackEvent('purchase');

binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);

expect(fs.eventProcessor!.buffer.length, 1);
expect(capture.requests, isEmpty);
});

test('When client is closed, then backgrounding no longer flushes',
() async {
final (fs, _) = await buildClient();
await fs.close();
// Restart the processor so a leaked listener would show as a flush.
final processor = fs.eventProcessor!..start();
addTearDown(processor.stop);
fs.trackEvent('purchase');

binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);

expect(processor.buffer.length, 1);
});
});

group('[Experiments] EventProcessor', () {
late Dio dio;
late DioAdapter adapter;
Expand Down
15 changes: 15 additions & 0 deletions test/fg/flagsmith_no_binding_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import 'package:flagsmith/flagsmith.dart';
import 'package:test/test.dart';

import '../shared.dart';

// Own file so the Flutter binding is never initialised in this isolate.
void main() {
test('When client is created before the Flutter binding, then it works',
() async {
final fs = FlagsmithClient(
apiKey: apiKey, config: const FlagsmithConfig(enableEvents: true));

await expectLater(fs.close(), completes);
});
}
Loading