flushEventsBySession method
Fuerza el envío de eventos de una sesión específica Este método solo está disponible desde las debug tools
Implementation
Future<void> flushEventsBySession(String sessionId) async {
if (!_isStarted) return;
final initialEventCount = await _getInitialEventCount();
bool flushSuccessful = false;
String? errorMessage;
try {
final allEvents = await storage.getAllEvents();
final sessionEvents = allEvents.where((event) {
final eventSessionId = event['session_id'] ?? event['_session_id'];
return eventSessionId == sessionId;
}).toList();
if (sessionEvents.isEmpty) {
ObslyLogger.debug('No events found for session: $sessionId');
// Log flush completion (empty) usando FlushLogger
FlushLogger.instance.logFlushComplete(
trigger: 'session_flush',
forced: true,
eventCount: 0,
sendActive: _sendActive,
successful: true,
);
return;
}
ObslyLogger.debug('Flushing ${sessionEvents.length} events for session: $sessionId');
// Enviar eventos en lotes
const batchSize = 50;
int successfulBatches = 0;
int totalBatches = 0;
for (int i = 0; i < sessionEvents.length; i += batchSize) {
final batch = sessionEvents.skip(i).take(batchSize).toList();
totalBatches++;
try {
final eventsToSend = batch.map((e) => ObslyEvent.fromJson(e)).toList();
ObslyLogger.debug(
'[SESSION_FLUSH] Sending batch ${totalBatches}/${((sessionEvents.length / 50).ceil())} with ${eventsToSend.length} events');
final success = await sender.sendBatch(eventsToSend);
ObslyLogger.debug('[SESSION_FLUSH] Batch ${totalBatches} result: ${success ? 'SUCCESS' : 'FAILED'}');
if (success) {
successfulBatches++;
// Eliminar eventos enviados del storage
await storage.deleteEventsByMap(batch.cast<Map<String, dynamic>>());
ObslyLogger.debug('[SESSION_FLUSH] Batch ${totalBatches} events deleted from storage');
} else {
ObslyLogger.warn('[SESSION_FLUSH] Batch ${totalBatches} failed - events kept in storage');
}
} catch (e, stackTrace) {
ObslyLogger.error('[SESSION_FLUSH] Error sending batch ${totalBatches}: $e', e, stackTrace);
errorMessage ??= e.toString();
}
}
flushSuccessful = successfulBatches == totalBatches;
ObslyLogger.debug('Session flush completed: ${successfulBatches}/${totalBatches} batches successful');
// Log flush completion usando FlushLogger
FlushLogger.instance.logFlushComplete(
trigger: 'session_flush',
forced: true,
eventCount: sessionEvents.length,
sendActive: _sendActive,
successful: flushSuccessful,
errorMessage: errorMessage,
);
} catch (e, stackTrace) {
ObslyLogger.error('Error flushing events for session $sessionId: $e', e, stackTrace);
errorMessage = e.toString();
// Log flush error usando FlushLogger
FlushLogger.instance.logFlushComplete(
trigger: 'session_flush',
forced: true,
eventCount: initialEventCount,
sendActive: _sendActive,
successful: false,
errorMessage: errorMessage,
);
}
}