import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:path/path.dart' as p; import 'diagnostic_redactor.dart'; /// Serializes bounded log writes, rotation and exports; failures remain observable /// in memory without interrupting editing or recursively logging themselves. final class DiagnosticStore { DiagnosticStore( this.directory, { this.maxFileBytes = 512 * 1024, this.fileCount = 5, this.maxPending = 256, this.flushInterval = const Duration(milliseconds: 250), this.batchSize = 32, this.maxBatchBytes = 64 * 1024, this.maxPendingBytes = 1024 * 1024, int? errorReserveRecords, int? errorReserveBytes, }) : errorReserveRecords = errorReserveRecords ?? maxPending ~/ 8, errorReserveBytes = errorReserveBytes ?? maxPendingBytes ~/ 4, assert( errorReserveRecords == null || (errorReserveRecords >= 0 && errorReserveRecords < maxPending), ), assert( errorReserveBytes == null || (errorReserveBytes >= 0 && errorReserveBytes < maxPendingBytes), ), assert(maxFileBytes >= 1024), assert(fileCount > 0), assert(maxPending > 0), assert(flushInterval > Duration.zero), assert(batchSize > 0), assert(maxBatchBytes > 0), assert(maxPendingBytes > 0); final Directory directory; final int maxFileBytes, fileCount, maxPending; final Duration flushInterval; final int batchSize, maxBatchBytes, maxPendingBytes; final int errorReserveRecords, errorReserveBytes; final _buffer = Queue<_DiagnosticRecord>(); Timer? _timer; int _bufferBytes = 0; int _pendingBytes = 0; int eventWriteBatches = 0; int eventFlushes = 0; int eventBytesWritten = 0; int get pendingRecords => _pending; int get pendingEventBytes => _pendingBytes; final _redactor = DiagnosticRedactor(); Future _tail = Future.value(); int _pending = 0; int dropped = 0; int droppedErrors = 0; int writeFailures = 0; String? lastWriteFailure; final List> _fallback = []; File _log(int index) => File(p.join(directory.path, 'events-$index.jsonl')); void record(Map record, {bool immediate = false}) { final isError = record['level'] == 'error'; final recordLimit = isError ? maxPending : maxPending - errorReserveRecords; final byteLimit = isError ? maxPendingBytes : maxPendingBytes - errorReserveBytes; // Non-error events and reports cannot consume reserved error capacity. // Saturated queues skip formatting; fatal errors bypass both limits. if (!immediate && (_pending >= recordLimit || _pendingBytes >= byteLimit)) { _drop(isError); return; } try { final safe = (_redactor.value(record)! as Map).cast(); final encoded = utf8.encode('${jsonEncode(safe)}\n'); if (encoded.length > maxFileBytes) { _drop(isError); return; } if (immediate) { try { directory.createSync(recursive: true); final fatal = File(p.join(directory.path, 'fatal.jsonl')); if (fatal.existsSync() && fatal.lengthSync() + encoded.length > maxFileBytes) { fatal.deleteSync(); } fatal.writeAsBytesSync(encoded, mode: FileMode.append, flush: true); } catch (error) { _failed([_DiagnosticRecord(safe, encoded)], error); } return; } if (_pendingBytes + encoded.length > byteLimit) { _drop(isError); return; } _pending++; _pendingBytes += encoded.length; _bufferBytes += encoded.length; _buffer.add(_DiagnosticRecord(safe, encoded)); if (_buffer.length >= batchSize || _bufferBytes >= maxBatchBytes) { _enqueueBuffered(); } else { _timer ??= Timer(flushInterval, _enqueueBuffered); } } catch (_) { _drop(isError); } } void _drop(bool isError) { dropped++; if (isError) droppedErrors++; } void _enqueueBuffered() { _timer?.cancel(); _timer = null; if (_buffer.isEmpty) return; final records = _buffer.toList(growable: false); _buffer.clear(); _bufferBytes = 0; _tail = _tail.then((_) => _writeBatch(records)); } Future _writeBatch(List<_DiagnosticRecord> records) async { eventWriteBatches++; var written = 0; try { await directory.create(recursive: true); while (written < records.length) { final current = _log(0); var length = 0; var interrupted = false; if (await current.exists()) { final reader = await current.open(); try { length = await reader.length(); if (length > 0) { await reader.setPosition(length - 1); interrupted = await reader.readByte() != 10; } } finally { await reader.close(); } } if (length + (interrupted ? 1 : 0) + records[written].encoded.length > maxFileBytes) { await _rotate(); length = 0; interrupted = false; } final bytes = BytesBuilder(copy: false); // Isolate an interrupted append from the next complete JSONL record. if (interrupted) bytes.addByte(10); var end = written; while (end < records.length) { final encoded = records[end].encoded; if (length + bytes.length + encoded.length > maxFileBytes || (end > written && bytes.length + encoded.length > maxBatchBytes)) { break; } bytes.add(encoded); end++; } final chunk = bytes.takeBytes(); await current.writeAsBytes(chunk, mode: FileMode.append, flush: true); eventFlushes++; eventBytesWritten += chunk.length; written = end; } } catch (error) { // A failed batch retains every unconfirmed record, with bounded fallback. _failed(records.skip(written), error); } finally { _pending -= records.length; _pendingBytes -= records.fold( 0, (size, record) => size + record.encoded.length, ); } } Future _rotate() async { final oldest = _log(fileCount - 1); if (await oldest.exists()) await oldest.delete(); for (var i = fileCount - 2; i >= 0; i--) { final file = _log(i); if (await file.exists()) await file.rename(_log(i + 1).path); } } void _failed(Iterable<_DiagnosticRecord> records, Object error) { lastWriteFailure = _redactor.text(error.toString()); for (final record in records) { writeFailures++; _fallback.add(record.safe); if (_fallback.length > 100) _fallback.removeAt(0); } } /// Drains buffered records and waits for writes already accepted by the store. Future flush() { _enqueueBuffered(); return _tail; } Future saveRequest(Map report, String requestId) { // UUID-only names prevent user text or paths from choosing a destination. if (!RegExp(r'^[a-fA-F0-9-]{36}$').hasMatch(requestId)) { return Future.value(); } if (_pending >= maxPending - errorReserveRecords) { dropped++; return Future.value(); } _enqueueBuffered(); _pending++; final operation = _tail.then((_) async { final requests = Directory(p.join(directory.path, 'requests')); try { await requests.create(recursive: true); final safe = _redactor.value(report); final encoded = jsonEncode(safe); if (utf8.encode(encoded).length > 256 * 1024) { dropped++; return; } final file = File( p.join( requests.path, '${DateTime.now().toUtc().microsecondsSinceEpoch}-$requestId.json', ), ); final temporary = File('${file.path}.tmp'); await temporary.writeAsString(encoded, flush: true); await temporary.rename(file.path); final files = await requests .list() .where((e) => e is File && e.path.endsWith('.json')) .cast() .toList(); files.sort((a, b) => a.path.compareTo(b.path)); if (files.length > 20) { for (final old in files.take(files.length - 20)) { await old.delete(); } } } catch (error) { writeFailures++; lastWriteFailure = _redactor.text(error.toString()); } finally { _pending--; } }); _tail = operation; return operation; } /// Exports only managed diagnostics, never project files or conversations. Future export(Directory destination, Map metadata) { _enqueueBuffered(); final completion = Completer(); _tail = _tail.then((_) async { try { final records = []; final logs = [ for (var i = fileCount - 1; i >= 0; i--) _log(i), File(p.join(directory.path, 'fatal.jsonl')), ]; for (final file in logs) { if (!await file.exists() || await file.length() > maxFileBytes) { continue; } for (final line in await file.readAsLines()) { try { records.add(_redactor.value(jsonDecode(line))); } catch (_) { // An interrupted append must not prevent exporting other records. } } } final reports = []; final requests = Directory(p.join(directory.path, 'requests')); if (await requests.exists()) { final files = await requests .list() .where((e) => e is File && e.path.endsWith('.json')) .cast() .toList(); files.sort((a, b) => b.path.compareTo(a.path)); for (final file in files.take(20)) { if (await file.length() > 256 * 1024) continue; try { reports.add( _redactor.value(jsonDecode(await file.readAsString())), ); } catch (_) {} } } await destination.create(recursive: true); final file = File( p.join( destination.path, 'cutdex-diagnostics-${DateTime.now().toUtc().microsecondsSinceEpoch}.json', ), ); final temporary = File('${file.path}.tmp'); await temporary.writeAsString( jsonEncode({ 'version': 1, 'exportedAt': DateTime.now().toUtc().toIso8601String(), 'metadata': _redactor.value(metadata), 'storage': { 'dropped': dropped, 'droppedErrors': droppedErrors, 'errorReserveRecords': errorReserveRecords, 'errorReserveBytes': errorReserveBytes, 'writeFailures': writeFailures, 'eventWriteBatches': eventWriteBatches, 'eventFlushes': eventFlushes, 'eventBytesWritten': eventBytesWritten, 'lastWriteFailure': lastWriteFailure, }, 'events': records, 'requests': reports, 'fallbackEvents': _fallback, }), flush: true, ); await temporary.rename(file.path); completion.complete(file); } catch (error, stack) { completion.completeError(error, stack); } }); return completion.future; } } final class _DiagnosticRecord { const _DiagnosticRecord(this.safe, this.encoded); final Map safe; final List encoded; }