|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:meta/meta.dart'; |
| 4 | + |
| 5 | +import '../sentry.dart'; |
| 6 | + |
| 7 | +@internal |
| 8 | +typedef SdkLifecycleCallback<T extends SdkLifecycleEvent> = FutureOr<void> |
| 9 | + Function(T event); |
| 10 | + |
| 11 | +@internal |
| 12 | +abstract class SdkLifecycleEvent {} |
| 13 | + |
| 14 | +/// Holds and dispatches SDK lifecycle events in a type-safe way. |
| 15 | +/// These are meant to be used internally and are not part of public api. |
| 16 | +@internal |
| 17 | +class SdkLifecycleRegistry { |
| 18 | + SdkLifecycleRegistry(this._options); |
| 19 | + |
| 20 | + final SentryOptions _options; |
| 21 | + final _lifecycleCallbacks = <Type, List<Function>>{}; |
| 22 | + |
| 23 | + Map<Type, List<Function>> get lifecycleCallbacks => _lifecycleCallbacks; |
| 24 | + |
| 25 | + void registerCallback<T extends SdkLifecycleEvent>( |
| 26 | + SdkLifecycleCallback<T> callback) { |
| 27 | + _lifecycleCallbacks[T] ??= []; |
| 28 | + _lifecycleCallbacks[T]?.add(callback); |
| 29 | + } |
| 30 | + |
| 31 | + void removeCallback<T extends SdkLifecycleEvent>( |
| 32 | + SdkLifecycleCallback<T> callback) { |
| 33 | + final callbacks = _lifecycleCallbacks[T]; |
| 34 | + callbacks?.remove(callback); |
| 35 | + } |
| 36 | + |
| 37 | + FutureOr<void> dispatchCallback<T extends SdkLifecycleEvent>(T event) async { |
| 38 | + final callbacks = _lifecycleCallbacks[event.runtimeType] ?? []; |
| 39 | + for (final cb in callbacks) { |
| 40 | + try { |
| 41 | + final result = (cb as SdkLifecycleCallback<T>)(event); |
| 42 | + if (result is Future) { |
| 43 | + await result; |
| 44 | + } |
| 45 | + } catch (exception, stackTrace) { |
| 46 | + _options.log( |
| 47 | + SentryLevel.error, |
| 48 | + 'The SDK lifecycle callback threw an exception', |
| 49 | + exception: exception, |
| 50 | + stackTrace: stackTrace, |
| 51 | + ); |
| 52 | + if (_options.automatedTestMode) { |
| 53 | + rethrow; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +@internal |
| 61 | +class OnBeforeCaptureLog extends SdkLifecycleEvent { |
| 62 | + OnBeforeCaptureLog(this.log); |
| 63 | + |
| 64 | + final SentryLog log; |
| 65 | +} |
| 66 | + |
| 67 | +@internal |
| 68 | +class OnBeforeSendEvent extends SdkLifecycleEvent { |
| 69 | + OnBeforeSendEvent(this.event, this.hint); |
| 70 | + |
| 71 | + final SentryEvent event; |
| 72 | + final Hint hint; |
| 73 | +} |
0 commit comments