diff --git a/examples/console/bin/main.dart b/examples/console/bin/main.dart index 7b2b6df..e0d2e23 100644 --- a/examples/console/bin/main.dart +++ b/examples/console/bin/main.dart @@ -12,11 +12,11 @@ void main([List? args]) { final options = _extractOptions(args ?? const []); runZonedGuarded( () async { - // Create centrifuge client. + // Create Spinify client. final client = Spinify( SpinifyConfig( client: ( - name: 'Centrifuge Console Example', + name: 'Spinify Console Example', version: '0.0.1', ), getToken: () => @@ -54,7 +54,7 @@ void main([List? args]) { io.exit(1); }, zoneValues: { - #dev.plugfox.centrifuge.log: options.verbose, + #dev.plugfox.spinify.log: options.verbose, }, ); } @@ -74,11 +74,11 @@ void main([List? args]) { )) .parse(args); final token = result['token']?.toString() ?? - io.Platform.environment['CENTRIFUGE_JWT_TOKEN']; + io.Platform.environment['SPINIFY_JWT_TOKEN']; if (token == null || token.isEmpty || token.split('.').length != 3) { print('Please provide a valid JWT token as argument with --token option ' 'or ' - 'CENTRIFUGE_JWT_TOKEN environment variable.'); + 'SPINIFY_JWT_TOKEN environment variable.'); io.exit(1); } return ( diff --git a/lib/interface.dart b/lib/interface.dart index 90ccdbf..c9b26ae 100644 --- a/lib/interface.dart +++ b/lib/interface.dart @@ -1,7 +1,7 @@ library interface; -export 'package:spinify/src/client/centrifuge_interface.dart'; export 'package:spinify/src/client/config.dart'; +export 'package:spinify/src/client/spinify_interface.dart'; export 'package:spinify/src/client/state.dart'; export 'package:spinify/src/client/states_stream.dart'; export 'package:spinify/src/model/client_info.dart'; @@ -11,7 +11,7 @@ export 'package:spinify/src/model/publication.dart'; export 'package:spinify/src/subscription/subscription.dart' show ISpinifySubscription, - CentrifugeClientSubscription, - CentrifugeServerSubscription; + SpinifyClientSubscription, + SpinifyServerSubscription; export 'package:spinify/src/subscription/subscription_config.dart'; export 'package:spinify/src/subscription/subscription_state.dart'; diff --git a/lib/spinify.dart b/lib/spinify.dart index 138566a..e4c21b6 100644 --- a/lib/spinify.dart +++ b/lib/spinify.dart @@ -1,7 +1,7 @@ library spinify; -export 'package:spinify/src/client/centrifuge.dart' show Spinify; export 'package:spinify/src/client/config.dart'; +export 'package:spinify/src/client/spinify.dart' show Spinify; export 'package:spinify/src/client/state.dart'; export 'package:spinify/src/client/states_stream.dart'; export 'package:spinify/src/model/client_info.dart'; @@ -9,6 +9,6 @@ export 'package:spinify/src/model/exception.dart'; export 'package:spinify/src/model/jwt.dart'; export 'package:spinify/src/model/publication.dart'; export 'package:spinify/src/subscription/subscription.dart' - show CentrifugeClientSubscription, CentrifugeServerSubscription; + show SpinifyClientSubscription, SpinifyServerSubscription; export 'package:spinify/src/subscription/subscription_config.dart'; export 'package:spinify/src/subscription/subscription_state.dart'; diff --git a/lib/src/client/config.dart b/lib/src/client/config.dart index 43f987b..0c568a2 100644 --- a/lib/src/client/config.dart +++ b/lib/src/client/config.dart @@ -4,22 +4,22 @@ import 'package:meta/meta.dart'; import 'package:spinify/src/model/pubspec.yaml.g.dart'; /// Token used for authentication -typedef CentrifugeToken = String; +typedef SpinifyToken = String; /// Callback to get/refresh tokens /// This callback is used for initial connection /// and for refreshing expired tokens. /// /// If method returns null then connection will be established without token. -typedef CentrifugeTokenCallback = FutureOr Function(); +typedef SpinifyTokenCallback = FutureOr Function(); /// Callback to get initial connection payload data. /// /// If method returns null then no payload will be sent at connect time. -typedef CentrifugeConnectionPayloadCallback = FutureOr?> Function(); +typedef SpinifyConnectionPayloadCallback = FutureOr?> Function(); -/// {@template centrifuge_config} -/// Centrifuge client common options. +/// {@template spinify_config} +/// Spinify client common options. /// /// There are several common options available when creating Client instance. /// @@ -32,7 +32,7 @@ typedef CentrifugeConnectionPayloadCallback = FutureOr?> Function(); /// {@category Entity} @immutable final class SpinifyConfig { - /// {@macro centrifuge_config} + /// {@macro spinify_config} SpinifyConfig({ this.getToken, this.getPayload, @@ -52,7 +52,7 @@ final class SpinifyConfig { /// Create a default config /// - /// {@macro centrifuge_config} + /// {@macro spinify_config} factory SpinifyConfig.byDefault() = SpinifyConfig; /// Callback to get/refresh tokens @@ -60,13 +60,13 @@ final class SpinifyConfig { /// and for refreshing expired tokens. /// /// If method returns null then connection will be established without token. - final CentrifugeTokenCallback? getToken; + final SpinifyTokenCallback? getToken; /// Callback to get connection payload data. /// The resulted data send with every connect request. /// /// If method returns null then no payload will be sent at connect time. - final CentrifugeConnectionPayloadCallback? getPayload; + final SpinifyConnectionPayloadCallback? getPayload; /// The additional delay between expected server heartbeat pings. /// @@ -101,5 +101,5 @@ final class SpinifyConfig { final Duration timeout; @override - String toString() => 'CentrifugeConfig{}'; + String toString() => 'SpinifyConfig{}'; } diff --git a/lib/src/client/observer.dart b/lib/src/client/observer.dart index ab67201..a44fa28 100644 --- a/lib/src/client/observer.dart +++ b/lib/src/client/observer.dart @@ -1,11 +1,11 @@ -import 'package:spinify/src/client/centrifuge_interface.dart'; +import 'package:spinify/src/client/spinify_interface.dart'; import 'package:spinify/src/client/state.dart'; import 'package:spinify/src/model/event.dart'; import 'package:spinify/src/model/exception.dart'; import 'package:spinify/src/subscription/subscription.dart'; import 'package:spinify/src/subscription/subscription_state.dart'; -/// An interface for observing the behavior of Centrifuge instances. +/// An interface for observing the behavior of Spinify instances. /// {@category Client} /// {@subCategory Observer} abstract class SpinifyObserver { @@ -13,29 +13,28 @@ abstract class SpinifyObserver { void onCreate(ISpinify client) {} /// Called whenever a [ISpinify] client changes its state - /// to [CentrifugeState$Connecting]. - void onConnected(ISpinify client, CentrifugeState$Connected state) {} + /// to [SpinifyState$Connecting]. + void onConnected(ISpinify client, SpinifyState$Connected state) {} - /// Called whenever a [ISpinify] client receives a [CentrifugeEvent]. - void onEvent(ISpinify client, CentrifugeEvent event) {} + /// Called whenever a [ISpinify] client receives a [SpinifyEvent]. + void onEvent(ISpinify client, SpinifyEvent event) {} /// Called whenever a [ISpinify] client changes its state /// from [prev] to [next]. - void onStateChanged( - ISpinify client, CentrifugeState prev, CentrifugeState next) {} + void onStateChanged(ISpinify client, SpinifyState prev, SpinifyState next) {} /// Called whenever a [ISpinifySubscription] changes its state /// from [prev] to [next]. /// Works both for client-side and server-side subscriptions. void onSubscriptionChanged(ISpinifySubscription subscription, - CentrifugeSubscriptionState prev, CentrifugeSubscriptionState next) {} + SpinifySubscriptionState prev, SpinifySubscriptionState next) {} /// Called whenever a [ISpinify] client changes its state - /// to [CentrifugeState$Disconnected]. - void onDisconnected(ISpinify client, CentrifugeState$Disconnected state) {} + /// to [SpinifyState$Disconnected]. + void onDisconnected(ISpinify client, SpinifyState$Disconnected state) {} - /// Called whenever an error is thrown in any Centrifuge client. - void onError(CentrifugeException error, StackTrace stackTrace) {} + /// Called whenever an error is thrown in any Spinify client. + void onError(SpinifyException error, StackTrace stackTrace) {} /// Called whenever a [ISpinify] is closed. void onClose(ISpinify client) {} diff --git a/lib/src/client/centrifuge.dart b/lib/src/client/spinify.dart similarity index 72% rename from lib/src/client/centrifuge.dart rename to lib/src/client/spinify.dart index f5c1b8a..44f5663 100644 --- a/lib/src/client/centrifuge.dart +++ b/lib/src/client/spinify.dart @@ -1,10 +1,10 @@ import 'dart:async'; import 'package:meta/meta.dart'; -import 'package:spinify/src/client/centrifuge_interface.dart'; import 'package:spinify/src/client/config.dart'; import 'package:spinify/src/client/disconnect_code.dart'; import 'package:spinify/src/client/observer.dart'; +import 'package:spinify/src/client/spinify_interface.dart'; import 'package:spinify/src/client/state.dart'; import 'package:spinify/src/client/states_stream.dart'; import 'package:spinify/src/model/channel_presence.dart'; @@ -80,7 +80,7 @@ abstract base class SpinifyBase implements ISpinify { @nonVirtual late final ISpinifyTransport _transport; - /// Centrifuge config. + /// Spinify config. /// {@nodoc} @nonVirtual final SpinifyConfig _config; @@ -95,7 +95,7 @@ abstract base class SpinifyBase implements ISpinify { late final ServerSubscriptionManager _serverSubscriptionManager = ServerSubscriptionManager(_transport); - /// Init centrifuge client, override this method to add custom logic. + /// Init spinify client, override this method to add custom logic. /// This method is called in constructor. /// {@nodoc} @protected @@ -106,21 +106,21 @@ abstract base class SpinifyBase implements ISpinify { } /// Called when connection established. - /// Right before [CentrifugeState$Connected] state. + /// Right before [SpinifyState$Connected] state. /// {@nodoc} @protected @mustCallSuper - void _onConnected(CentrifugeState$Connected state) { + void _onConnected(SpinifyState$Connected state) { logger.fine('Connection established'); Spinify.observer?.onConnected(this, state); } /// Called when connection lost. - /// Right before [CentrifugeState$Disconnected] state. + /// Right before [SpinifyState$Disconnected] state. /// {@nodoc} @protected @mustCallSuper - void _onDisconnected(CentrifugeState$Disconnected state) { + void _onDisconnected(SpinifyState$Disconnected state) { logger.fine('Connection lost'); Spinify.observer?.onDisconnected(this, state); } @@ -129,9 +129,12 @@ abstract base class SpinifyBase implements ISpinify { @mustCallSuper Future close() async { await _transport.close(); - logger.fine('Centrifuge client closed'); + logger.fine('Spinify client closed'); Spinify.observer?.onClose(this); } + + @override + String toString() => 'Spinify{}'; } /// Mixin responsible for event receiving and distribution by controllers @@ -140,37 +143,37 @@ abstract base class SpinifyBase implements ISpinify { base mixin SpinifyEventReceiverMixin on SpinifyBase, SpinifyStateMixin { @protected @nonVirtual - final StreamController _pushController = - StreamController.broadcast(); + final StreamController _pushController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _publicationsController = - StreamController.broadcast(); + final StreamController _publicationsController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _messagesController = - StreamController.broadcast(); + final StreamController _messagesController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _joinController = - StreamController.broadcast(); + final StreamController _joinController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _leaveController = - StreamController.broadcast(); + final StreamController _leaveController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _presenceController = - StreamController.broadcast(); + final StreamController _presenceController = + StreamController.broadcast(); @override @nonVirtual - late final CentrifugePushesStream stream = CentrifugePushesStream( + late final SpinifyPushesStream stream = SpinifyPushesStream( pushes: _pushController.stream, publications: _publicationsController.stream, messages: _messagesController.stream, @@ -191,37 +194,37 @@ base mixin SpinifyEventReceiverMixin on SpinifyBase, SpinifyStateMixin { @nonVirtual @pragma('vm:prefer-inline') @pragma('dart2js:tryInline') - void _onEvent(CentrifugeEvent event) { + void _onEvent(SpinifyEvent event) { Spinify.observer?.onEvent(this, event); - if (event is! CentrifugeChannelPush) return; + if (event is! SpinifyChannelPush) return; // This is a push to a channel. _clientSubscriptionManager.onPush(event); _pushController.add(event); switch (event) { - case CentrifugePublication publication: + case SpinifyPublication publication: logger.fine( 'Publication event received for channel ${publication.channel}'); _publicationsController.add(publication); - case CentrifugeMessage message: + case SpinifyMessage message: logger.fine('Message event received for channel ${message.channel}'); _messagesController.add(message); - case CentrifugeJoin join: + case SpinifyJoin join: logger.fine('Join event received for channel ${join.channel} ' 'and user ${join.info.user}'); _presenceController.add(join); _joinController.add(join); - case CentrifugeLeave leave: + case SpinifyLeave leave: logger.fine('Leave event received for channel ${leave.channel} ' 'and user ${leave.info.user}'); _presenceController.add(leave); _leaveController.add(leave); - case CentrifugeSubscribe subscribe: + case SpinifySubscribe subscribe: _serverSubscriptionManager.subscribe(subscribe); - case CentrifugeUnsubscribe unsubscribe: + case SpinifyUnsubscribe unsubscribe: _serverSubscriptionManager.unsubscribe(unsubscribe); - case CentrifugeConnect _: + case SpinifyConnect _: break; - case CentrifugeDisconnect event: + case SpinifyDisconnect event: final code = event.code; final reconnect = code < 3500 || code >= 5000 || (code >= 4000 && code < 4500); @@ -235,7 +238,7 @@ base mixin SpinifyEventReceiverMixin on SpinifyBase, SpinifyStateMixin { disconnect().ignore(); } break; - case CentrifugeRefresh _: + case SpinifyRefresh _: logger.fine('Refresh connection token by server push'); _refreshToken(); break; @@ -246,7 +249,7 @@ base mixin SpinifyEventReceiverMixin on SpinifyBase, SpinifyStateMixin { Future close() async { await super.close(); _transport.events.removeListener(_onEvent); - for (final controller in >[ + for (final controller in >[ _pushController, _publicationsController, _messagesController, @@ -259,7 +262,7 @@ base mixin SpinifyEventReceiverMixin on SpinifyBase, SpinifyStateMixin { } } -/// Mixin responsible for centrifuge states +/// Mixin responsible for spinify states /// {@nodoc} @internal base mixin SpinifyStateMixin on SpinifyBase, SpinifyErrorsMixin { @@ -269,16 +272,16 @@ base mixin SpinifyStateMixin on SpinifyBase, SpinifyErrorsMixin { @override @nonVirtual - CentrifugeState get state => _state; + SpinifyState get state => _state; @nonVirtual @protected - late CentrifugeState _state; + late SpinifyState _state; @override @nonVirtual - late final CentrifugeStatesStream states = - CentrifugeStatesStream(_statesController.stream); + late final SpinifyStatesStream states = + SpinifyStatesStream(_statesController.stream); @override void _initSpinify() { @@ -291,20 +294,20 @@ base mixin SpinifyStateMixin on SpinifyBase, SpinifyErrorsMixin { @nonVirtual @pragma('vm:prefer-inline') @pragma('dart2js:tryInline') - void _onStateChange(CentrifugeState newState) { + void _onStateChange(SpinifyState newState) { final oldState = _state; logger.info('State changed: ${oldState.type} -> ${newState.type}'); _refreshTimer?.cancel(); _refreshTimer = null; switch (newState) { - case CentrifugeState$Disconnected state: + case SpinifyState$Disconnected state: _onDisconnected(state); - case CentrifugeState$Connecting _: + case SpinifyState$Connecting _: break; - case CentrifugeState$Connected state: + case SpinifyState$Connected state: _onConnected(state); if (state.expires == true) _setRefreshTimer(state.ttl); - case CentrifugeState$Closed _: + case SpinifyState$Closed _: break; } _statesController.add(_state = newState); @@ -313,8 +316,8 @@ base mixin SpinifyStateMixin on SpinifyBase, SpinifyErrorsMixin { @protected @nonVirtual - final StreamController _statesController = - StreamController.broadcast(); + final StreamController _statesController = + StreamController.broadcast(); /// Refresh connection token when ttl is expired. /// {@nodoc} @@ -344,7 +347,7 @@ base mixin SpinifyStateMixin on SpinifyBase, SpinifyErrorsMixin { 'Error while refreshing connection token', ); _emitError( - CentrifugeRefreshException( + SpinifyRefreshException( message: 'Error while refreshing connection token', error: error, ), @@ -366,7 +369,7 @@ base mixin SpinifyStateMixin on SpinifyBase, SpinifyErrorsMixin { base mixin SpinifyErrorsMixin on SpinifyBase { @protected @nonVirtual - void _emitError(CentrifugeException exception, StackTrace stackTrace) => + void _emitError(SpinifyException exception, StackTrace stackTrace) => Spinify.observer?.onError(exception, stackTrace); } @@ -382,16 +385,16 @@ base mixin SpinifyConnectionMixin _refreshTimer?.cancel(); _refreshTimer = null; await _transport.connect(url, _serverSubscriptionManager); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeConnectionException( + final spinifyException = SpinifyConnectionException( message: 'Error while connecting to $url', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @@ -399,17 +402,17 @@ base mixin SpinifyConnectionMixin FutureOr ready() async { try { switch (state) { - case CentrifugeState$Disconnected _: - throw const CentrifugeConnectionException( + case SpinifyState$Disconnected _: + throw const SpinifyConnectionException( message: 'Client is not connected', ); - case CentrifugeState$Closed _: - throw const CentrifugeConnectionException( + case SpinifyState$Closed _: + throw const SpinifyConnectionException( message: 'Client is permanently closed', ); - case CentrifugeState$Connected _: + case SpinifyState$Connected _: return; - case CentrifugeState$Connecting _: + case SpinifyState$Connecting _: await states.connected.first.timeout(_config.timeout); } } on TimeoutException catch (error, stackTrace) { @@ -419,22 +422,22 @@ base mixin SpinifyConnectionMixin DisconnectCode.timeout.reason, ) .ignore(); - final centrifugeException = CentrifugeConnectionException( + final spinifyException = SpinifyConnectionException( message: 'Timeout exception while waiting for connection', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); - } on CentrifugeException catch (error, stackTrace) { + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeConnectionException( + final spinifyException = SpinifyConnectionException( message: 'Client is not connected', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @@ -446,16 +449,16 @@ base mixin SpinifyConnectionMixin logger.fine('Interactively disconnecting'); try { await _transport.disconnect(code, reason); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeConnectionException( + final spinifyException = SpinifyConnectionException( message: 'Error while disconnecting', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @@ -475,13 +478,13 @@ base mixin SpinifySendMixin on SpinifyBase, SpinifyErrorsMixin { try { await ready(); await _transport.sendAsyncMessage(data); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSendException(error: error); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + final spinifyException = SpinifySendException(error: error); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -491,14 +494,14 @@ base mixin SpinifySendMixin on SpinifyBase, SpinifyErrorsMixin { @internal base mixin SpinifyClientSubscriptionMixin on SpinifyBase, SpinifyErrorsMixin { @override - CentrifugeClientSubscription newSubscription( + SpinifyClientSubscription newSubscription( String channel, [ - CentrifugeSubscriptionConfig? config, + SpinifySubscriptionConfig? config, ]) { final sub = _clientSubscriptionManager[channel] ?? _serverSubscriptionManager[channel]; if (sub != null) { - throw CentrifugeSubscriptionException( + throw SpinifySubscriptionException( channel: channel, message: 'Subscription already exists', ); @@ -507,41 +510,41 @@ base mixin SpinifyClientSubscriptionMixin on SpinifyBase, SpinifyErrorsMixin { } @override - Map get subscriptions => + Map get subscriptions => _clientSubscriptionManager.subscriptions; @override - CentrifugeClientSubscription? getSubscription(String channel) => + SpinifyClientSubscription? getSubscription(String channel) => _clientSubscriptionManager[channel]; @override Future removeSubscription( - CentrifugeClientSubscription subscription, + SpinifyClientSubscription subscription, ) async { try { await _clientSubscriptionManager.removeSubscription(subscription); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( channel: subscription.channel, message: 'Error while unsubscribing', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @override - void _onConnected(CentrifugeState$Connected state) { + void _onConnected(SpinifyState$Connected state) { super._onConnected(state); _clientSubscriptionManager.subscribeAll(); } @override - void _onDisconnected(CentrifugeState$Disconnected state) { + void _onDisconnected(SpinifyState$Disconnected state) { super._onDisconnected(state); _clientSubscriptionManager.unsubscribeAll(); } @@ -558,13 +561,13 @@ base mixin SpinifyClientSubscriptionMixin on SpinifyBase, SpinifyErrorsMixin { @internal base mixin SpinifyServerSubscriptionMixin on SpinifyBase { @override - void _onConnected(CentrifugeState$Connected state) { + void _onConnected(SpinifyState$Connected state) { super._onConnected(state); _serverSubscriptionManager.setSubscribedAll(); } @override - void _onDisconnected(CentrifugeState$Disconnected state) { + void _onDisconnected(SpinifyState$Disconnected state) { super._onDisconnected(state); _serverSubscriptionManager.setSubscribingAll(); } @@ -586,16 +589,16 @@ base mixin SpinifyPublicationsMixin try { await ready(); await _transport.publish(channel, data); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSendException( + final spinifyException = SpinifySendException( message: 'Error while publishing to channel $channel', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -604,38 +607,38 @@ base mixin SpinifyPublicationsMixin /// {@nodoc} base mixin SpinifyPresenceMixin on SpinifyBase, SpinifyErrorsMixin { @override - Future presence(String channel) async { + Future presence(String channel) async { try { await ready(); return await _transport.presence(channel); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeFetchException( + final spinifyException = SpinifyFetchException( message: 'Error while fetching presence for channel $channel', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @override - Future presenceStats(String channel) async { + Future presenceStats(String channel) async { try { await ready(); return await _transport.presenceStats(channel); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeFetchException( + final spinifyException = SpinifyFetchException( message: 'Error while fetching presence for channel $channel', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -644,10 +647,10 @@ base mixin SpinifyPresenceMixin on SpinifyBase, SpinifyErrorsMixin { /// {@nodoc} base mixin SpinifyHistoryMixin on SpinifyBase, SpinifyErrorsMixin { @override - Future history( + Future history( String channel, { int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }) async { try { @@ -658,16 +661,16 @@ base mixin SpinifyHistoryMixin on SpinifyBase, SpinifyErrorsMixin { since: since, reverse: reverse, ); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeFetchException( + final spinifyException = SpinifyFetchException( message: 'Error while fetching history for channel $channel', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -680,16 +683,16 @@ base mixin SpinifyRPCMixin on SpinifyBase, SpinifyErrorsMixin { try { await ready(); return await _transport.rpc(method, data); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeFetchException( + final spinifyException = SpinifyFetchException( message: 'Error while remote procedure call for method $method', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -700,7 +703,7 @@ base mixin SpinifyRPCMixin on SpinifyBase, SpinifyErrorsMixin { @internal base mixin SpinifyQueueMixin on SpinifyBase { /// {@nodoc} - final CentrifugeEventQueue _eventQueue = CentrifugeEventQueue(); + final SpinifyEventQueue _eventQueue = SpinifyEventQueue(); @override Future connect(String url) => @@ -714,27 +717,27 @@ base mixin SpinifyQueueMixin on SpinifyBase { FutureOr ready() => _eventQueue.push('ready', super.ready); @override - Future presence(String channel) => - _eventQueue.push( + Future presence(String channel) => + _eventQueue.push( 'presence', () => super.presence(channel), ); @override - Future presenceStats(String channel) => - _eventQueue.push( + Future presenceStats(String channel) => + _eventQueue.push( 'presenceStats', () => super.presenceStats(channel), ); @override - Future history( + Future history( String channel, { int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }) => - _eventQueue.push( + _eventQueue.push( 'history', () => super.history( channel, diff --git a/lib/src/client/centrifuge_interface.dart b/lib/src/client/spinify_interface.dart similarity index 74% rename from lib/src/client/centrifuge_interface.dart rename to lib/src/client/spinify_interface.dart index 9451fa0..56e40ba 100644 --- a/lib/src/client/centrifuge_interface.dart +++ b/lib/src/client/spinify_interface.dart @@ -12,7 +12,7 @@ import 'package:spinify/src/model/stream_position.dart'; import 'package:spinify/src/subscription/subscription.dart'; import 'package:spinify/src/subscription/subscription_config.dart'; -/// Centrifuge client interface. +/// Spinify client interface. abstract interface class ISpinify implements ISpinifyStateOwner, @@ -43,87 +43,87 @@ abstract interface class ISpinify Future close(); } -/// Centrifuge client state owner interface. +/// Spinify client state owner interface. abstract interface class ISpinifyStateOwner { /// State of client. - CentrifugeState get state; + SpinifyState get state; /// Stream of client states. - abstract final CentrifugeStatesStream states; + abstract final SpinifyStatesStream states; } -/// Centrifuge send publication interface. +/// Spinify send publication interface. abstract interface class ISpinifyPublicationSender { /// Publish data to specific subscription channel Future publish(String channel, List data); } -/// Centrifuge send asynchronous message interface. +/// Spinify send asynchronous message interface. abstract interface class ISpinifyAsyncMessageSender { /// Send asynchronous message to a server. This method makes sense - /// only when using Centrifuge library for Go on a server side. In Centrifuge + /// only when using Centrifuge library for Go on a server side. In Centrifugo /// asynchronous message handler does not exist. Future send(List data); } -/// Centrifuge event receiver interface. +/// Spinify event receiver interface. abstract interface class ISpinifyEventReceiver { /// Stream of received pushes from Centrifugo server for a channel. - abstract final CentrifugePushesStream stream; + abstract final SpinifyPushesStream stream; } -/// Centrifuge client subscriptions manager interface. +/// Spinify client subscriptions manager interface. abstract interface class ISpinifyClientSubscriptionsManager { /// Create new client-side subscription. /// `newSubscription(channel, config)` allocates a new Subscription /// in the registry or throws an exception if the Subscription /// is already there. We will discuss common Subscription options below. - CentrifugeClientSubscription newSubscription( + SpinifyClientSubscription newSubscription( String channel, [ - CentrifugeSubscriptionConfig? config, + SpinifySubscriptionConfig? config, ]); /// Get subscription to the channel /// from internal registry or null if not found. /// - /// You need to call [CentrifugeClientSubscription.subscribe] + /// You need to call [SpinifyClientSubscription.subscribe] /// to start receiving events /// in the channel. - CentrifugeClientSubscription? getSubscription(String channel); + SpinifyClientSubscription? getSubscription(String channel); /// Remove the [Subscription] from internal registry - /// and unsubscribe from [CentrifugeClientSubscription.channel]. - Future removeSubscription(CentrifugeClientSubscription subscription); + /// and unsubscribe from [SpinifyClientSubscription.channel]. + Future removeSubscription(SpinifyClientSubscription subscription); /// Get map wirth all registered client-side subscriptions. /// Returns all registered subscriptions, /// so you can iterate over all and do some action if required /// (for example, you want to unsubscribe/remove all subscriptions). - Map get subscriptions; + Map get subscriptions; } -/// Centrifuge presence owner interface. +/// Spinify presence owner interface. abstract interface class ISpinifyPresenceOwner { /// Fetch presence information inside a channel. - Future presence(String channel); + Future presence(String channel); /// Fetch presence stats information inside a channel. - Future presenceStats(String channel); + Future presenceStats(String channel); } -/// Centrifuge history owner interface. +/// Spinify history owner interface. abstract interface class ISpinifyHistoryOwner { /// Fetch publication history inside a channel. /// Only for channels where history is enabled. - Future history( + Future history( String channel, { int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }); } -/// Centrifuge remote procedure call interface. +/// Spinify remote procedure call interface. abstract interface class ISpinifyRemoteProcedureCall { /// Send arbitrary RPC and wait for response. Future> rpc(String method, List data); diff --git a/lib/src/client/state.dart b/lib/src/client/state.dart index 8999883..11f9ed7 100644 --- a/lib/src/client/state.dart +++ b/lib/src/client/state.dart @@ -3,7 +3,7 @@ import 'dart:convert'; import 'package:meta/meta.dart'; /// {@template state} -/// Centrifuge client connection states +/// Spinify client connection states /// /// Client connection has 4 states: /// @@ -34,26 +34,26 @@ import 'package:meta/meta.dart'; /// {@category Client} /// {@category Entity} @immutable -sealed class CentrifugeState extends _$CentrifugeStateBase { +sealed class SpinifyState extends _$SpinifyStateBase { /// {@macro state} - const CentrifugeState(super.timestamp); + const SpinifyState(super.timestamp); /// Disconnected state /// {@macro state} - factory CentrifugeState.disconnected({ + factory SpinifyState.disconnected({ DateTime? timestamp, int? closeCode, String? closeReason, - }) = CentrifugeState$Disconnected; + }) = SpinifyState$Disconnected; /// Connecting /// {@macro state} - factory CentrifugeState.connecting( - {required String url, DateTime? timestamp}) = CentrifugeState$Connecting; + factory SpinifyState.connecting({required String url, DateTime? timestamp}) = + SpinifyState$Connecting; /// Connected /// {@macro state} - factory CentrifugeState.connected({ + factory SpinifyState.connected({ required String url, DateTime? timestamp, String? client, @@ -65,21 +65,20 @@ sealed class CentrifugeState extends _$CentrifugeStateBase { String? session, String? node, List? data, - }) = CentrifugeState$Connected; + }) = SpinifyState$Connected; /// Permanently closed /// {@macro state} - factory CentrifugeState.closed({DateTime? timestamp}) = - CentrifugeState$Closed; + factory SpinifyState.closed({DateTime? timestamp}) = SpinifyState$Closed; /// Restore state from JSON /// {@macro state} - factory CentrifugeState.fromJson(Map json) => switch (( + factory SpinifyState.fromJson(Map json) => switch (( json['type']?.toString().trim().toLowerCase(), json['timestamp'] ?? DateTime.now().microsecondsSinceEpoch, json['url'], )) { - ('disconnected', int timestamp, _) => CentrifugeState.disconnected( + ('disconnected', int timestamp, _) => SpinifyState.disconnected( timestamp: DateTime.fromMicrosecondsSinceEpoch(timestamp), closeCode: switch (json['closeCode']) { int closeCode => closeCode, @@ -90,11 +89,11 @@ sealed class CentrifugeState extends _$CentrifugeStateBase { _ => null, }, ), - ('connecting', int timestamp, String url) => CentrifugeState.connecting( + ('connecting', int timestamp, String url) => SpinifyState.connecting( url: url, timestamp: DateTime.fromMicrosecondsSinceEpoch(timestamp), ), - ('connected', int timestamp, String url) => CentrifugeState.connected( + ('connected', int timestamp, String url) => SpinifyState.connected( url: url, timestamp: DateTime.fromMicrosecondsSinceEpoch(timestamp), client: json['client']?.toString(), @@ -122,7 +121,7 @@ sealed class CentrifugeState extends _$CentrifugeStateBase { _ => null, }, ), - ('closed', int timestamp, _) => CentrifugeState.closed( + ('closed', int timestamp, _) => SpinifyState.closed( timestamp: DateTime.fromMicrosecondsSinceEpoch(timestamp), ), _ => throw FormatException('Unknown state: $json'), @@ -137,12 +136,11 @@ sealed class CentrifugeState extends _$CentrifugeStateBase { /// {@macro state} /// {@category Client} /// {@category Entity} -final class CentrifugeState$Disconnected extends CentrifugeState - with _$CentrifugeState { +final class SpinifyState$Disconnected extends SpinifyState with _$SpinifyState { /// Disconnected /// /// {@macro state} - CentrifugeState$Disconnected({ + SpinifyState$Disconnected({ DateTime? timestamp, this.closeCode, this.closeReason, @@ -176,10 +174,10 @@ final class CentrifugeState$Disconnected extends CentrifugeState @override R map({ - required CentrifugeStateMatch disconnected, - required CentrifugeStateMatch connecting, - required CentrifugeStateMatch connected, - required CentrifugeStateMatch closed, + required SpinifyStateMatch disconnected, + required SpinifyStateMatch connecting, + required SpinifyStateMatch connected, + required SpinifyStateMatch closed, }) => disconnected(this); @@ -196,11 +194,11 @@ final class CentrifugeState$Disconnected extends CentrifugeState @override bool operator ==(Object other) => identical(this, other) || - (other is CentrifugeState$Disconnected && + (other is SpinifyState$Disconnected && other.timestamp.isAtSameMomentAs(timestamp)); @override - String toString() => 'CentrifugeState.disconnected{$timestamp}'; + String toString() => 'SpinifyState.disconnected{$timestamp}'; } /// Connecting @@ -208,12 +206,11 @@ final class CentrifugeState$Disconnected extends CentrifugeState /// {@macro state} /// {@category Client} /// {@category Entity} -final class CentrifugeState$Connecting extends CentrifugeState - with _$CentrifugeState { +final class SpinifyState$Connecting extends SpinifyState with _$SpinifyState { /// Connecting /// /// {@macro state} - CentrifugeState$Connecting({required this.url, DateTime? timestamp}) + SpinifyState$Connecting({required this.url, DateTime? timestamp}) : super(timestamp ?? DateTime.now()); @override @@ -236,10 +233,10 @@ final class CentrifugeState$Connecting extends CentrifugeState @override R map({ - required CentrifugeStateMatch disconnected, - required CentrifugeStateMatch connecting, - required CentrifugeStateMatch connected, - required CentrifugeStateMatch closed, + required SpinifyStateMatch disconnected, + required SpinifyStateMatch connecting, + required SpinifyStateMatch connected, + required SpinifyStateMatch closed, }) => connecting(this); @@ -249,11 +246,11 @@ final class CentrifugeState$Connecting extends CentrifugeState @override bool operator ==(Object other) => identical(this, other) || - (other is CentrifugeState$Connecting && + (other is SpinifyState$Connecting && other.timestamp.isAtSameMomentAs(timestamp)); @override - String toString() => 'CentrifugeState.connecting{$timestamp}'; + String toString() => 'SpinifyState.connecting{$timestamp}'; } /// Connected @@ -261,12 +258,11 @@ final class CentrifugeState$Connecting extends CentrifugeState /// {@macro state} /// {@category Client} /// {@category Entity} -final class CentrifugeState$Connected extends CentrifugeState - with _$CentrifugeState { +final class SpinifyState$Connected extends SpinifyState with _$SpinifyState { /// Connected /// /// {@macro state} - CentrifugeState$Connected({ + SpinifyState$Connected({ required this.url, DateTime? timestamp, this.client, @@ -330,10 +326,10 @@ final class CentrifugeState$Connected extends CentrifugeState @override R map({ - required CentrifugeStateMatch disconnected, - required CentrifugeStateMatch connecting, - required CentrifugeStateMatch connected, - required CentrifugeStateMatch closed, + required SpinifyStateMatch disconnected, + required SpinifyStateMatch connecting, + required SpinifyStateMatch connected, + required SpinifyStateMatch closed, }) => connected(this); @@ -357,11 +353,11 @@ final class CentrifugeState$Connected extends CentrifugeState @override bool operator ==(Object other) => identical(this, other) || - (other is CentrifugeState$Connected && + (other is SpinifyState$Connected && other.timestamp.isAtSameMomentAs(timestamp)); @override - String toString() => 'CentrifugeState.connected{$timestamp}'; + String toString() => 'SpinifyState.connected{$timestamp}'; } /// Permanently closed @@ -369,12 +365,11 @@ final class CentrifugeState$Connected extends CentrifugeState /// {@macro state} /// {@category Client} /// {@category Entity} -final class CentrifugeState$Closed extends CentrifugeState - with _$CentrifugeState { +final class SpinifyState$Closed extends SpinifyState with _$SpinifyState { /// Permanently closed /// /// {@macro state} - CentrifugeState$Closed({DateTime? timestamp}) + SpinifyState$Closed({DateTime? timestamp}) : super(timestamp ?? DateTime.now()); @override @@ -397,10 +392,10 @@ final class CentrifugeState$Closed extends CentrifugeState @override R map({ - required CentrifugeStateMatch disconnected, - required CentrifugeStateMatch connecting, - required CentrifugeStateMatch connected, - required CentrifugeStateMatch closed, + required SpinifyStateMatch disconnected, + required SpinifyStateMatch connecting, + required SpinifyStateMatch connected, + required SpinifyStateMatch closed, }) => closed(this); @@ -410,25 +405,24 @@ final class CentrifugeState$Closed extends CentrifugeState @override bool operator ==(Object other) => identical(this, other) || - (other is CentrifugeState$Closed && + (other is SpinifyState$Closed && other.timestamp.isAtSameMomentAs(timestamp)); @override - String toString() => 'CentrifugeState.closed{$timestamp}'; + String toString() => 'SpinifyState.closed{$timestamp}'; } /// {@nodoc} -base mixin _$CentrifugeState on CentrifugeState {} +base mixin _$SpinifyState on SpinifyState {} -/// Pattern matching for [CentrifugeState]. -typedef CentrifugeStateMatch = R Function( - S state); +/// Pattern matching for [SpinifyState]. +typedef SpinifyStateMatch = R Function(S state); /// {@nodoc} @immutable -abstract base class _$CentrifugeStateBase { +abstract base class _$SpinifyStateBase { /// {@nodoc} - const _$CentrifugeStateBase(this.timestamp); + const _$SpinifyStateBase(this.timestamp); /// Represents the current state type. abstract final String type; @@ -451,21 +445,21 @@ abstract base class _$CentrifugeStateBase { /// Timestamp of state change. final DateTime timestamp; - /// Pattern matching for [CentrifugeState]. + /// Pattern matching for [SpinifyState]. R map({ - required CentrifugeStateMatch disconnected, - required CentrifugeStateMatch connecting, - required CentrifugeStateMatch connected, - required CentrifugeStateMatch closed, + required SpinifyStateMatch disconnected, + required SpinifyStateMatch connecting, + required SpinifyStateMatch connected, + required SpinifyStateMatch closed, }); - /// Pattern matching for [CentrifugeState]. + /// Pattern matching for [SpinifyState]. R maybeMap({ required R Function() orElse, - CentrifugeStateMatch? disconnected, - CentrifugeStateMatch? connecting, - CentrifugeStateMatch? connected, - CentrifugeStateMatch? closed, + SpinifyStateMatch? disconnected, + SpinifyStateMatch? connecting, + SpinifyStateMatch? connected, + SpinifyStateMatch? closed, }) => map( disconnected: disconnected ?? (_) => orElse(), @@ -474,12 +468,12 @@ abstract base class _$CentrifugeStateBase { closed: closed ?? (_) => orElse(), ); - /// Pattern matching for [CentrifugeState]. + /// Pattern matching for [SpinifyState]. R? mapOrNull({ - CentrifugeStateMatch? disconnected, - CentrifugeStateMatch? connecting, - CentrifugeStateMatch? connected, - CentrifugeStateMatch? closed, + SpinifyStateMatch? disconnected, + SpinifyStateMatch? connecting, + SpinifyStateMatch? connected, + SpinifyStateMatch? closed, }) => map( disconnected: disconnected ?? (_) => null, diff --git a/lib/src/client/states_stream.dart b/lib/src/client/states_stream.dart index c918449..c4ba0e2 100644 --- a/lib/src/client/states_stream.dart +++ b/lib/src/client/states_stream.dart @@ -2,32 +2,32 @@ import 'dart:async'; import 'package:spinify/src/client/state.dart'; -/// Stream of Centrifuge's [CentrifugeState] changes. +/// Stream of Spinify's [SpinifyState] changes. /// {@category Client} /// {@category Entity} -final class CentrifugeStatesStream extends StreamView { - /// Stream of Centrifuge's [CentrifugeState] changes. - CentrifugeStatesStream(super.stream); +final class SpinifyStatesStream extends StreamView { + /// Stream of Spinify's [SpinifyState] changes. + SpinifyStatesStream(super.stream); /// Connection has not yet been established, but the WebSocket is trying. - late final Stream disconnected = - whereType(); + late final Stream disconnected = + whereType(); /// Disconnected state - late final Stream connecting = - whereType(); + late final Stream connecting = + whereType(); /// Connected - late final Stream connected = - whereType(); + late final Stream connected = + whereType(); /// Permanently closed - late final Stream closed = - whereType(); + late final Stream closed = + whereType(); - /// Filtered stream of data of [CentrifugeState]. - Stream whereType() => - transform(StreamTransformer.fromHandlers( + /// Filtered stream of data of [SpinifyState]. + Stream whereType() => + transform(StreamTransformer.fromHandlers( handleData: (data, sink) => switch (data) { T valid => sink.add(valid), _ => null, diff --git a/lib/src/model/channel_presence.dart b/lib/src/model/channel_presence.dart index 88e91c5..361d8bc 100644 --- a/lib/src/model/channel_presence.dart +++ b/lib/src/model/channel_presence.dart @@ -10,16 +10,16 @@ import 'package:spinify/src/model/client_info.dart'; /// {@subCategory Channel} /// {@subCategory Presence} @immutable -sealed class CentrifugeChannelPresence extends CentrifugeChannelPush { +sealed class SpinifyChannelPresence extends SpinifyChannelPush { /// {@macro channel_presence} - const CentrifugeChannelPresence({ + const SpinifyChannelPresence({ required super.timestamp, required super.channel, required this.info, }); /// Client info - final CentrifugeClientInfo info; + final SpinifyClientInfo info; /// Whether this is a join event abstract final bool isJoin; @@ -29,9 +29,9 @@ sealed class CentrifugeChannelPresence extends CentrifugeChannelPush { } /// {@macro channel_presence} -final class CentrifugeJoin extends CentrifugeChannelPresence { +final class SpinifyJoin extends SpinifyChannelPresence { /// {@macro channel_presence} - const CentrifugeJoin({ + const SpinifyJoin({ required super.timestamp, required super.channel, required super.info, @@ -48,9 +48,9 @@ final class CentrifugeJoin extends CentrifugeChannelPresence { } /// {@macro channel_presence} -final class CentrifugeLeave extends CentrifugeChannelPresence { +final class SpinifyLeave extends SpinifyChannelPresence { /// {@macro channel_presence} - const CentrifugeLeave({ + const SpinifyLeave({ required super.timestamp, required super.channel, required super.info, diff --git a/lib/src/model/channel_push.dart b/lib/src/model/channel_push.dart index 8292edf..a6ec1ce 100644 --- a/lib/src/model/channel_push.dart +++ b/lib/src/model/channel_push.dart @@ -1,12 +1,12 @@ import 'package:meta/meta.dart'; import 'package:spinify/src/model/event.dart'; -/// {@template centrifuge_channel_push} +/// {@template spinify_channel_push} /// Base class for all channel push events. /// {@endtemplate} -abstract base class CentrifugeChannelPush extends CentrifugeEvent { - /// {@template centrifuge_channel_push} - const CentrifugeChannelPush({ +abstract base class SpinifyChannelPush extends SpinifyEvent { + /// {@template spinify_channel_push} + const SpinifyChannelPush({ required super.timestamp, required this.channel, }); diff --git a/lib/src/model/client_info.dart b/lib/src/model/client_info.dart index d3f8d9c..d2e683c 100644 --- a/lib/src/model/client_info.dart +++ b/lib/src/model/client_info.dart @@ -5,9 +5,9 @@ import 'package:meta/meta.dart'; /// {@endtemplate} /// {@category Entity} @immutable -final class CentrifugeClientInfo { +final class SpinifyClientInfo { /// {@macro client_info} - const CentrifugeClientInfo({ + const SpinifyClientInfo({ required this.user, required this.client, required this.connectionInfo, @@ -37,14 +37,14 @@ final class CentrifugeClientInfo { @override bool operator ==(Object other) => identical(this, other) || - other is CentrifugeClientInfo && + other is SpinifyClientInfo && user == other.client && client == other.client && connectionInfo == other.connectionInfo && channelInfo == other.channelInfo; @override - String toString() => 'CentrifugeClientInfo{' + String toString() => 'SpinifyClientInfo{' 'user: $user, ' 'client: $client, ' 'connectionInfo: ${connectionInfo == null ? 'null' : 'bytes'}, ' diff --git a/lib/src/model/connect.dart b/lib/src/model/connect.dart index a0fe970..ca3a96d 100644 --- a/lib/src/model/connect.dart +++ b/lib/src/model/connect.dart @@ -3,9 +3,9 @@ import 'package:spinify/src/model/channel_push.dart'; /// {@template connect} /// Connect push from Centrifugo server. /// {@endtemplate} -final class CentrifugeConnect extends CentrifugeChannelPush { +final class SpinifyConnect extends SpinifyChannelPush { /// {@macro connect} - const CentrifugeConnect({ + const SpinifyConnect({ required super.timestamp, required super.channel, required this.client, diff --git a/lib/src/model/disconnect.dart b/lib/src/model/disconnect.dart index 50cb490..f9133cb 100644 --- a/lib/src/model/disconnect.dart +++ b/lib/src/model/disconnect.dart @@ -3,9 +3,9 @@ import 'package:spinify/src/model/channel_push.dart'; /// {@template disconnect} /// Disconnect push from Centrifugo server. /// {@endtemplate} -final class CentrifugeDisconnect extends CentrifugeChannelPush { +final class SpinifyDisconnect extends SpinifyChannelPush { /// {@macro disconnect} - const CentrifugeDisconnect({ + const SpinifyDisconnect({ required super.timestamp, required super.channel, required this.code, diff --git a/lib/src/model/event.dart b/lib/src/model/event.dart index 318d8a3..65897ae 100644 --- a/lib/src/model/event.dart +++ b/lib/src/model/event.dart @@ -1,12 +1,12 @@ import 'package:meta/meta.dart'; -/// {@template centrifuge_event} +/// {@template spinify_event} /// Base class for all channel events. /// {@endtemplate} @immutable -abstract base class CentrifugeEvent { - /// {@template centrifuge_event} - const CentrifugeEvent({ +abstract base class SpinifyEvent { + /// {@template spinify_event} + const SpinifyEvent({ required this.timestamp, }); diff --git a/lib/src/model/exception.dart b/lib/src/model/exception.dart index df65f7c..faba366 100644 --- a/lib/src/model/exception.dart +++ b/lib/src/model/exception.dart @@ -1,13 +1,13 @@ import 'package:meta/meta.dart'; /// {@template exception} -/// Centrifuge exception. +/// Spinify exception. /// {@endtemplate} /// {@category Exception} @immutable -sealed class CentrifugeException implements Exception { +sealed class SpinifyException implements Exception { /// {@macro exception} - const CentrifugeException( + const SpinifyException( this.code, this.message, [ this.error, @@ -34,11 +34,11 @@ sealed class CentrifugeException implements Exception { /// {@macro exception} /// {@category Exception} -final class CentrifugeConnectionException extends CentrifugeException { +final class SpinifyConnectionException extends SpinifyException { /// {@macro exception} - const CentrifugeConnectionException({String? message, Object? error}) + const SpinifyConnectionException({String? message, Object? error}) : super( - 'centrifuge_connection_exception', + 'spinify_connection_exception', message ?? 'Connection problem', error, ); @@ -46,14 +46,14 @@ final class CentrifugeConnectionException extends CentrifugeException { /// {@macro exception} /// {@category Exception} -final class CentrifugeReplyException extends CentrifugeException { +final class SpinifyReplyException extends SpinifyException { /// {@macro exception} - const CentrifugeReplyException({ + const SpinifyReplyException({ required this.replyCode, required String replyMessage, required this.temporary, }) : super( - 'centrifuge_reply_exception', + 'spinify_reply_exception', replyMessage, ); @@ -66,11 +66,11 @@ final class CentrifugeReplyException extends CentrifugeException { /// {@macro exception} /// {@category Exception} -final class CentrifugePingException extends CentrifugeException { +final class SpinifyPingException extends SpinifyException { /// {@macro exception} - const CentrifugePingException([Object? error]) + const SpinifyPingException([Object? error]) : super( - 'centrifuge_ping_exception', + 'spinify_ping_exception', 'Ping error', error, ); @@ -78,14 +78,14 @@ final class CentrifugePingException extends CentrifugeException { /// {@macro exception} /// {@category Exception} -final class CentrifugeSubscriptionException extends CentrifugeException { +final class SpinifySubscriptionException extends SpinifyException { /// {@macro exception} - const CentrifugeSubscriptionException({ + const SpinifySubscriptionException({ required this.channel, required String message, Object? error, }) : super( - 'centrifuge_subscription_exception', + 'spinify_subscription_exception', message, error, ); @@ -96,13 +96,13 @@ final class CentrifugeSubscriptionException extends CentrifugeException { /// {@macro exception} /// {@category Exception} -final class CentrifugeSendException extends CentrifugeException { +final class SpinifySendException extends SpinifyException { /// {@macro exception} - const CentrifugeSendException({ + const SpinifySendException({ String? message, Object? error, }) : super( - 'centrifuge_send_exception', + 'spinify_send_exception', message ?? 'Failed to send message', error, ); @@ -110,13 +110,13 @@ final class CentrifugeSendException extends CentrifugeException { /// {@macro exception} /// {@category Exception} -final class CentrifugeFetchException extends CentrifugeException { +final class SpinifyFetchException extends SpinifyException { /// {@macro exception} - const CentrifugeFetchException({ + const SpinifyFetchException({ String? message, Object? error, }) : super( - 'centrifuge_fetch_exception', + 'spinify_fetch_exception', message ?? 'Failed to fetch data', error, ); @@ -124,13 +124,13 @@ final class CentrifugeFetchException extends CentrifugeException { /// {@macro exception} /// {@category Exception} -final class CentrifugeRefreshException extends CentrifugeException { +final class SpinifyRefreshException extends SpinifyException { /// {@macro exception} - const CentrifugeRefreshException({ + const SpinifyRefreshException({ String? message, Object? error, }) : super( - 'centrifuge_refresh_exception', + 'spinify_refresh_exception', message ?? 'Error while refreshing connection token', error, ); diff --git a/lib/src/model/history.dart b/lib/src/model/history.dart index cfe508e..b091c1e 100644 --- a/lib/src/model/history.dart +++ b/lib/src/model/history.dart @@ -7,16 +7,16 @@ import 'package:spinify/src/model/stream_position.dart'; /// {@endtemplate} /// {@category Entity} @immutable -final class CentrifugeHistory { +final class SpinifyHistory { /// {@macro history} - const CentrifugeHistory({ + const SpinifyHistory({ required this.publications, required this.since, }); /// Publications - final List publications; + final List publications; /// Offset and epoch of last publication in publications list - final CentrifugeStreamPosition since; + final SpinifyStreamPosition since; } diff --git a/lib/src/model/jwt.dart b/lib/src/model/jwt.dart index 515c66a..7980684 100644 --- a/lib/src/model/jwt.dart +++ b/lib/src/model/jwt.dart @@ -20,11 +20,11 @@ import 'package:meta/meta.dart'; /// {@endtemplate} /// {@category Entity} @immutable -sealed class CentrifugeJWT { +sealed class SpinifyJWT { /// {@macro jwt} /// /// Creates JWT from [secret] (with HMAC-SHA256 algorithm) - const factory CentrifugeJWT({ + const factory SpinifyJWT({ required String sub, int? exp, int? iat, @@ -37,17 +37,17 @@ sealed class CentrifugeJWT { Map? subs, Map? meta, int? expireAt, - }) = _CentrifugeJWTImpl; + }) = _SpinifyJWTImpl; /// {@macro jwt} /// /// Parses JWT, if [secret] is provided /// then checks signature by HMAC-SHA256 algorithm. - factory CentrifugeJWT.decode(String jwt, [String? secret]) = - _CentrifugeJWTImpl.decode; + factory SpinifyJWT.decode(String jwt, [String? secret]) = + _SpinifyJWTImpl.decode; /// {@nodoc} - const CentrifugeJWT._(); + const SpinifyJWT._(); /// This is a standard JWT claim which must contain /// an ID of the current application user (as string). @@ -233,8 +233,8 @@ sealed class CentrifugeJWT { String encode(String secret); } -final class _CentrifugeJWTImpl extends CentrifugeJWT { - const _CentrifugeJWTImpl({ +final class _SpinifyJWTImpl extends SpinifyJWT { + const _SpinifyJWTImpl({ required this.sub, this.exp, this.iat, @@ -249,7 +249,7 @@ final class _CentrifugeJWTImpl extends CentrifugeJWT { this.expireAt, }) : super._(); - factory _CentrifugeJWTImpl.decode(String jwt, [String? secret]) { + factory _SpinifyJWTImpl.decode(String jwt, [String? secret]) { // Разделение токена на составляющие части var parts = jwt.split('.'); if (parts.length != 3) { @@ -286,7 +286,7 @@ final class _CentrifugeJWTImpl extends CentrifugeJWT { const FormatException('Can\'t decode token payload'), stackTrace); } try { - return _CentrifugeJWTImpl( + return _SpinifyJWTImpl( sub: payload['sub'] as String, exp: payload['exp'] as int?, iat: payload['iat'] as int?, @@ -392,7 +392,7 @@ final class _CentrifugeJWTImpl extends CentrifugeJWT { } @override - String toString() => 'CentrifugoJWT{sub: $sub}'; + String toString() => 'SpinifyJWT{sub: $sub}'; } /// A converter that converts Base64-encoded strings diff --git a/lib/src/model/message.dart b/lib/src/model/message.dart index 82e181a..535eab5 100644 --- a/lib/src/model/message.dart +++ b/lib/src/model/message.dart @@ -3,9 +3,9 @@ import 'package:spinify/src/model/channel_push.dart'; /// {@template message} /// Message push from Centrifugo server. /// {@endtemplate} -final class CentrifugeMessage extends CentrifugeChannelPush { +final class SpinifyMessage extends SpinifyChannelPush { /// {@macro message} - const CentrifugeMessage({ + const SpinifyMessage({ required super.timestamp, required super.channel, required this.data, diff --git a/lib/src/model/presence.dart b/lib/src/model/presence.dart index e505d46..cecfc53 100644 --- a/lib/src/model/presence.dart +++ b/lib/src/model/presence.dart @@ -6,9 +6,9 @@ import 'package:spinify/src/model/client_info.dart'; /// {@endtemplate} /// {@category Entity} @immutable -final class CentrifugePresence { +final class SpinifyPresence { /// {@macro presence} - const CentrifugePresence({ + const SpinifyPresence({ required this.channel, required this.clients, }); @@ -17,5 +17,5 @@ final class CentrifugePresence { final String channel; /// Publications - final Map clients; + final Map clients; } diff --git a/lib/src/model/presence_stats.dart b/lib/src/model/presence_stats.dart index 0ca5d6b..fa1ed42 100644 --- a/lib/src/model/presence_stats.dart +++ b/lib/src/model/presence_stats.dart @@ -5,9 +5,9 @@ import 'package:meta/meta.dart'; /// {@endtemplate} /// {@category Entity} @immutable -final class CentrifugePresenceStats { +final class SpinifyPresenceStats { /// {@macro presence_stats} - const CentrifugePresenceStats({ + const SpinifyPresenceStats({ required this.channel, required this.clients, required this.users, diff --git a/lib/src/model/publication.dart b/lib/src/model/publication.dart index 778e9b2..1e609b9 100644 --- a/lib/src/model/publication.dart +++ b/lib/src/model/publication.dart @@ -8,9 +8,9 @@ import 'package:spinify/src/model/client_info.dart'; /// {@endtemplate} /// {@category Entity} @immutable -final class CentrifugePublication extends CentrifugeChannelPush { +final class SpinifyPublication extends SpinifyChannelPush { /// {@macro publication} - const CentrifugePublication({ + const SpinifyPublication({ required super.timestamp, required super.channel, required this.data, @@ -30,7 +30,7 @@ final class CentrifugePublication extends CentrifugeChannelPush { /// Optional information about client connection who published this /// (only exists if publication comes from client-side publish() API). - final CentrifugeClientInfo? info; + final SpinifyClientInfo? info; /// Optional tags, this is a map with string keys and string values final Map? tags; diff --git a/lib/src/model/pushes_stream.dart b/lib/src/model/pushes_stream.dart index a2cf479..cf4bf08 100644 --- a/lib/src/model/pushes_stream.dart +++ b/lib/src/model/pushes_stream.dart @@ -11,10 +11,10 @@ import 'package:spinify/src/model/publication.dart'; /// {@subCategory Pushes} /// {@subCategory Events} /// {@subCategory Channel} -final class CentrifugePushesStream extends StreamView { +final class SpinifyPushesStream extends StreamView { /// Stream of received events. - CentrifugePushesStream({ - required Stream pushes, + SpinifyPushesStream({ + required Stream pushes, required this.publications, required this.messages, required this.presenceEvents, @@ -23,23 +23,23 @@ final class CentrifugePushesStream extends StreamView { }) : super(pushes); /// Publications stream. - final Stream publications; + final Stream publications; /// Messages stream. - final Stream messages; + final Stream messages; /// Stream of presence (join & leave) events. - final Stream presenceEvents; + final Stream presenceEvents; /// Join events - final Stream joinEvents; + final Stream joinEvents; /// Leave events - final Stream leaveEvents; + final Stream leaveEvents; - /// Filtered stream of data of [CentrifugeEvent]. - Stream whereType() => - transform(StreamTransformer.fromHandlers( + /// Filtered stream of data of [SpinifyEvent]. + Stream whereType() => + transform(StreamTransformer.fromHandlers( handleData: (data, sink) => switch (data) { T valid => sink.add(valid), _ => null, diff --git a/lib/src/model/refresh.dart b/lib/src/model/refresh.dart index 117be07..2310b40 100644 --- a/lib/src/model/refresh.dart +++ b/lib/src/model/refresh.dart @@ -4,9 +4,9 @@ import 'package:spinify/src/model/channel_push.dart'; /// {@template refresh} /// Refresh push from Centrifugo server. /// {@endtemplate} -final class CentrifugeRefresh extends CentrifugeChannelPush { +final class SpinifyRefresh extends SpinifyChannelPush { /// {@macro refresh} - const CentrifugeRefresh({ + const SpinifyRefresh({ required super.timestamp, required super.channel, required this.expires, @@ -26,9 +26,9 @@ final class CentrifugeRefresh extends CentrifugeChannelPush { /// {@nodoc} @internal @immutable -final class CentrifugeRefreshResult { +final class SpinifyRefreshResult { /// {@nodoc} - const CentrifugeRefreshResult({ + const SpinifyRefreshResult({ required this.expires, this.client, this.version, @@ -51,9 +51,9 @@ final class CentrifugeRefreshResult { /// {@nodoc} @internal @immutable -final class CentrifugeSubRefreshResult { +final class SpinifySubRefreshResult { /// {@nodoc} - const CentrifugeSubRefreshResult({ + const SpinifySubRefreshResult({ required this.expires, this.ttl, }); diff --git a/lib/src/model/stream_position.dart b/lib/src/model/stream_position.dart index 18bca72..f118247 100644 --- a/lib/src/model/stream_position.dart +++ b/lib/src/model/stream_position.dart @@ -1,4 +1,4 @@ import 'package:fixnum/fixnum.dart' as fixnum; /// Stream position. -typedef CentrifugeStreamPosition = ({fixnum.Int64 offset, String epoch}); +typedef SpinifyStreamPosition = ({fixnum.Int64 offset, String epoch}); diff --git a/lib/src/model/subscribe.dart b/lib/src/model/subscribe.dart index 437e913..ddc5362 100644 --- a/lib/src/model/subscribe.dart +++ b/lib/src/model/subscribe.dart @@ -4,9 +4,9 @@ import 'package:spinify/src/model/stream_position.dart'; /// {@template subscribe} /// Subscribe push from Centrifugo server. /// {@endtemplate} -final class CentrifugeSubscribe extends CentrifugeChannelPush { +final class SpinifySubscribe extends SpinifyChannelPush { /// {@macro subscribe} - const CentrifugeSubscribe({ + const SpinifySubscribe({ required super.timestamp, required super.channel, required this.positioned, @@ -28,5 +28,5 @@ final class CentrifugeSubscribe extends CentrifugeChannelPush { final List data; /// Stream position. - final CentrifugeStreamPosition? streamPosition; + final SpinifyStreamPosition? streamPosition; } diff --git a/lib/src/model/unsubscribe.dart b/lib/src/model/unsubscribe.dart index 1db54e8..620634d 100644 --- a/lib/src/model/unsubscribe.dart +++ b/lib/src/model/unsubscribe.dart @@ -3,9 +3,9 @@ import 'package:spinify/src/model/channel_push.dart'; /// {@template unsubscribe} /// Unsubscribe push from Centrifugo server. /// {@endtemplate} -final class CentrifugeUnsubscribe extends CentrifugeChannelPush { +final class SpinifyUnsubscribe extends SpinifyChannelPush { /// {@macro unsubscribe} - const CentrifugeUnsubscribe({ + const SpinifyUnsubscribe({ required super.timestamp, required super.channel, required this.code, diff --git a/lib/src/subscription/client_subscription_impl.dart b/lib/src/subscription/client_subscription_impl.dart index fa528eb..61c40f8 100644 --- a/lib/src/subscription/client_subscription_impl.dart +++ b/lib/src/subscription/client_subscription_impl.dart @@ -2,8 +2,8 @@ import 'dart:async'; import 'package:fixnum/fixnum.dart' as fixnum; import 'package:meta/meta.dart'; -import 'package:spinify/src/client/centrifuge.dart'; import 'package:spinify/src/client/disconnect_code.dart'; +import 'package:spinify/src/client/spinify.dart'; import 'package:spinify/src/model/channel_presence.dart'; import 'package:spinify/src/model/channel_push.dart'; import 'package:spinify/src/model/connect.dart'; @@ -31,33 +31,32 @@ import 'package:spinify/src/util/logger.dart' as logger; /// Client-side subscription implementation. /// {@nodoc} @internal -final class CentrifugeClientSubscriptionImpl - extends CentrifugeClientSubscriptionBase +final class SpinifyClientSubscriptionImpl extends SpinifyClientSubscriptionBase with - CentrifugeClientSubscriptionEventReceiverMixin, - CentrifugeClientSubscriptionErrorsMixin, - CentrifugeClientSubscriptionSubscribeMixin, - CentrifugeClientSubscriptionPublishingMixin, - CentrifugeClientSubscriptionHistoryMixin, - CentrifugeClientSubscriptionPresenceMixin, - CentrifugeClientSubscriptionQueueMixin { + SpinifyClientSubscriptionEventReceiverMixin, + SpinifyClientSubscriptionErrorsMixin, + SpinifyClientSubscriptionSubscribeMixin, + SpinifyClientSubscriptionPublishingMixin, + SpinifyClientSubscriptionHistoryMixin, + SpinifyClientSubscriptionPresenceMixin, + SpinifyClientSubscriptionQueueMixin { /// {@nodoc} - CentrifugeClientSubscriptionImpl({ + SpinifyClientSubscriptionImpl({ required super.channel, required super.transportWeakRef, - CentrifugeSubscriptionConfig? config, - }) : super(config: config ?? const CentrifugeSubscriptionConfig.byDefault()); + SpinifySubscriptionConfig? config, + }) : super(config: config ?? const SpinifySubscriptionConfig.byDefault()); } /// {@nodoc} @internal -abstract base class CentrifugeClientSubscriptionBase - implements CentrifugeClientSubscription { +abstract base class SpinifyClientSubscriptionBase + implements SpinifyClientSubscription { /// {@nodoc} - CentrifugeClientSubscriptionBase({ + SpinifyClientSubscriptionBase({ required this.channel, required WeakReference transportWeakRef, - required CentrifugeSubscriptionConfig config, + required SpinifySubscriptionConfig config, }) : _config = config { _transportWeakRef = transportWeakRef; _initSubscription(); @@ -70,7 +69,7 @@ abstract base class CentrifugeClientSubscriptionBase late fixnum.Int64 _offset; @override - CentrifugeStreamPosition? get since => switch (state.since?.epoch) { + SpinifyStreamPosition? get since => switch (state.since?.epoch) { String epoch => (epoch: epoch, offset: _offset), _ => state.since, }; @@ -87,14 +86,14 @@ abstract base class CentrifugeClientSubscriptionBase /// Subscription config. /// {@nodoc} - final CentrifugeSubscriptionConfig _config; + final SpinifySubscriptionConfig _config; /// Init subscription. /// {@nodoc} @protected @mustCallSuper void _initSubscription() { - _state = CentrifugeSubscriptionState.unsubscribed( + _state = SpinifySubscriptionState.unsubscribed( since: _config.since, code: 0, reason: 'initial state'); _offset = _config.since?.offset ?? fixnum.Int64.ZERO; } @@ -105,23 +104,23 @@ abstract base class CentrifugeClientSubscriptionBase /// - `subscribed` /// {@nodoc} @override - CentrifugeSubscriptionState get state => _state; - late CentrifugeSubscriptionState _state; + SpinifySubscriptionState get state => _state; + late SpinifySubscriptionState _state; /// Stream of subscription states. /// {@nodoc} @override - late final CentrifugeSubscriptionStateStream states = - CentrifugeSubscriptionStateStream(_stateController.stream); + late final SpinifySubscriptionStateStream states = + SpinifySubscriptionStateStream(_stateController.stream); /// States controller. /// {@nodoc} - final StreamController _stateController = - StreamController.broadcast(); + final StreamController _stateController = + StreamController.broadcast(); /// Set new state. /// {@nodoc} - void _setState(CentrifugeSubscriptionState state) { + void _setState(SpinifySubscriptionState state) { if (_state == state) return; final previousState = _state; _stateController.add(_state = state); @@ -131,7 +130,7 @@ abstract base class CentrifugeClientSubscriptionBase /// Notify about new publication. /// {@nodoc} @nonVirtual - void _handlePublication(CentrifugePublication publication) { + void _handlePublication(SpinifyPublication publication) { final offset = publication.offset; if (offset != null && offset > _offset) _offset = offset; } @@ -141,7 +140,7 @@ abstract base class CentrifugeClientSubscriptionBase @mustCallSuper Future close([int code = 0, String reason = 'closed']) async { if (!_state.isUnsubscribed) - _setState(CentrifugeSubscriptionState.unsubscribed( + _setState(SpinifySubscriptionState.unsubscribed( code: code, reason: reason, recoverable: false, @@ -154,41 +153,41 @@ abstract base class CentrifugeClientSubscriptionBase /// Mixin responsible for event receiving and distribution by controllers /// and streams to subscribers. /// {@nodoc} -base mixin CentrifugeClientSubscriptionEventReceiverMixin - on CentrifugeClientSubscriptionBase { +base mixin SpinifyClientSubscriptionEventReceiverMixin + on SpinifyClientSubscriptionBase { @protected @nonVirtual - final StreamController _pushController = - StreamController.broadcast(); + final StreamController _pushController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _publicationsController = - StreamController.broadcast(); + final StreamController _publicationsController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _messagesController = - StreamController.broadcast(); + final StreamController _messagesController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _joinController = - StreamController.broadcast(); + final StreamController _joinController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _leaveController = - StreamController.broadcast(); + final StreamController _leaveController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _presenceController = - StreamController.broadcast(); + final StreamController _presenceController = + StreamController.broadcast(); @override @nonVirtual - late final CentrifugePushesStream stream = CentrifugePushesStream( + late final SpinifyPushesStream stream = SpinifyPushesStream( pushes: _pushController.stream, publications: _publicationsController.stream, messages: _messagesController.stream, @@ -203,34 +202,34 @@ base mixin CentrifugeClientSubscriptionEventReceiverMixin } /// Handle push event from server for the specific channel. - /// Called from `CentrifugeClientSubscriptionsManager.onPush` + /// Called from `SpinifyClientSubscriptionsManager.onPush` /// {@nodoc} @internal @nonVirtual - void onPush(CentrifugeChannelPush push) { + void onPush(SpinifyChannelPush push) { // This is a push to a channel. _pushController.add(push); switch (push) { - case CentrifugePublication publication: + case SpinifyPublication publication: _handlePublication(publication); _publicationsController.add(publication); - case CentrifugeMessage message: + case SpinifyMessage message: _messagesController.add(message); - case CentrifugeJoin join: + case SpinifyJoin join: _presenceController.add(join); _joinController.add(join); - case CentrifugeLeave leave: + case SpinifyLeave leave: _presenceController.add(leave); _leaveController.add(leave); - case CentrifugeSubscribe _: + case SpinifySubscribe _: break; // For server side subscriptions. - case CentrifugeUnsubscribe _: + case SpinifyUnsubscribe _: break; // For server side subscriptions. - case CentrifugeConnect _: + case SpinifyConnect _: break; - case CentrifugeDisconnect _: + case SpinifyDisconnect _: break; - case CentrifugeRefresh _: + case SpinifyRefresh _: break; } } @@ -238,7 +237,7 @@ base mixin CentrifugeClientSubscriptionEventReceiverMixin @override Future close([int code = 0, String reason = 'closed']) async { await super.close(code, reason); - for (final controller in >[ + for (final controller in >[ _pushController, _publicationsController, _messagesController, @@ -254,21 +253,19 @@ base mixin CentrifugeClientSubscriptionEventReceiverMixin /// Mixin responsible for errors stream. /// {@nodoc} @internal -base mixin CentrifugeClientSubscriptionErrorsMixin - on CentrifugeClientSubscriptionBase { +base mixin SpinifyClientSubscriptionErrorsMixin + on SpinifyClientSubscriptionBase { @protected @nonVirtual - void _emitError(CentrifugeException exception, StackTrace stackTrace) => + void _emitError(SpinifyException exception, StackTrace stackTrace) => Spinify.observer?.onError(exception, stackTrace); } /// Mixin responsible for subscribing. /// {@nodoc} @internal -base mixin CentrifugeClientSubscriptionSubscribeMixin - on - CentrifugeClientSubscriptionBase, - CentrifugeClientSubscriptionErrorsMixin { +base mixin SpinifyClientSubscriptionSubscribeMixin + on SpinifyClientSubscriptionBase, SpinifyClientSubscriptionErrorsMixin { /// Refresh timer. /// {@nodoc} Timer? _refreshTimer; @@ -286,7 +283,7 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin } _refreshTimer?.cancel(); _refreshTimer = null; - _setState(CentrifugeSubscriptionState$Subscribing( + _setState(SpinifySubscriptionState$Subscribing( since: since, recoverable: state.recoverable, )); @@ -303,7 +300,7 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin ); final offset = subscribed.since?.offset; if (offset != null && offset > _offset) _offset = offset; - _setState(CentrifugeSubscriptionState$Subscribed( + _setState(SpinifySubscriptionState$Subscribed( since: subscribed.since ?? since, recoverable: subscribed.recoverable, ttl: subscribed.ttl, @@ -311,19 +308,19 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin if (subscribed.publications.isNotEmpty) subscribed.publications.forEach(_handlePublication); if (subscribed.expires) _setRefreshTimer(subscribed.ttl); - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { unsubscribe(0, 'error while subscribing').ignore(); _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { unsubscribe(0, 'error while subscribing').ignore(); - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while subscribing', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @@ -333,14 +330,14 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin FutureOr ready() async { try { switch (state) { - case CentrifugeSubscriptionState$Unsubscribed _: - throw CentrifugeSubscriptionException( + case SpinifySubscriptionState$Unsubscribed _: + throw SpinifySubscriptionException( message: 'Subscription is not subscribed', channel: channel, ); - case CentrifugeSubscriptionState$Subscribed _: + case SpinifySubscriptionState$Subscribed _: return; - case CentrifugeSubscriptionState$Subscribing _: + case SpinifySubscriptionState$Subscribing _: await states.subscribed.first.timeout(_config.timeout); } } on TimeoutException catch (error, stackTrace) { @@ -350,24 +347,24 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin DisconnectCode.timeout.reason, ) .ignore(); - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Timeout exception while waiting for subscribing to $channel', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); - } on CentrifugeException catch (error, stackTrace) { + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Subscription is not subscribed', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @@ -379,7 +376,7 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin _refreshTimer?.cancel(); _refreshTimer = null; if (state.isUnsubscribed) return; - _setState(CentrifugeSubscriptionState.unsubscribed( + _setState(SpinifySubscriptionState.unsubscribed( code: code, reason: reason, since: since, @@ -389,19 +386,19 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin try { await _transport.unsubscribe(channel, _config); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while unsubscribing', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); _transport .disconnect( DisconnectCode.unsubscribeError.code, DisconnectCode.unsubscribeError.reason, ) .ignore(); - Error.throwWithStackTrace(centrifugeException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @@ -435,7 +432,7 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin 'Error while refreshing subscription token', ); _emitError( - CentrifugeRefreshException( + SpinifyRefreshException( message: 'Error while refreshing subscription token', error: error, ), @@ -452,12 +449,12 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin try { if (!state.isUnsubscribed) await unsubscribe(code, reason); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while unsubscribing from channel $channel', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); } await super.close(code, reason); } @@ -466,22 +463,20 @@ base mixin CentrifugeClientSubscriptionSubscribeMixin /// Mixin responsible for publishing. /// {@nodoc} @internal -base mixin CentrifugeClientSubscriptionPublishingMixin - on - CentrifugeClientSubscriptionBase, - CentrifugeClientSubscriptionErrorsMixin { +base mixin SpinifyClientSubscriptionPublishingMixin + on SpinifyClientSubscriptionBase, SpinifyClientSubscriptionErrorsMixin { @override Future publish(List data) async { try { await ready(); await _transport.publish(channel, data); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSendException( + final spinifyException = SpinifySendException( message: 'Error while publishing to channel $channel', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -489,14 +484,12 @@ base mixin CentrifugeClientSubscriptionPublishingMixin /// Mixin responsible for history. /// {@nodoc} @internal -base mixin CentrifugeClientSubscriptionHistoryMixin - on - CentrifugeClientSubscriptionBase, - CentrifugeClientSubscriptionErrorsMixin { +base mixin SpinifyClientSubscriptionHistoryMixin + on SpinifyClientSubscriptionBase, SpinifyClientSubscriptionErrorsMixin { @override - Future history({ + Future history({ int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }) async { await ready(); @@ -508,13 +501,13 @@ base mixin CentrifugeClientSubscriptionHistoryMixin reverse: reverse, ); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while fetching history', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -522,39 +515,37 @@ base mixin CentrifugeClientSubscriptionHistoryMixin /// Mixin responsible for presence. /// {@nodoc} @internal -base mixin CentrifugeClientSubscriptionPresenceMixin - on - CentrifugeClientSubscriptionBase, - CentrifugeClientSubscriptionErrorsMixin { +base mixin SpinifyClientSubscriptionPresenceMixin + on SpinifyClientSubscriptionBase, SpinifyClientSubscriptionErrorsMixin { @override - Future presence() async { + Future presence() async { await ready(); try { return await _transport.presence(channel); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while fetching history', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @override - Future presenceStats() async { + Future presenceStats() async { await ready(); try { return await _transport.presenceStats(channel); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while fetching history', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -563,10 +554,10 @@ base mixin CentrifugeClientSubscriptionPresenceMixin /// SHOULD BE LAST MIXIN. /// {@nodoc} @internal -base mixin CentrifugeClientSubscriptionQueueMixin - on CentrifugeClientSubscriptionBase { +base mixin SpinifyClientSubscriptionQueueMixin + on SpinifyClientSubscriptionBase { /// {@nodoc} - final CentrifugeEventQueue _eventQueue = CentrifugeEventQueue(); + final SpinifyEventQueue _eventQueue = SpinifyEventQueue(); @override FutureOr ready() => _eventQueue.push( @@ -597,12 +588,12 @@ base mixin CentrifugeClientSubscriptionQueueMixin ); @override - Future history({ + Future history({ int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }) => - _eventQueue.push( + _eventQueue.push( 'history', () => super.history( limit: limit, @@ -612,12 +603,12 @@ base mixin CentrifugeClientSubscriptionQueueMixin ); @override - Future presence() => - _eventQueue.push('presence', super.presence); + Future presence() => + _eventQueue.push('presence', super.presence); @override - Future presenceStats() => _eventQueue - .push('presenceStats', super.presenceStats); + Future presenceStats() => _eventQueue + .push('presenceStats', super.presenceStats); @override Future close([int code = 0, String reason = 'closed']) => _eventQueue diff --git a/lib/src/subscription/client_subscription_manager.dart b/lib/src/subscription/client_subscription_manager.dart index 9cb1d5b..0968dc5 100644 --- a/lib/src/subscription/client_subscription_manager.dart +++ b/lib/src/subscription/client_subscription_manager.dart @@ -16,35 +16,35 @@ final class ClientSubscriptionManager { ClientSubscriptionManager(ISpinifyTransport transport) : _transportWeakRef = WeakReference(transport); - /// Centrifuge client weak reference. + /// Spinify client weak reference. /// {@nodoc} final WeakReference _transportWeakRef; /// Subscriptions registry (channel -> subscription). - /// Channel : CentrifugeClientSubscription + /// Channel : SpinifyClientSubscription /// {@nodoc} - final Map _channelSubscriptions = - {}; + final Map _channelSubscriptions = + {}; /// Create new client-side subscription. /// `newSubscription(channel, config)` allocates a new Subscription /// in the registry or throws an exception if the Subscription /// is already there. We will discuss common Subscription options below. /// {@nodoc} - CentrifugeClientSubscription newSubscription( + SpinifyClientSubscription newSubscription( String channel, - CentrifugeSubscriptionConfig? config, + SpinifySubscriptionConfig? config, ) { if (_channelSubscriptions.containsKey(channel)) { - throw CentrifugeSubscriptionException( + throw SpinifySubscriptionException( channel: channel, message: 'Subscription to a channel "$channel" already exists ' 'in client\'s internal registry', ); } - return _channelSubscriptions[channel] = CentrifugeClientSubscriptionImpl( + return _channelSubscriptions[channel] = SpinifyClientSubscriptionImpl( channel: channel, - config: config ?? const CentrifugeSubscriptionConfig.byDefault(), + config: config ?? const SpinifySubscriptionConfig.byDefault(), transportWeakRef: _transportWeakRef, ); } @@ -54,17 +54,17 @@ final class ClientSubscriptionManager { /// so you can iterate over all and do some action if required /// (for example, you want to unsubscribe/remove all subscriptions). /// {@nodoc} - Map get subscriptions => - UnmodifiableMapView({ + Map get subscriptions => + UnmodifiableMapView({ for (final entry in _channelSubscriptions.entries) entry.key: entry.value, }); - /// Remove the [CentrifugeClientSubscription] from internal registry - /// and unsubscribe from [CentrifugeClientSubscription.channel]. + /// Remove the [SpinifyClientSubscription] from internal registry + /// and unsubscribe from [SpinifyClientSubscription.channel]. /// {@nodoc} Future removeSubscription( - CentrifugeClientSubscription subscription, + SpinifyClientSubscription subscription, ) async { final subFromRegistry = _channelSubscriptions[subscription.channel]; try { @@ -73,11 +73,11 @@ final class ClientSubscriptionManager { // If not the same subscription instance - unsubscribe it too. await subscription.unsubscribe(); } - } on CentrifugeException { + } on SpinifyException { rethrow; } on Object catch (error, stackTrace) { Error.throwWithStackTrace( - CentrifugeSubscriptionException( + SpinifySubscriptionException( channel: subscription.channel, message: 'Error while unsubscribing', error: error, @@ -124,15 +124,15 @@ final class ClientSubscriptionManager { /// Handle push event from server for the specific channel. /// {@nodoc} @internal - void onPush(CentrifugeChannelPush push) => + void onPush(SpinifyChannelPush push) => _channelSubscriptions[push.channel]?.onPush(push); /// Get subscription to the channel /// from internal registry or null if not found. /// - /// You need to call [CentrifugeClientSubscription.subscribe] + /// You need to call [SpinifyClientSubscription.subscribe] /// to start receiving events /// {@nodoc} - CentrifugeClientSubscription? operator [](String channel) => + SpinifyClientSubscription? operator [](String channel) => _channelSubscriptions[channel]; } diff --git a/lib/src/subscription/server_subscription_impl.dart b/lib/src/subscription/server_subscription_impl.dart index a150ab8..1dd27db 100644 --- a/lib/src/subscription/server_subscription_impl.dart +++ b/lib/src/subscription/server_subscription_impl.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'package:fixnum/fixnum.dart' as fixnum; import 'package:meta/meta.dart'; -import 'package:spinify/src/client/centrifuge.dart'; +import 'package:spinify/src/client/spinify.dart'; import 'package:spinify/src/model/channel_presence.dart'; import 'package:spinify/src/model/channel_push.dart'; import 'package:spinify/src/model/connect.dart'; @@ -29,18 +29,17 @@ import 'package:spinify/src/util/logger.dart' as logger; /// Server-side subscription implementation. /// {@nodoc} @internal -final class CentrifugeServerSubscriptionImpl - extends CentrifugeServerSubscriptionBase +final class SpinifyServerSubscriptionImpl extends SpinifyServerSubscriptionBase with - CentrifugeServerSubscriptionEventReceiverMixin, - CentrifugeServerSubscriptionErrorsMixin, - CentrifugeServerSubscriptionReadyMixin, - CentrifugeServerSubscriptionPublishingMixin, - CentrifugeServerSubscriptionHistoryMixin, - CentrifugeServerSubscriptionPresenceMixin, - CentrifugeServerSubscriptionQueueMixin { + SpinifyServerSubscriptionEventReceiverMixin, + SpinifyServerSubscriptionErrorsMixin, + SpinifyServerSubscriptionReadyMixin, + SpinifyServerSubscriptionPublishingMixin, + SpinifyServerSubscriptionHistoryMixin, + SpinifyServerSubscriptionPresenceMixin, + SpinifyServerSubscriptionQueueMixin { /// {@nodoc} - CentrifugeServerSubscriptionImpl({ + SpinifyServerSubscriptionImpl({ required super.channel, required super.transportWeakRef, }); @@ -48,10 +47,10 @@ final class CentrifugeServerSubscriptionImpl /// {@nodoc} @internal -abstract base class CentrifugeServerSubscriptionBase - implements CentrifugeServerSubscription { +abstract base class SpinifyServerSubscriptionBase + implements SpinifyServerSubscription { /// {@nodoc} - CentrifugeServerSubscriptionBase({ + SpinifyServerSubscriptionBase({ required this.channel, required WeakReference transportWeakRef, }) { @@ -63,7 +62,7 @@ abstract base class CentrifugeServerSubscriptionBase final String channel; @override - CentrifugeStreamPosition? get since => switch (state.since?.epoch) { + SpinifyStreamPosition? get since => switch (state.since?.epoch) { String epoch => (epoch: epoch, offset: _offset), _ => state.since, }; @@ -86,8 +85,8 @@ abstract base class CentrifugeServerSubscriptionBase @protected @mustCallSuper void _initSubscription() { - _state = CentrifugeSubscriptionState.unsubscribed( - code: 0, reason: 'initial state'); + _state = + SpinifySubscriptionState.unsubscribed(code: 0, reason: 'initial state'); } /// Subscription has 3 states: @@ -96,23 +95,23 @@ abstract base class CentrifugeServerSubscriptionBase /// - `subscribed` /// {@nodoc} @override - CentrifugeSubscriptionState get state => _state; - late CentrifugeSubscriptionState _state; + SpinifySubscriptionState get state => _state; + late SpinifySubscriptionState _state; /// Stream of subscription states. /// {@nodoc} @override - late final CentrifugeSubscriptionStateStream states = - CentrifugeSubscriptionStateStream(_stateController.stream); + late final SpinifySubscriptionStateStream states = + SpinifySubscriptionStateStream(_stateController.stream); /// States controller. /// {@nodoc} - final StreamController _stateController = - StreamController.broadcast(); + final StreamController _stateController = + StreamController.broadcast(); /// Set new state. /// {@nodoc} - void _setState(CentrifugeSubscriptionState state) { + void _setState(SpinifySubscriptionState state) { if (_state == state) return; final previousState = _state; _stateController.add(_state = state); @@ -122,7 +121,7 @@ abstract base class CentrifugeServerSubscriptionBase /// Notify about new publication. /// {@nodoc} @nonVirtual - void _handlePublication(CentrifugePublication publication) { + void _handlePublication(SpinifyPublication publication) { final offset = publication.offset; if (offset != null && offset > _offset) _offset = offset; } @@ -132,7 +131,7 @@ abstract base class CentrifugeServerSubscriptionBase @mustCallSuper Future close([int code = 0, String reason = 'closed']) async { if (!_state.isUnsubscribed) - _setState(CentrifugeSubscriptionState.unsubscribed( + _setState(SpinifySubscriptionState.unsubscribed( code: 0, reason: 'closed', recoverable: false, @@ -145,41 +144,41 @@ abstract base class CentrifugeServerSubscriptionBase /// Mixin responsible for event receiving and distribution by controllers /// and streams to subscribers. /// {@nodoc} -base mixin CentrifugeServerSubscriptionEventReceiverMixin - on CentrifugeServerSubscriptionBase { +base mixin SpinifyServerSubscriptionEventReceiverMixin + on SpinifyServerSubscriptionBase { @protected @nonVirtual - final StreamController _pushController = - StreamController.broadcast(); + final StreamController _pushController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _publicationsController = - StreamController.broadcast(); + final StreamController _publicationsController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _messagesController = - StreamController.broadcast(); + final StreamController _messagesController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _joinController = - StreamController.broadcast(); + final StreamController _joinController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _leaveController = - StreamController.broadcast(); + final StreamController _leaveController = + StreamController.broadcast(); @protected @nonVirtual - final StreamController _presenceController = - StreamController.broadcast(); + final StreamController _presenceController = + StreamController.broadcast(); @override @nonVirtual - late final CentrifugePushesStream stream = CentrifugePushesStream( + late final SpinifyPushesStream stream = SpinifyPushesStream( pushes: _pushController.stream, publications: _publicationsController.stream, messages: _messagesController.stream, @@ -194,44 +193,44 @@ base mixin CentrifugeServerSubscriptionEventReceiverMixin } /// Handle push event from server for the specific channel. - /// Called from `CentrifugeClientSubscriptionsManager.onPush` + /// Called from `SpinifyClientSubscriptionsManager.onPush` /// {@nodoc} @internal @nonVirtual - void onPush(CentrifugeChannelPush push) { + void onPush(SpinifyChannelPush push) { // This is a push to a channel. _pushController.add(push); switch (push) { - case CentrifugePublication publication: + case SpinifyPublication publication: _handlePublication(publication); _publicationsController.add(publication); - case CentrifugeMessage message: + case SpinifyMessage message: _messagesController.add(message); - case CentrifugeJoin join: + case SpinifyJoin join: _presenceController.add(join); _joinController.add(join); - case CentrifugeLeave leave: + case SpinifyLeave leave: _presenceController.add(leave); _leaveController.add(leave); - case CentrifugeSubscribe sub: + case SpinifySubscribe sub: final offset = sub.streamPosition?.offset; if (offset != null && offset > _offset) _offset = offset; - _setState(CentrifugeSubscriptionState.subscribed( + _setState(SpinifySubscriptionState.subscribed( since: sub.streamPosition ?? since, recoverable: sub.recoverable, )); - case CentrifugeUnsubscribe unsub: - _setState(CentrifugeSubscriptionState.unsubscribed( + case SpinifyUnsubscribe unsub: + _setState(SpinifySubscriptionState.unsubscribed( code: unsub.code, reason: unsub.reason, recoverable: state.recoverable, since: since, )); - case CentrifugeConnect _: + case SpinifyConnect _: break; - case CentrifugeDisconnect _: + case SpinifyDisconnect _: break; - case CentrifugeRefresh _: + case SpinifyRefresh _: break; } } @@ -239,7 +238,7 @@ base mixin CentrifugeServerSubscriptionEventReceiverMixin @override Future close([int code = 0, String reason = 'closed']) async { await super.close(code, reason); - for (final controller in >[ + for (final controller in >[ _pushController, _publicationsController, _messagesController, @@ -255,48 +254,46 @@ base mixin CentrifugeServerSubscriptionEventReceiverMixin /// Mixin responsible for errors stream. /// {@nodoc} @internal -base mixin CentrifugeServerSubscriptionErrorsMixin - on CentrifugeServerSubscriptionBase { +base mixin SpinifyServerSubscriptionErrorsMixin + on SpinifyServerSubscriptionBase { @protected @nonVirtual - void _emitError(CentrifugeException exception, StackTrace stackTrace) => + void _emitError(SpinifyException exception, StackTrace stackTrace) => Spinify.observer?.onError(exception, stackTrace); } /// Mixin responsible for ready method. /// {@nodoc} @internal -base mixin CentrifugeServerSubscriptionReadyMixin - on - CentrifugeServerSubscriptionBase, - CentrifugeServerSubscriptionErrorsMixin { +base mixin SpinifyServerSubscriptionReadyMixin + on SpinifyServerSubscriptionBase, SpinifyServerSubscriptionErrorsMixin { /// Await for subscription to be ready. /// {@nodoc} @override FutureOr ready() async { try { switch (state) { - case CentrifugeSubscriptionState$Unsubscribed _: - throw CentrifugeSubscriptionException( + case SpinifySubscriptionState$Unsubscribed _: + throw SpinifySubscriptionException( message: 'Subscription is not subscribed', channel: channel, ); - case CentrifugeSubscriptionState$Subscribed _: + case SpinifySubscriptionState$Subscribed _: return; - case CentrifugeSubscriptionState$Subscribing _: + case SpinifySubscriptionState$Subscribing _: await states.subscribed.first; } - } on CentrifugeException catch (error, stackTrace) { + } on SpinifyException catch (error, stackTrace) { _emitError(error, stackTrace); rethrow; } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Subscription is not subscribed', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @@ -304,7 +301,7 @@ base mixin CentrifugeServerSubscriptionReadyMixin /// {@nodoc} void setSubscribed() { if (!state.isSubscribed) - _setState(CentrifugeSubscriptionState.subscribed( + _setState(SpinifySubscriptionState.subscribed( since: since, recoverable: state.recoverable, )); @@ -314,7 +311,7 @@ base mixin CentrifugeServerSubscriptionReadyMixin /// {@nodoc} void setSubscribing() { if (!state.isSubscribing) - _setState(CentrifugeSubscriptionState.subscribing( + _setState(SpinifySubscriptionState.subscribing( since: since, recoverable: state.recoverable, )); @@ -324,7 +321,7 @@ base mixin CentrifugeServerSubscriptionReadyMixin /// {@nodoc} void setUnsubscribed(int code, String reason) { if (!state.isUnsubscribed) - _setState(CentrifugeSubscriptionState.unsubscribed( + _setState(SpinifySubscriptionState.unsubscribed( code: code, reason: reason, recoverable: state.recoverable, @@ -343,22 +340,20 @@ base mixin CentrifugeServerSubscriptionReadyMixin /// Mixin responsible for publishing. /// {@nodoc} @internal -base mixin CentrifugeServerSubscriptionPublishingMixin - on - CentrifugeServerSubscriptionBase, - CentrifugeServerSubscriptionErrorsMixin { +base mixin SpinifyServerSubscriptionPublishingMixin + on SpinifyServerSubscriptionBase, SpinifyServerSubscriptionErrorsMixin { @override Future publish(List data) async { try { await ready(); await _transport.publish(channel, data); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSendException( + final spinifyException = SpinifySendException( message: 'Error while publishing to channel $channel', error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -366,14 +361,12 @@ base mixin CentrifugeServerSubscriptionPublishingMixin /// Mixin responsible for history. /// {@nodoc} @internal -base mixin CentrifugeServerSubscriptionHistoryMixin - on - CentrifugeServerSubscriptionBase, - CentrifugeServerSubscriptionErrorsMixin { +base mixin SpinifyServerSubscriptionHistoryMixin + on SpinifyServerSubscriptionBase, SpinifyServerSubscriptionErrorsMixin { @override - Future history({ + Future history({ int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }) async { await ready(); @@ -385,13 +378,13 @@ base mixin CentrifugeServerSubscriptionHistoryMixin reverse: reverse, ); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while fetching history', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -399,39 +392,37 @@ base mixin CentrifugeServerSubscriptionHistoryMixin /// Mixin responsible for presence. /// {@nodoc} @internal -base mixin CentrifugeServerSubscriptionPresenceMixin - on - CentrifugeServerSubscriptionBase, - CentrifugeServerSubscriptionErrorsMixin { +base mixin SpinifyServerSubscriptionPresenceMixin + on SpinifyServerSubscriptionBase, SpinifyServerSubscriptionErrorsMixin { @override - Future presence() async { + Future presence() async { await ready(); try { return await _transport.presence(channel); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while fetching history', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } @override - Future presenceStats() async { + Future presenceStats() async { await ready(); try { return await _transport.presenceStats(channel); } on Object catch (error, stackTrace) { - final centrifugeException = CentrifugeSubscriptionException( + final spinifyException = SpinifySubscriptionException( message: 'Error while fetching history', channel: channel, error: error, ); - _emitError(centrifugeException, stackTrace); - Error.throwWithStackTrace(centrifugeException, stackTrace); + _emitError(spinifyException, stackTrace); + Error.throwWithStackTrace(spinifyException, stackTrace); } } } @@ -440,10 +431,10 @@ base mixin CentrifugeServerSubscriptionPresenceMixin /// SHOULD BE LAST MIXIN. /// {@nodoc} @internal -base mixin CentrifugeServerSubscriptionQueueMixin - on CentrifugeServerSubscriptionBase { +base mixin SpinifyServerSubscriptionQueueMixin + on SpinifyServerSubscriptionBase { /// {@nodoc} - final CentrifugeEventQueue _eventQueue = CentrifugeEventQueue(); + final SpinifyEventQueue _eventQueue = SpinifyEventQueue(); @override FutureOr ready() => _eventQueue.push( @@ -458,12 +449,12 @@ base mixin CentrifugeServerSubscriptionQueueMixin ); @override - Future history({ + Future history({ int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }) => - _eventQueue.push( + _eventQueue.push( 'history', () => super.history( limit: limit, @@ -473,12 +464,12 @@ base mixin CentrifugeServerSubscriptionQueueMixin ); @override - Future presence() => - _eventQueue.push('presence', super.presence); + Future presence() => + _eventQueue.push('presence', super.presence); @override - Future presenceStats() => _eventQueue - .push('presenceStats', super.presenceStats); + Future presenceStats() => _eventQueue + .push('presenceStats', super.presenceStats); @override Future close([int code = 0, String reason = 'closed']) => _eventQueue diff --git a/lib/src/subscription/server_subscription_manager.dart b/lib/src/subscription/server_subscription_manager.dart index 94b69aa..414bc25 100644 --- a/lib/src/subscription/server_subscription_manager.dart +++ b/lib/src/subscription/server_subscription_manager.dart @@ -16,37 +16,37 @@ final class ServerSubscriptionManager { ServerSubscriptionManager(ISpinifyTransport transport) : _transportWeakRef = WeakReference(transport); - /// Centrifuge client weak reference. + /// Spinify client weak reference. /// {@nodoc} final WeakReference _transportWeakRef; /// Subscriptions registry (channel -> subscription). - /// Channel : CentrifugeClientSubscription + /// Channel : SpinifyClientSubscription /// {@nodoc} - final Map _channelSubscriptions = - {}; + final Map _channelSubscriptions = + {}; /// Get map wirth all registered client-side subscriptions. /// Returns all registered subscriptions, /// so you can iterate over all and do some action if required /// (for example, you want to unsubscribe/remove all subscriptions). /// {@nodoc} - Map get subscriptions => - UnmodifiableMapView({ + Map get subscriptions => + UnmodifiableMapView({ for (final entry in _channelSubscriptions.entries) entry.key: entry.value, }); - /// Called on [CentrifugeSubscribe] push from server. - void subscribe(CentrifugeSubscribe subscribe) {} + /// Called on [SpinifySubscribe] push from server. + void subscribe(SpinifySubscribe subscribe) {} - /// Called on [CentrifugeUnsubscribe] push from server. - void unsubscribe(CentrifugeUnsubscribe subscribe) {} + /// Called on [SpinifyUnsubscribe] push from server. + void unsubscribe(SpinifyUnsubscribe subscribe) {} /// Called when client finished connection handshake with server. /// Add non existing subscriptions to registry and mark all connected. /// Remove subscriptions which are not in [subs] argument. - void upsert(List subs) { + void upsert(List subs) { final currentChannels = _channelSubscriptions.keys.toSet(); // Remove subscriptions which are not in subs argument. for (final channel in currentChannels) { @@ -55,7 +55,7 @@ final class ServerSubscriptionManager { } // Add non existing subscriptions to registry and mark all connected. for (final sub in subs) { - (_channelSubscriptions[sub.channel] ??= CentrifugeServerSubscriptionImpl( + (_channelSubscriptions[sub.channel] ??= SpinifyServerSubscriptionImpl( channel: sub.channel, transportWeakRef: _transportWeakRef, )) @@ -109,15 +109,15 @@ final class ServerSubscriptionManager { /// Handle push event from server for the specific channel. /// {@nodoc} @internal - void onPush(CentrifugeChannelPush push) => + void onPush(SpinifyChannelPush push) => _channelSubscriptions[push.channel]?.onPush(push); /// Get subscription to the channel /// from internal registry or null if not found. /// - /// You need to call [CentrifugeClientSubscription.subscribe] + /// You need to call [SpinifyClientSubscription.subscribe] /// to start receiving events /// {@nodoc} - CentrifugeServerSubscription? operator [](String channel) => + SpinifyServerSubscription? operator [](String channel) => _channelSubscriptions[channel]; } diff --git a/lib/src/subscription/subcibed_on_channel.dart b/lib/src/subscription/subcibed_on_channel.dart index e2db5d9..6ea0464 100644 --- a/lib/src/subscription/subcibed_on_channel.dart +++ b/lib/src/subscription/subcibed_on_channel.dart @@ -32,10 +32,10 @@ final class SubcibedOnChannel { final bool recoverable; /// Stream position. - final CentrifugeStreamPosition? since; + final SpinifyStreamPosition? since; /// List of publications since last stream position. - final List publications; + final List publications; /// Whether channel is recovered after stream failure. final bool recovered; diff --git a/lib/src/subscription/subscription.dart b/lib/src/subscription/subscription.dart index 29fee4c..0693e0d 100644 --- a/lib/src/subscription/subscription.dart +++ b/lib/src/subscription/subscription.dart @@ -9,7 +9,7 @@ import 'package:spinify/src/subscription/subscription_state.dart'; import 'package:spinify/src/subscription/subscription_states_stream.dart'; /// {@template subscription} -/// Centrifuge subscription interface. +/// Spinify subscription interface. /// {@endtemplate} /// {@category Subscription} /// {@category Entity} @@ -18,16 +18,16 @@ abstract interface class ISpinifySubscription { abstract final String channel; /// Current subscription state. - abstract final CentrifugeSubscriptionState state; + abstract final SpinifySubscriptionState state; /// Offset of last successfully received message. - abstract final CentrifugeStreamPosition? since; + abstract final SpinifyStreamPosition? since; /// Stream of subscription states. - abstract final CentrifugeSubscriptionStateStream states; + abstract final SpinifySubscriptionStateStream states; /// Stream of received pushes from Centrifugo server for a channel. - abstract final CentrifugePushesStream stream; + abstract final SpinifyPushesStream stream; /// Await for subscription to be ready. /// Ready resolves when subscription successfully subscribed. @@ -39,17 +39,17 @@ abstract interface class ISpinifySubscription { /// Fetch publication history inside a channel. /// Only for channels where history is enabled. - Future history({ + Future history({ int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }); /// Fetch presence information inside a channel. - Future presence(); + Future presence(); /// Fetch presence stats information inside a channel. - Future presenceStats(); + Future presenceStats(); } /// {@template client_subscription} @@ -107,7 +107,7 @@ abstract interface class ISpinifySubscription { /// {@category Subscription} /// {@category Entity} /// {@subCategory Client-side} -abstract interface class CentrifugeClientSubscription +abstract interface class SpinifyClientSubscription implements ISpinifySubscription { /// Start subscribing to a channel Future subscribe(); @@ -119,7 +119,7 @@ abstract interface class CentrifugeClientSubscription ]); @override - String toString() => 'CentrifugeClientSubscription{channel: $channel}'; + String toString() => 'SpinifyClientSubscription{channel: $channel}'; } /// {@template server_subscription} @@ -137,8 +137,8 @@ abstract interface class CentrifugeClientSubscription /// {@category Subscription} /// {@category Entity} /// {@subCategory Server-side} -abstract interface class CentrifugeServerSubscription +abstract interface class SpinifyServerSubscription implements ISpinifySubscription { @override - String toString() => 'CentrifugeServerSubscription{channel: $channel}'; + String toString() => 'SpinifyServerSubscription{channel: $channel}'; } diff --git a/lib/src/subscription/subscription_config.dart b/lib/src/subscription/subscription_config.dart index 445569a..334a68a 100644 --- a/lib/src/subscription/subscription_config.dart +++ b/lib/src/subscription/subscription_config.dart @@ -4,17 +4,17 @@ import 'package:fixnum/fixnum.dart' as fixnum; import 'package:meta/meta.dart'; /// Token used for subscription. -typedef CentrifugeSubscriptionToken = String; +typedef SpinifySubscriptionToken = String; /// Callback to get token for subscription. /// If method returns null then subscription will be established without token. -typedef CentrifugeSubscriptionTokenCallback - = FutureOr Function(); +typedef SpinifySubscriptionTokenCallback = FutureOr + Function(); /// Callback to set subscription payload data. /// /// If method returns null then no payload will be sent at subscribe time. -typedef CentrifugeSubscribePayloadCallback = FutureOr?> Function(); +typedef SpinifySubscribePayloadCallback = FutureOr?> Function(); /// {@template subscription_config} /// Subscription common options @@ -39,9 +39,9 @@ typedef CentrifugeSubscribePayloadCallback = FutureOr?> Function(); /// {@category Subscription} /// {@category Entity} @immutable -class CentrifugeSubscriptionConfig { +class SpinifySubscriptionConfig { /// {@macro subscription_config} - const CentrifugeSubscriptionConfig({ + const SpinifySubscriptionConfig({ this.getToken, this.getPayload, this.resubscribeInterval = ( @@ -59,16 +59,16 @@ class CentrifugeSubscriptionConfig { /// /// {@macro subscription_config} @literal - const factory CentrifugeSubscriptionConfig.byDefault() = - CentrifugeSubscriptionConfig; + const factory SpinifySubscriptionConfig.byDefault() = + SpinifySubscriptionConfig; /// Callback to get token for subscription /// and get updated token upon expiration. - final CentrifugeSubscriptionTokenCallback? getToken; + final SpinifySubscriptionTokenCallback? getToken; /// Data to send with subscription request. /// Subscription `data` is attached to every subscribe/resubscribe request. - final CentrifugeSubscribePayloadCallback? getPayload; + final SpinifySubscribePayloadCallback? getPayload; /// Resubscribe backoff algorithm final ({Duration min, Duration max}) resubscribeInterval; diff --git a/lib/src/subscription/subscription_state.dart b/lib/src/subscription/subscription_state.dart index 69fde7e..9aa951a 100644 --- a/lib/src/subscription/subscription_state.dart +++ b/lib/src/subscription/subscription_state.dart @@ -13,40 +13,39 @@ import 'package:meta/meta.dart'; /// {@category Subscription} /// {@category Entity} @immutable -sealed class CentrifugeSubscriptionState - extends _$CentrifugeSubscriptionStateBase { +sealed class SpinifySubscriptionState extends _$SpinifySubscriptionStateBase { /// {@macro subscription_state} - const CentrifugeSubscriptionState( + const SpinifySubscriptionState( {required super.timestamp, required super.since, required super.recoverable}); /// Unsubscribed /// {@macro subscription_state} - factory CentrifugeSubscriptionState.unsubscribed({ + factory SpinifySubscriptionState.unsubscribed({ required int code, required String reason, DateTime? timestamp, ({fixnum.Int64 offset, String epoch})? since, bool recoverable, - }) = CentrifugeSubscriptionState$Unsubscribed; + }) = SpinifySubscriptionState$Unsubscribed; /// Subscribing /// {@macro subscription_state} - factory CentrifugeSubscriptionState.subscribing({ + factory SpinifySubscriptionState.subscribing({ DateTime? timestamp, ({fixnum.Int64 offset, String epoch})? since, bool recoverable, - }) = CentrifugeSubscriptionState$Subscribing; + }) = SpinifySubscriptionState$Subscribing; /// Subscribed /// {@macro subscription_state} - factory CentrifugeSubscriptionState.subscribed({ + factory SpinifySubscriptionState.subscribed({ DateTime? timestamp, ({fixnum.Int64 offset, String epoch})? since, bool recoverable, DateTime? ttl, - }) = CentrifugeSubscriptionState$Subscribed; + }) = SpinifySubscriptionState$Subscribed; } /// Unsubscribed state @@ -54,10 +53,10 @@ sealed class CentrifugeSubscriptionState /// {@nodoc} /// {@category Subscription} /// {@category Entity} -final class CentrifugeSubscriptionState$Unsubscribed - extends CentrifugeSubscriptionState with _$CentrifugeSubscriptionState { +final class SpinifySubscriptionState$Unsubscribed + extends SpinifySubscriptionState with _$SpinifySubscriptionState { /// {@nodoc} - CentrifugeSubscriptionState$Unsubscribed({ + SpinifySubscriptionState$Unsubscribed({ required this.code, required this.reason, DateTime? timestamp, @@ -85,14 +84,14 @@ final class CentrifugeSubscriptionState$Unsubscribed @override R map({ - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch unsubscribed, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribing, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribed, }) => unsubscribed(this); @@ -111,10 +110,10 @@ final class CentrifugeSubscriptionState$Unsubscribed /// {@nodoc} /// {@category Subscription} /// {@category Entity} -final class CentrifugeSubscriptionState$Subscribing - extends CentrifugeSubscriptionState with _$CentrifugeSubscriptionState { +final class SpinifySubscriptionState$Subscribing + extends SpinifySubscriptionState with _$SpinifySubscriptionState { /// {@nodoc} - CentrifugeSubscriptionState$Subscribing({ + SpinifySubscriptionState$Subscribing({ DateTime? timestamp, ({fixnum.Int64 offset, String epoch})? since, bool recoverable = false, @@ -134,14 +133,14 @@ final class CentrifugeSubscriptionState$Subscribing @override R map({ - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch unsubscribed, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribing, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribed, }) => subscribing(this); @@ -160,10 +159,10 @@ final class CentrifugeSubscriptionState$Subscribing /// {@nodoc} /// {@category Subscription} /// {@category Entity} -final class CentrifugeSubscriptionState$Subscribed - extends CentrifugeSubscriptionState with _$CentrifugeSubscriptionState { +final class SpinifySubscriptionState$Subscribed extends SpinifySubscriptionState + with _$SpinifySubscriptionState { /// {@nodoc} - CentrifugeSubscriptionState$Subscribed({ + SpinifySubscriptionState$Subscribed({ DateTime? timestamp, ({fixnum.Int64 offset, String epoch})? since, bool recoverable = false, @@ -187,14 +186,14 @@ final class CentrifugeSubscriptionState$Subscribed @override R map({ - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch unsubscribed, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribing, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribed, }) => subscribed(this); @@ -210,18 +209,17 @@ final class CentrifugeSubscriptionState$Subscribed } /// {@nodoc} -base mixin _$CentrifugeSubscriptionState on CentrifugeSubscriptionState {} +base mixin _$SpinifySubscriptionState on SpinifySubscriptionState {} -/// Pattern matching for [CentrifugeSubscriptionState]. -typedef CentrifugeSubscriptionStateMatch - = R Function(S state); +/// Pattern matching for [SpinifySubscriptionState]. +typedef SpinifySubscriptionStateMatch = R + Function(S state); /// {@nodoc} @immutable -abstract base class _$CentrifugeSubscriptionStateBase { +abstract base class _$SpinifySubscriptionStateBase { /// {@nodoc} - const _$CentrifugeSubscriptionStateBase({ + const _$SpinifySubscriptionStateBase({ required this.timestamp, required this.since, required this.recoverable, @@ -245,29 +243,27 @@ abstract base class _$CentrifugeSubscriptionStateBase { /// Whether channel is subscribed. abstract final bool isSubscribed; - /// Pattern matching for [CentrifugeSubscriptionState]. + /// Pattern matching for [SpinifySubscriptionState]. R map({ - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch unsubscribed, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribing, - required CentrifugeSubscriptionStateMatch + required SpinifySubscriptionStateMatch subscribed, }); - /// Pattern matching for [CentrifugeSubscriptionState]. + /// Pattern matching for [SpinifySubscriptionState]. R maybeMap({ required R Function() orElse, - CentrifugeSubscriptionStateMatch? + SpinifySubscriptionStateMatch? unsubscribed, - CentrifugeSubscriptionStateMatch? + SpinifySubscriptionStateMatch? subscribing, - CentrifugeSubscriptionStateMatch? + SpinifySubscriptionStateMatch? subscribed, }) => map( @@ -276,15 +272,13 @@ abstract base class _$CentrifugeSubscriptionStateBase { subscribed: subscribed ?? (_) => orElse(), ); - /// Pattern matching for [CentrifugeSubscriptionState]. + /// Pattern matching for [SpinifySubscriptionState]. R? mapOrNull({ - CentrifugeSubscriptionStateMatch? + SpinifySubscriptionStateMatch? unsubscribed, - CentrifugeSubscriptionStateMatch? + SpinifySubscriptionStateMatch? subscribing, - CentrifugeSubscriptionStateMatch? + SpinifySubscriptionStateMatch? subscribed, }) => map( diff --git a/lib/src/subscription/subscription_states_stream.dart b/lib/src/subscription/subscription_states_stream.dart index 90a384d..5997d4e 100644 --- a/lib/src/subscription/subscription_states_stream.dart +++ b/lib/src/subscription/subscription_states_stream.dart @@ -2,29 +2,29 @@ import 'dart:async'; import 'package:spinify/src/subscription/subscription_state.dart'; -/// Stream of Centrifuge's [CentrifugeSubscriptionState] changes. +/// Stream of Spinify's [SpinifySubscriptionState] changes. /// {@category Subscription} /// {@category Entity} -final class CentrifugeSubscriptionStateStream - extends StreamView { - /// Stream of Centrifuge's [CentrifugeSubscriptionState] changes. - CentrifugeSubscriptionStateStream(super.stream); +final class SpinifySubscriptionStateStream + extends StreamView { + /// Stream of Spinify's [SpinifySubscriptionState] changes. + SpinifySubscriptionStateStream(super.stream); /// Unsubscribed - late final Stream unsubscribed = - whereType(); + late final Stream unsubscribed = + whereType(); /// Subscribing - late final Stream subscribing = - whereType(); + late final Stream subscribing = + whereType(); /// Subscribed - late final Stream subscribed = - whereType(); + late final Stream subscribed = + whereType(); - /// Filtered stream of data of [CentrifugeSubscriptionState]. - Stream whereType() => transform( - StreamTransformer.fromHandlers( + /// Filtered stream of data of [SpinifySubscriptionState]. + Stream whereType() => + transform(StreamTransformer.fromHandlers( handleData: (data, sink) => switch (data) { T valid => sink.add(valid), _ => null, diff --git a/lib/src/transport/transport_interface.dart b/lib/src/transport/transport_interface.dart index 790380e..6989379 100644 --- a/lib/src/transport/transport_interface.dart +++ b/lib/src/transport/transport_interface.dart @@ -19,15 +19,15 @@ import 'package:spinify/src/util/notifier.dart'; abstract interface class ISpinifyTransport { /// Current state /// {@nodoc} - CentrifugeState get state; + SpinifyState get state; /// State observable. /// {@nodoc} - abstract final CentrifugeListenable states; + abstract final SpinifyListenable states; - /// Centrifuge events. + /// Spinify events. /// {@nodoc} - abstract final CentrifugeListenable events; + abstract final SpinifyListenable events; /// Connect to the server. /// [url] is a URL of endpoint. @@ -48,15 +48,15 @@ abstract interface class ISpinifyTransport { /// {@nodoc} Future subscribe( String channel, - CentrifugeSubscriptionConfig config, - CentrifugeStreamPosition? since, + SpinifySubscriptionConfig config, + SpinifyStreamPosition? since, ); /// Unsubscribe from channel. /// {@nodoc} Future unsubscribe( String channel, - CentrifugeSubscriptionConfig config, + SpinifySubscriptionConfig config, ); /// Publish data to channel. @@ -66,20 +66,20 @@ abstract interface class ISpinifyTransport { /// Fetch publication history inside a channel. /// Only for channels where history is enabled. /// {@nodoc} - Future history( + Future history( String channel, { int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }); /// Fetch presence information inside a channel. /// {@nodoc} - Future presence(String channel); + Future presence(String channel); /// Fetch presence stats information inside a channel. /// {@nodoc} - Future presenceStats(String channel); + Future presenceStats(String channel); /// Disconnect from the server. /// e.g. code: 0, reason: 'disconnect called' @@ -88,11 +88,11 @@ abstract interface class ISpinifyTransport { /// Send refresh token command to server. /// {@nodoc} - Future sendRefresh(String token); + Future sendRefresh(String token); /// Send subscription channel refresh token command to server. /// {@nodoc} - Future sendSubRefresh( + Future sendSubRefresh( String channel, String token, ); diff --git a/lib/src/transport/transport_protobuf_codec.dart b/lib/src/transport/transport_protobuf_codec.dart index d72c3f9..a1dfd5d 100644 --- a/lib/src/transport/transport_protobuf_codec.dart +++ b/lib/src/transport/transport_protobuf_codec.dart @@ -28,7 +28,6 @@ final class TransportProtobufEncoder extends Converter> { @override List convert(pb.GeneratedMessage input) { - // TODO(plugfox): Find out better way to encode. /* final buffer = pb.CodedBufferWriter(); input.writeToCodedBufferWriter(buffer); return buffer.toBuffer(); */ diff --git a/lib/src/transport/ws_protobuf_transport.dart b/lib/src/transport/ws_protobuf_transport.dart index ecd4233..78315a0 100644 --- a/lib/src/transport/ws_protobuf_transport.dart +++ b/lib/src/transport/ws_protobuf_transport.dart @@ -36,22 +36,22 @@ import 'package:ws/ws.dart'; /// {@nodoc} @internal -abstract base class CentrifugeWSPBTransportBase implements ISpinifyTransport { +abstract base class SpinifyWSPBTransportBase implements ISpinifyTransport { /// {@nodoc} - CentrifugeWSPBTransportBase({ + SpinifyWSPBTransportBase({ required SpinifyConfig config, }) : _config = config, _webSocket = WebSocketClient( WebSocketOptions.selector( js: () => WebSocketOptions.js( connectionRetryInterval: null, - protocols: _$protocolsCentrifugeProtobuf, + protocols: _$protocolsSpinifyProtobuf, timeout: config.timeout, useBlobForBinary: false, ), vm: () => WebSocketOptions.vm( connectionRetryInterval: null, - protocols: _$protocolsCentrifugeProtobuf, + protocols: _$protocolsSpinifyProtobuf, timeout: config.timeout, headers: config.headers, ), @@ -62,17 +62,17 @@ abstract base class CentrifugeWSPBTransportBase implements ISpinifyTransport { /// Protocols for websocket. /// {@nodoc} - static const List _$protocolsCentrifugeProtobuf = [ + static const List _$protocolsSpinifyProtobuf = [ 'centrifuge-protobuf' ]; - /// Centrifuge config. + /// Spinify config. /// {@nodoc} final SpinifyConfig _config; @override - final CentrifugeChangeNotifier events = - CentrifugeChangeNotifier(); + final SpinifyChangeNotifier events = + SpinifyChangeNotifier(); /// Init transport, override this method to add custom logic. /// {@nodoc} @@ -117,15 +117,15 @@ abstract base class CentrifugeWSPBTransportBase implements ISpinifyTransport { /// {@nodoc} @internal // ignore: lines_longer_than_80_chars -final class SpinifyWSPBTransport = CentrifugeWSPBTransportBase +final class SpinifyWSPBTransport = SpinifyWSPBTransportBase with - CentrifugeWSPBReplyMixin, - CentrifugeWSPBStateHandlerMixin, - CentrifugeWSPBSenderMixin, - CentrifugeWSPBConnectionMixin, - CentrifugeWSPBPingPongMixin, - CentrifugeWSPBSubscription, - CentrifugeWSPBHandlerMixin; + SpinifyWSPBReplyMixin, + SpinifyWSPBStateHandlerMixin, + SpinifyWSPBSenderMixin, + SpinifyWSPBConnectionMixin, + SpinifyWSPBPingPongMixin, + SpinifyWSPBSubscription, + SpinifyWSPBHandlerMixin; /// Stored completer for responses. /// {@nodoc} @@ -137,7 +137,7 @@ typedef _ReplyCompleter = ({ /// Mixin responsible for holding reply completers. /// {@nodoc} @internal -base mixin CentrifugeWSPBReplyMixin on CentrifugeWSPBTransportBase { +base mixin SpinifyWSPBReplyMixin on SpinifyWSPBTransportBase { /// Completers for messages by id. /// Contains timer for timeout and completer for response. /// {@nodoc} @@ -198,8 +198,8 @@ base mixin CentrifugeWSPBReplyMixin on CentrifugeWSPBTransportBase { /// Mixin responsible for sending data through websocket with protobuf. /// {@nodoc} @internal -base mixin CentrifugeWSPBSenderMixin - on CentrifugeWSPBTransportBase, CentrifugeWSPBReplyMixin { +base mixin SpinifyWSPBSenderMixin + on SpinifyWSPBTransportBase, SpinifyWSPBReplyMixin { /// Encoder protobuf commands to bytes. /// {@nodoc} static const Converter> _commandEncoder = @@ -223,7 +223,7 @@ base mixin CentrifugeWSPBSenderMixin await _sendCommand(command); final reply = await future; if (reply.hasError()) { - throw CentrifugeReplyException( + throw SpinifyReplyException( replyCode: reply.error.code, replyMessage: reply.error.message, temporary: reply.error.temporary, @@ -321,11 +321,11 @@ base mixin CentrifugeWSPBSenderMixin /// Mixin responsible for connection. /// {@nodoc} @internal -base mixin CentrifugeWSPBConnectionMixin +base mixin SpinifyWSPBConnectionMixin on - CentrifugeWSPBTransportBase, - CentrifugeWSPBSenderMixin, - CentrifugeWSPBStateHandlerMixin { + SpinifyWSPBTransportBase, + SpinifyWSPBSenderMixin, + SpinifyWSPBStateHandlerMixin { @override Future connect( String url, @@ -336,7 +336,7 @@ base mixin CentrifugeWSPBConnectionMixin await _webSocket.connect(url); final request = pb.ConnectRequest(); final token = await _config.getToken?.call(); - assert(token == null || token.length > 5, 'Centrifuge JWT is too short'); + assert(token == null || token.length > 5, 'Spinify JWT is too short'); if (token != null) request.token = token; final payload = await _config.getPayload?.call(); if (payload != null) request.data = payload; @@ -346,9 +346,9 @@ base mixin CentrifugeWSPBConnectionMixin // Add server-side subscriptions to connect request. { final subs = serverSubscriptionManager.subscriptions.values; - for (final CentrifugeServerSubscription( + for (final SpinifyServerSubscription( channel: String channel, - state: CentrifugeSubscriptionState(:recoverable, :since), + state: SpinifySubscriptionState(:recoverable, :since), ) in subs) { if (since == null) continue; final subRequest = pb.SubscribeRequest() @@ -363,7 +363,7 @@ base mixin CentrifugeWSPBConnectionMixin result = await _sendMessage(request, pb.ConnectResult()); } on Object catch (error, stackTrace) { Error.throwWithStackTrace( - CentrifugeConnectionException( + SpinifyConnectionException( message: 'Error while making connect request', error: error, ), @@ -378,12 +378,12 @@ base mixin CentrifugeWSPBConnectionMixin // Update server-side subscriptions. { - final subs = result.subs.entries.map((e) { + final subs = result.subs.entries.map((e) { final channel = e.key; final sub = e.value; final positioned = sub.hasPositioned() && sub.positioned; final recoverable = sub.hasRecoverable() && sub.recoverable; - return CentrifugeSubscribe( + return SpinifySubscribe( timestamp: now, channel: channel, positioned: positioned, @@ -398,7 +398,7 @@ base mixin CentrifugeWSPBConnectionMixin serverSubscriptionManager.upsert(subs); } - _setState(CentrifugeState$Connected( + _setState(SpinifyState$Connected( url: url, timestamp: now, client: result.hasClient() ? result.client : null, @@ -419,18 +419,18 @@ base mixin CentrifugeWSPBConnectionMixin } @override - Future sendRefresh(String token) { + Future sendRefresh(String token) { if (!_state.isConnected) throw StateError('Not connected'); return _sendMessage(pb.RefreshRequest()..token = token, pb.RefreshResult()) - .then( + .then( (result) { final state = _state; - if (state is CentrifugeState$Connected) { + if (state is SpinifyState$Connected) { final now = DateTime.now(); final expires = result.hasExpires() && result.expires && result.hasTtl(); final ttl = expires ? now.add(Duration(seconds: result.ttl)) : null; - _setState(CentrifugeState$Connected( + _setState(SpinifyState$Connected( url: state.url, timestamp: now, client: result.hasClient() ? result.client : null, @@ -443,7 +443,7 @@ base mixin CentrifugeWSPBConnectionMixin session: state.session, data: state.data, )); - return CentrifugeRefreshResult( + return SpinifyRefreshResult( expires: expires, ttl: ttl, ); @@ -458,8 +458,8 @@ base mixin CentrifugeWSPBConnectionMixin /// Handler for websocket states. /// {@nodoc} @internal -base mixin CentrifugeWSPBStateHandlerMixin - on CentrifugeWSPBTransportBase, CentrifugeWSPBReplyMixin { +base mixin SpinifyWSPBStateHandlerMixin + on SpinifyWSPBTransportBase, SpinifyWSPBReplyMixin { // Subscribe to websocket state after first connection. /// Subscription to websocket state. /// {@nodoc} @@ -467,11 +467,11 @@ base mixin CentrifugeWSPBStateHandlerMixin @override @nonVirtual - CentrifugeState get state => _state; + SpinifyState get state => _state; @protected @nonVirtual - CentrifugeState _state = CentrifugeState$Disconnected( + SpinifyState _state = SpinifyState$Disconnected( timestamp: DateTime.now(), closeCode: null, closeReason: 'Not connected yet', @@ -480,19 +480,18 @@ base mixin CentrifugeWSPBStateHandlerMixin /// {@nodoc} @override @nonVirtual - final CentrifugeChangeNotifier states = - CentrifugeChangeNotifier(); + final SpinifyChangeNotifier states = SpinifyChangeNotifier(); @override void _initTransport() { super._initTransport(); } - /// Change state of centrifuge client. + /// Change state of spinify client. /// {@nodoc} @protected @nonVirtual - void _setState(CentrifugeState state) { + void _setState(SpinifyState state) { if (state == _state) return; states.notify(_state = state); } @@ -503,14 +502,14 @@ base mixin CentrifugeWSPBStateHandlerMixin @pragma('dart2js:tryInline') void _handleWebSocketClosedStates(WebSocketClientState$Closed state) { _setState( - CentrifugeState$Disconnected( + SpinifyState$Disconnected( timestamp: DateTime.now(), closeCode: state.closeCode, closeReason: state.closeReason, ), ); _failAllReplies( - const CentrifugeReplyException( + const SpinifyReplyException( replyCode: 3000, replyMessage: 'Connection closed', temporary: true, @@ -525,7 +524,7 @@ base mixin CentrifugeWSPBStateHandlerMixin ServerSubscriptionManager serverSubscriptionManager, ) { // Change state to connecting before connection. - _setState(CentrifugeState$Connecting(url: url)); + _setState(SpinifyState$Connecting(url: url)); // Subscribe to websocket state after initialization. _webSocketClosedStateSubscription ??= _webSocket.stateChanges.closed.listen( _handleWebSocketClosedStates, @@ -537,7 +536,7 @@ base mixin CentrifugeWSPBStateHandlerMixin @override Future close() async { _webSocketClosedStateSubscription?.cancel().ignore(); - _setState(CentrifugeState$Closed()); + _setState(SpinifyState$Closed()); await super.close(); states.close(); } @@ -546,11 +545,11 @@ base mixin CentrifugeWSPBStateHandlerMixin /// Handler for websocket messages and decode protobuf. /// {@nodoc} @internal -base mixin CentrifugeWSPBHandlerMixin +base mixin SpinifyWSPBHandlerMixin on - CentrifugeWSPBTransportBase, - CentrifugeWSPBSenderMixin, - CentrifugeWSPBPingPongMixin { + SpinifyWSPBTransportBase, + SpinifyWSPBSenderMixin, + SpinifyWSPBPingPongMixin { /// Encoder protobuf commands to bytes. /// {@nodoc} static const Converter, Iterable> _replyDecoder = @@ -600,7 +599,7 @@ base mixin CentrifugeWSPBHandlerMixin @pragma('dart2js:tryInline') void _onPing() { _restartPingTimer(); - if (state case CentrifugeState$Connected(:bool? sendPong)) { + if (state case SpinifyState$Connected(:bool? sendPong)) { if (sendPong != true) return; _sendAsyncMessage(pb.PingRequest()).ignore(); logger.fine('Pong message sent'); @@ -622,7 +621,7 @@ base mixin CentrifugeWSPBHandlerMixin events.notify($publicationDecode(push.channel)(push.pub)); } else if (push.hasMessage()) { events.notify( - CentrifugeMessage( + SpinifyMessage( timestamp: now, channel: channel, data: push.message.hasData() ? push.message.data : const [], @@ -630,7 +629,7 @@ base mixin CentrifugeWSPBHandlerMixin ); } else if (push.hasJoin()) { events.notify( - CentrifugeJoin( + SpinifyJoin( timestamp: now, channel: channel, info: $decodeClientInfo(push.join.info), @@ -638,7 +637,7 @@ base mixin CentrifugeWSPBHandlerMixin ); } else if (push.hasLeave()) { events.notify( - CentrifugeLeave( + SpinifyLeave( timestamp: now, channel: channel, info: $decodeClientInfo(push.join.info), @@ -650,7 +649,7 @@ base mixin CentrifugeWSPBHandlerMixin final recoverable = push.subscribe.hasRecoverable() && push.subscribe.recoverable; events.notify( - CentrifugeSubscribe( + SpinifySubscribe( timestamp: now, channel: channel, positioned: positioned, @@ -665,7 +664,7 @@ base mixin CentrifugeWSPBHandlerMixin ); } else if (push.hasUnsubscribe()) { events.notify( - CentrifugeUnsubscribe( + SpinifyUnsubscribe( timestamp: now, channel: channel, code: push.unsubscribe.hasCode() ? push.unsubscribe.code : 0, @@ -677,7 +676,7 @@ base mixin CentrifugeWSPBHandlerMixin final expires = connect.hasExpires() && connect.expires && connect.hasTtl(); events.notify( - CentrifugeConnect( + SpinifyConnect( timestamp: now, channel: channel, data: push.message.hasData() ? push.message.data : const [], @@ -694,7 +693,7 @@ base mixin CentrifugeWSPBHandlerMixin ); } else if (push.hasDisconnect()) { events.notify( - CentrifugeDisconnect( + SpinifyDisconnect( timestamp: now, channel: channel, code: push.disconnect.hasCode() ? push.disconnect.code : 0, @@ -706,7 +705,7 @@ base mixin CentrifugeWSPBHandlerMixin ), ); } else if (push.hasRefresh()) { - events.notify(CentrifugeRefresh( + events.notify(SpinifyRefresh( timestamp: now, channel: channel, expires: push.refresh.hasExpires() && push.refresh.expires, @@ -724,21 +723,21 @@ base mixin CentrifugeWSPBHandlerMixin } } -/// Mixin responsible for centrifuge subscriptions. +/// Mixin responsible for spinify subscriptions. /// {@nodoc} @internal -base mixin CentrifugeWSPBSubscription - on CentrifugeWSPBTransportBase, CentrifugeWSPBSenderMixin { +base mixin SpinifyWSPBSubscription + on SpinifyWSPBTransportBase, SpinifyWSPBSenderMixin { @override Future subscribe( String channel, - CentrifugeSubscriptionConfig config, - CentrifugeStreamPosition? since, + SpinifySubscriptionConfig config, + SpinifyStreamPosition? since, ) async { if (!state.isConnected) { - throw CentrifugeSubscriptionException( + throw SpinifySubscriptionException( channel: channel, - message: 'Centrifuge client is not connected', + message: 'Spinify client is not connected', ); } final request = pb.SubscribeRequest() @@ -749,7 +748,7 @@ base mixin CentrifugeWSPBSubscription final token = await config.getToken?.call(); assert( token == null || token.length > 5, - 'Centrifuge Subscription JWT is too short', + 'Spinify Subscription JWT is too short', ); if (token != null && token.isNotEmpty) request.token = token; final data = await config.getPayload?.call(); @@ -774,7 +773,7 @@ base mixin CentrifugeWSPBSubscription rethrow; } on Object catch (error, stackTrace) { Error.throwWithStackTrace( - CentrifugeSubscriptionException( + SpinifySubscriptionException( channel: channel, message: 'Error while making subscribe request', error: error, @@ -786,9 +785,9 @@ base mixin CentrifugeWSPBSubscription final publicationDecoder = $publicationDecode(channel); final publications = result.publications.isEmpty ? _emptyPublicationsList - : UnmodifiableListView( + : UnmodifiableListView( result.publications - .map(publicationDecoder) + .map(publicationDecoder) .toList(growable: false), ); final recoverable = result.hasRecoverable() && result.recoverable; @@ -812,7 +811,7 @@ base mixin CentrifugeWSPBSubscription @override Future unsubscribe( String channel, - CentrifugeSubscriptionConfig config, + SpinifySubscriptionConfig config, ) async { if (_webSocket.state.readyState.isDisconnecting || _webSocket.state.readyState.isClosed) { @@ -831,10 +830,10 @@ base mixin CentrifugeWSPBSubscription pb.PublishResult()); @override - Future history( + Future history( String channel, { int? limit, - CentrifugeStreamPosition? since, + SpinifyStreamPosition? since, bool? reverse, }) async { final request = pb.HistoryRequest()..channel = channel; @@ -847,12 +846,12 @@ base mixin CentrifugeWSPBSubscription } final result = await _sendMessage(request, pb.HistoryResult()); final publicationDecoder = $publicationDecode(channel); - return CentrifugeHistory( + return SpinifyHistory( publications: result.publications.isEmpty ? _emptyPublicationsList - : UnmodifiableListView( + : UnmodifiableListView( result.publications - .map(publicationDecoder) + .map(publicationDecoder) .toList(growable: false), ), since: (epoch: result.epoch, offset: result.offset), @@ -860,15 +859,15 @@ base mixin CentrifugeWSPBSubscription } @override - Future presence(String channel) => + Future presence(String channel) => _sendMessage(pb.PresenceRequest()..channel = channel, pb.PresenceResult()) - .then( - (r) => CentrifugePresence( + .then( + (r) => SpinifyPresence( channel: channel, - clients: UnmodifiableMapView( - { + clients: UnmodifiableMapView( + { for (final e in r.presence.entries) - e.key: CentrifugeClientInfo( + e.key: SpinifyClientInfo( user: e.value.user, client: e.value.client, channelInfo: e.value.hasChanInfo() ? e.value.chanInfo : null, @@ -881,11 +880,11 @@ base mixin CentrifugeWSPBSubscription ); @override - Future presenceStats(String channel) => _sendMessage( + Future presenceStats(String channel) => _sendMessage( pb.PresenceStatsRequest()..channel = channel, pb.PresenceStatsResult()) - .then( - (r) => CentrifugePresenceStats( + .then( + (r) => SpinifyPresenceStats( channel: channel, clients: r.hasNumClients() ? r.numClients : 0, users: r.hasNumUsers() ? r.numUsers : 0, @@ -893,7 +892,7 @@ base mixin CentrifugeWSPBSubscription ); @override - Future sendSubRefresh( + Future sendSubRefresh( String channel, String token, ) => @@ -902,10 +901,10 @@ base mixin CentrifugeWSPBSubscription ..channel = channel ..token = token, pb.SubRefreshResult()) - .then( + .then( (r) { final expires = r.hasExpires() && r.expires && r.hasTtl(); - return CentrifugeSubRefreshResult( + return SpinifySubRefreshResult( expires: expires, ttl: expires ? DateTime.now().add(Duration(seconds: r.ttl)) : null, ); @@ -930,7 +929,7 @@ base mixin CentrifugeWSPBSubscription /// Usually a server sends pings every 25 seconds. /// {@nodoc} @internal -base mixin CentrifugeWSPBPingPongMixin on CentrifugeWSPBTransportBase { +base mixin SpinifyWSPBPingPongMixin on SpinifyWSPBTransportBase { @protected @nonVirtual Timer? _pingTimer; @@ -953,7 +952,7 @@ base mixin CentrifugeWSPBPingPongMixin on CentrifugeWSPBTransportBase { @nonVirtual void _restartPingTimer() { _tearDownPingTimer(); - if (state case CentrifugeState$Connected(:Duration pingInterval)) { + if (state case SpinifyState$Connected(:Duration pingInterval)) { _pingTimer = Timer( pingInterval + _config.serverPingDelay, () => disconnect( @@ -977,16 +976,16 @@ base mixin CentrifugeWSPBPingPongMixin on CentrifugeWSPBTransportBase { } /// {@nodoc} -final List _emptyPublicationsList = - List.empty(growable: false); +final List _emptyPublicationsList = + List.empty(growable: false); /// {@nodoc} @internal -CentrifugePublication Function(pb.Publication publication) $publicationDecode( +SpinifyPublication Function(pb.Publication publication) $publicationDecode( String channel, ) { final timestamp = DateTime.now(); - return (publication) => CentrifugePublication( + return (publication) => SpinifyPublication( timestamp: timestamp, channel: channel, offset: publication.hasOffset() ? publication.offset : null, @@ -999,8 +998,7 @@ CentrifugePublication Function(pb.Publication publication) $publicationDecode( /// {@nodoc} @internal -CentrifugeClientInfo $decodeClientInfo(pb.ClientInfo info) => - CentrifugeClientInfo( +SpinifyClientInfo $decodeClientInfo(pb.ClientInfo info) => SpinifyClientInfo( client: info.client, user: info.user, channelInfo: info.hasChanInfo() ? info.chanInfo : null, diff --git a/lib/src/util/event_queue.dart b/lib/src/util/event_queue.dart index d0c7bde..1bb6bfb 100644 --- a/lib/src/util/event_queue.dart +++ b/lib/src/util/event_queue.dart @@ -5,19 +5,19 @@ import 'package:meta/meta.dart'; /// {@nodoc} @internal -final class CentrifugeEventQueue { +final class SpinifyEventQueue { /// {@nodoc} - CentrifugeEventQueue(); + SpinifyEventQueue(); - final DoubleLinkedQueue> _queue = - DoubleLinkedQueue>(); + final DoubleLinkedQueue> _queue = + DoubleLinkedQueue>(); Future? _processing; bool _isClosed = false; /// Push it at the end of the queue. /// {@nodoc} Future push(String id, FutureOr Function() fn) { - final task = CentrifugeTask(id, fn); + final task = SpinifyTask(id, fn); _queue.add(task); _exec(); return task.future; @@ -62,9 +62,9 @@ final class CentrifugeEventQueue { /// {@nodoc} @internal -class CentrifugeTask { +class SpinifyTask { /// {@nodoc} - CentrifugeTask(this.id, FutureOr Function() fn) + SpinifyTask(this.id, FutureOr Function() fn) : _fn = fn, _completer = Completer(); diff --git a/lib/src/util/logger.dart b/lib/src/util/logger.dart index bfbae67..15695cf 100644 --- a/lib/src/util/logger.dart +++ b/lib/src/util/logger.dart @@ -3,16 +3,16 @@ import 'dart:developer' as developer; import 'package:meta/meta.dart'; -/// Constants used to debug the Centrifuge client. +/// Constants used to debug the Spinify client. /// --dart-define=dev.plugfox.ws.debug=true /// {@nodoc} @internal bool get $enableLogging => const bool.fromEnvironment( - 'dev.plugfox.centrifuge.log', + 'dev.plugfox.spinify.log', defaultValue: false, ) || - Zone.current[#dev.plugfox.centrifuge.log] == true; + Zone.current[#dev.plugfox.spinify.log] == true; /// Tracing information /// {@nodoc} @@ -52,7 +52,7 @@ void Function( developer.log( reason ?? message?.toString() ?? '', level: level, - name: 'centrifuge', + name: 'spinify', error: message is Exception || message is Error ? message : null, stackTrace: stackTrace, ); diff --git a/lib/src/util/notifier.dart b/lib/src/util/notifier.dart index 442d0d3..7ca4e3d 100644 --- a/lib/src/util/notifier.dart +++ b/lib/src/util/notifier.dart @@ -7,7 +7,7 @@ typedef ValueChanged = void Function(T value); /// Notify about value changes. /// {@nodoc} @internal -abstract interface class CentrifugeListenable { +abstract interface class SpinifyListenable { /// Add listener. /// {@nodoc} void addListener(ValueChanged listener); @@ -20,10 +20,10 @@ abstract interface class CentrifugeListenable { /// Notify about value changes. /// {@nodoc} @internal -final class CentrifugeChangeNotifier implements CentrifugeListenable { +final class SpinifyChangeNotifier implements SpinifyListenable { /// Notify about value changes. /// {@nodoc} - CentrifugeChangeNotifier(); + SpinifyChangeNotifier(); /// Notify about value changes. /// {@nodoc} diff --git a/test/unit/centrifuge_test.dart b/test/unit/spinify_test.dart similarity index 63% rename from test/unit/centrifuge_test.dart rename to test/unit/spinify_test.dart index 3806ca8..54429ba 100644 --- a/test/unit/centrifuge_test.dart +++ b/test/unit/spinify_test.dart @@ -1,13 +1,13 @@ import 'package:spinify/spinify.dart'; import 'package:test/test.dart'; -void main() => group('Centrifuge', () { +void main() => group('Spinify', () { const url = 'ws://localhost:8000/connection/websocket'; test('Connection', () async { final client = Spinify(); await client.connect(url); - expect(client.state, isA()); + expect(client.state, isA()); await client.disconnect(); - expect(client.state, isA()); + expect(client.state, isA()); }); }); diff --git a/test/unit_test.dart b/test/unit_test.dart index 39da9f7..2a41207 100644 --- a/test/unit_test.dart +++ b/test/unit_test.dart @@ -2,10 +2,10 @@ import 'package:test/test.dart'; -import 'unit/centrifuge_test.dart' as centrifuge_test; +import 'unit/spinify_test.dart' as spinify_test; void main() { group('Unit', () { - centrifuge_test.main(); + spinify_test.main(); }); }