diff --git a/README.md b/README.md index ee8f12f..ea1c74f 100644 --- a/README.md +++ b/README.md @@ -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`, so subclasses that +override it must update their signature. ## Contributing diff --git a/lib/src/core/events/event_processor.dart b/lib/src/core/events/event_processor.dart index 63732df..76444c8 100644 --- a/lib/src/core/events/event_processor.dart +++ b/lib/src/core/events/event_processor.dart @@ -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'; @@ -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 stop() { _stopped = true; _timer?.cancel(); _timer = null; - unawaited(flush()); + return flush(); } Future _postBatch( diff --git a/lib/src/flagsmith_client.dart b/lib/src/flagsmith_client.dart index c8e67dd..955faa4 100644 --- a/lib/src/flagsmith_client.dart +++ b/lib/src/flagsmith_client.dart @@ -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'; @@ -49,6 +51,7 @@ class FlagsmithClient { Timer? _analyticsTimer; EventProcessor? _eventProcessor; + _EventsLifecycleObserver? _lifecycleObserver; /// Internal events pipeline; exposed for tests only. @visibleForTesting @@ -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 _setupAnalyticsTimer(int analyticsInterval) async { _analyticsTimer?.cancel(); // Failures are logged, and the analytics are resent on the next tick. @@ -717,11 +746,29 @@ class FlagsmithClient { // Loading from API Stream 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 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'); + } } /// test toggle feature @@ -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; + } + } +} diff --git a/test/fg/flagsmith_experiments_test.dart b/test/fg/flagsmith_experiments_test.dart index ce7abe4..ee713f4 100644 --- a/test/fg/flagsmith_experiments_test.dart +++ b/test/fg/flagsmith_experiments_test.dart @@ -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'; @@ -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( @@ -57,7 +60,7 @@ Future<(FlagsmithClient, EventsCapture)> buildClient({ DioException(requestOptions: RequestOptions(path: eventsEndpoint))); return; } - server.reply(200, {}); + server.reply(200, {}, delay: eventsDelay); }, data: Matchers.any); }); await fs.initialize(); @@ -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(); @@ -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; diff --git a/test/fg/flagsmith_no_binding_test.dart b/test/fg/flagsmith_no_binding_test.dart new file mode 100644 index 0000000..fca841c --- /dev/null +++ b/test/fg/flagsmith_no_binding_test.dart @@ -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); + }); +}