refactor: app startup improvements

This commit is contained in:
cogwheel0
2025-09-23 13:43:01 +05:30
parent 8da8a78001
commit f6a1b6123b
10 changed files with 1153 additions and 214 deletions

View File

@@ -12,6 +12,9 @@ class ConnectivityService {
final _connectivityController =
StreamController<ConnectivityStatus>.broadcast();
ConnectivityStatus _lastStatus = ConnectivityStatus.checking;
int _recentFailures = 0;
Duration _interval = const Duration(seconds: 10);
int _lastLatencyMs = -1;
ConnectivityService(this._dio) {
_startConnectivityMonitoring();
@@ -20,6 +23,7 @@ class ConnectivityService {
Stream<ConnectivityStatus> get connectivityStream =>
_connectivityController.stream;
ConnectivityStatus get currentStatus => _lastStatus;
int get lastLatencyMs => _lastLatencyMs;
/// Stream that emits true when connected, false when offline
Stream<bool> get isConnected =>
@@ -30,12 +34,12 @@ class ConnectivityService {
void _startConnectivityMonitoring() {
// Initial check after a brief delay to avoid showing offline during startup
Timer(const Duration(milliseconds: 1000), () {
Timer(const Duration(milliseconds: 800), () {
_checkConnectivity();
});
// Check periodically; balance responsiveness with battery/network usage
_connectivityTimer = Timer.periodic(const Duration(seconds: 10), (_) {
// Check periodically; interval adapts to recent failures
_connectivityTimer = Timer.periodic(_interval, (_) {
_checkConnectivity();
});
}
@@ -45,7 +49,7 @@ class ConnectivityService {
// DNS lookup is a lightweight, permission-free reachability check
final result = await InternetAddress.lookup(
'google.com',
).timeout(const Duration(seconds: 3));
).timeout(const Duration(seconds: 2));
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
_updateStatus(ConnectivityStatus.online);
@@ -57,20 +61,23 @@ class ConnectivityService {
// As a secondary check, hit a public 204 endpoint that returns quickly
try {
final start = DateTime.now();
await _dio
.get(
'https://www.google.com/generate_204',
options: Options(
method: 'GET',
sendTimeout: const Duration(seconds: 3),
receiveTimeout: const Duration(seconds: 3),
sendTimeout: const Duration(seconds: 2),
receiveTimeout: const Duration(seconds: 2),
followRedirects: false,
validateStatus: (status) => status != null && status < 400,
),
)
.timeout(const Duration(seconds: 3));
.timeout(const Duration(seconds: 2));
_lastLatencyMs = DateTime.now().difference(start).inMilliseconds;
_updateStatus(ConnectivityStatus.online);
} catch (_) {
_lastLatencyMs = -1;
_updateStatus(ConnectivityStatus.offline);
}
}
@@ -80,6 +87,28 @@ class ConnectivityService {
_lastStatus = status;
_connectivityController.add(status);
}
// Adapt polling interval based on recent failures to reduce battery/CPU
if (status == ConnectivityStatus.offline) {
_recentFailures = (_recentFailures + 1).clamp(0, 10);
} else if (status == ConnectivityStatus.online) {
_recentFailures = 0;
}
final newInterval = _recentFailures >= 3
? const Duration(seconds: 20)
: _recentFailures == 2
? const Duration(seconds: 15)
: const Duration(seconds: 10);
if (newInterval != _interval) {
_interval = newInterval;
_connectivityTimer?.cancel();
_connectivityTimer = Timer.periodic(
_interval,
(_) => _checkConnectivity(),
);
}
}
Future<bool> checkConnectivity() async {

View File

@@ -4,18 +4,19 @@ import '../models/server_config.dart';
class SocketService {
final ServerConfig serverConfig;
final String? authToken;
final bool websocketOnly;
io.Socket? _socket;
String? _authToken;
SocketService({
required this.serverConfig,
required this.authToken,
String? authToken,
this.websocketOnly = false,
});
}) : _authToken = authToken;
String? get sessionId => _socket?.id;
io.Socket? get socket => _socket;
String? get authToken => _authToken;
bool get isConnected => _socket?.connected == true;
@@ -39,9 +40,7 @@ class SocketService {
final builder = io.OptionBuilder()
// Transport selection
.setTransports(
websocketOnly ? ['websocket'] : ['polling', 'websocket'],
)
.setTransports(websocketOnly ? ['websocket'] : ['polling', 'websocket'])
.setRememberUpgrade(!websocketOnly)
.setUpgrade(!websocketOnly)
// Tune reconnect/backoff and timeouts
@@ -55,9 +54,9 @@ class SocketService {
// Merge Authorization (if any) with user-defined custom headers for the
// Socket.IO handshake. Avoid overriding reserved headers.
final Map<String, String> extraHeaders = {};
if (authToken != null && authToken!.isNotEmpty) {
extraHeaders['Authorization'] = 'Bearer $authToken';
builder.setAuth({'token': authToken});
if (_authToken != null && _authToken!.isNotEmpty) {
extraHeaders['Authorization'] = 'Bearer $_authToken';
builder.setAuth({'token': _authToken});
}
if (serverConfig.customHeaders.isNotEmpty) {
final reserved = {
@@ -78,7 +77,8 @@ class SocketService {
final lower = key.toLowerCase();
if (!reserved.contains(lower) && value.isNotEmpty) {
// Do not overwrite Authorization we already set from authToken
if (lower == 'authorization' && extraHeaders.containsKey('Authorization')) {
if (lower == 'authorization' &&
extraHeaders.containsKey('Authorization')) {
return;
}
extraHeaders[key] = value;
@@ -93,9 +93,9 @@ class SocketService {
_socket!.on('connect', (_) {
debugPrint('Socket connected: ${_socket!.id}');
if (authToken != null && authToken!.isNotEmpty) {
if (_authToken != null && _authToken!.isNotEmpty) {
_socket!.emit('user-join', {
'auth': {'token': authToken}
'auth': {'token': _authToken},
});
}
});
@@ -110,10 +110,10 @@ class SocketService {
_socket!.on('reconnect', (attempt) {
debugPrint('Socket reconnected after $attempt attempts');
if (authToken != null && authToken!.isNotEmpty) {
if (_authToken != null && _authToken!.isNotEmpty) {
// Best-effort rejoin
_socket!.emit('user-join', {
'auth': {'token': authToken}
'auth': {'token': _authToken},
});
}
});
@@ -127,6 +127,21 @@ class SocketService {
});
}
/// Update the auth token used by the socket service.
/// If connected, emits a best-effort rejoin with the new token.
void updateAuthToken(String? token) {
_authToken = token;
if (_socket?.connected == true &&
_authToken != null &&
_authToken!.isNotEmpty) {
try {
_socket!.emit('user-join', {
'auth': {'token': _authToken},
});
} catch (_) {}
}
}
void onChatEvents(void Function(Map<String, dynamic> event) handler) {
_socket?.on('chat-events', (data) {
try {
@@ -168,6 +183,7 @@ class SocketService {
void offEvent(String eventName) {
_socket?.off(eventName);
}
void dispose() {
try {
_socket?.dispose();
@@ -177,7 +193,9 @@ class SocketService {
// Best-effort: ensure there is an active connection and wait briefly.
// Returns true if connected by the end of the timeout.
Future<bool> ensureConnected({Duration timeout = const Duration(seconds: 2)}) async {
Future<bool> ensureConnected({
Duration timeout = const Duration(seconds: 2),
}) async {
if (isConnected) return true;
try {
await connect();