readHeader method

Future<SessionHeader> readHeader()

Reads the session header (first line) only — the metadata an open needs without touching the record body. The prefix read doubles from 4 KiB so a normal open moves a few KiB, never the file.

Implementation

Future<SessionHeader> readHeader() async {
  final info = await stat();
  if (info == null) {
    throw SessionException(
      'Session not found: $path',
      code: SessionErrorCode.notFound,
    );
  }
  const maxPrefix = 64 << 10;
  var prefix = info.size < 4 << 10 ? info.size : 4 << 10;
  List<(int, Uint8List)> lines = const [];
  while (true) {
    final bytes = await _readRange(0, prefix);
    lines = _splitLines(bytes, 0);
    if (lines.isNotEmpty || info.size <= prefix) break;
    prefix *= 4; // header line longer than the prefix: keep doubling
    if (prefix > maxPrefix) prefix = info.size; // last resort: full read
  }
  if (lines.isEmpty) {
    throw SessionException(
      'Missing session header: $path',
      code: SessionErrorCode.invalidSession,
    );
  }
  return parseSessionHeaderLine(utf8.decode(lines.first.$2), path);
}