insertEvent method

Future<bool> insertEvent(
  1. int tsMillis,
  2. String eventName,
  3. String payloadJson
)

Insert an event. Tries SQLite first, falls back to memory queue.

Implementation

Future<bool> insertEvent(
  int tsMillis,
  String eventName,
  String payloadJson,
) async {
  return await _lock.synchronized(() async {
    if (_dbAvailable) {
      final ok = await _sqliteStorage.insertEvent(
        tsMillis,
        eventName,
        payloadJson,
      );
      _syncStorageState();
      if (ok) return true;
      // DB write failed — mark unavailable and fall back
      _dbAvailable = false;
      dbLogger.warning(
        'EventStorageHandler: SQLite write failed, falling back to memory',
      );
    }

    if (!_dbAvailable && _shouldAttemptDbRecovery()) {
      _dbAvailable = await _sqliteStorage.open();
      _syncStorageState();
      if (_dbAvailable) {
        _recordDbOpenSuccess();
        // NOTE: Do NOT drain memory queue here. If readBatch() has already
        // snapshot memory events for an in-flight HTTP send, draining them
        // to SQLite would cause duplicates — the events would be sent once
        // from the HTTP payload and again from SQLite in the next flush.
        // Instead, readBatch() drains memory→DB at the start of each read,
        // which is safe because both happen within the same _lock scope.
        final ok = await _sqliteStorage.insertEvent(
          tsMillis,
          eventName,
          payloadJson,
        );
        _syncStorageState();
        if (ok) {
          return true;
        }
        _dbAvailable = false;
      } else {
        _recordDbOpenFailure();
      }
    }

    return _memoryQueue.enqueue(tsMillis, eventName, payloadJson);
  });
}