archiveOldServices method

Future<void> archiveOldServices(
  1. Iterable<ServiceOfJournal> currentState
)

This function move old finished(and outDated) services to Hive box with name archiveHiveName.

There are two reason to archive services, first - we want active hiveBox small and fast on all devices, second - we want worker to only see today's services, and services which didn't committed yet(stale/rejected).

Archive is only for committed services. Only hiveArchiveLimit number of services could be stored in archive, the oldest services will be deleted first.

Implementation

Future<void> archiveOldServices(
    Iterable<ServiceOfJournal> currentState) async {
  //
  // > open hive archive and add old services
  //
  openArchiveHive.whenData((hiveArchive) async {
    final toDay = DateTime.now().dateOnly();
    final forDelete = currentState
        .whereNot((element) => element.provDate.dateOnly() == toDay);
    final forArchive = forDelete.map((e) => e.copyWith());
    if (forArchive.isNotEmpty) {
      await hiveArchive.addAll(forArchive); // check duplicates error
      //
      // > keep only [archiveLimit] number of services, delete oldest and close
      //
      // todo: check if hiveArch always place new services last,
      //  in that case we can just use deleteAt()
      final archList = hiveArchive.values.toList()
        ..sort((a, b) => a.provDate.compareTo(b.provDate))
        ..reversed;
      final archiveLimit = ref.read(journalArchiveSizeProvider);
      if (hiveArchive.length > archiveLimit) {
        //
        // > delete all services after archList[archiveLimit]
        //
        await hiveArchive.deleteAll(
          archList.slice(archiveLimit).map<dynamic>((e) => e.key),
        );
      }
      await hiveArchive.compact();
      //
      // > update datesInArchive
      //
      openArchiveHive.whenData((hiveArchive) {
        ref.read(daysWithServicesProvider(apiKey).notifier).state =
            hiveArchive.values
                .map((element) => element.provDate)
                .map((e) => e.dateOnly())
                .toSet();
      });
      ref.invalidate(archiveReaderProvider(apiKey));
      //
      // > update hive
      //
      openHive.whenData((hive) async {
        await hive.clear();
        await hive.addAll(state);
      });
    }
  });
}