import '../../../core/api_gateway.dart'; import 'run_models.dart' show runStateOf; /// Run deletion and disk-size rules. No widgets here. /// The states a run can be deleted in: it has finished one way or another. const _terminalStates = {'succeeded', 'failed', 'canceled', 'interrupted'}; /// Why an active run cannot be selected or deleted, for its disabled control. const runDeleteBlockedReason = 'Active runs can’t be deleted until they finish.'; /// Whether [run] has finished, so its recorded data may be deleted. A run /// still executing (running, waiting, queued, pending) never qualifies, nor /// does one whose status the client does not recognise. bool runIsDeletable(JsonMap run) => run['id'] is int && run['executing'] != true && _terminalStates.contains(runStateOf(run['status'])); /// The run's recorded size on disk, or null when it is unknown: older servers /// omit `size_bytes`, and the server sends 0 for "not measured yet". int? runSizeBytes(JsonMap run) { final value = run['size_bytes']; if (value is int && value > 0) return value; if (value is num && value > 0 && value.isFinite) return value.round(); return null; } /// A compact human size: `512 B`, `4.2 KB`, `340 MB`, `1.2 GB`. /// /// Binary multiples, one decimal below ten units, whole units above. String formatByteSize(int bytes) { if (bytes < 1024) return '$bytes B'; const units = ['KB', 'MB', 'GB', 'TB', 'PB']; var value = bytes / 1024; var unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; } // Rounding 1023.6 MB up would print "1024 MB"; promote it instead. if (value >= 1023.5 && unit < units.length - 1) { value /= 1024; unit++; } final text = value < 9.95 ? value.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '') : value.round().toString(); return '$text ${units[unit]}'; } /// The known total of [runs]' sizes, and whether any size was unknown. ({int bytes, int unknown}) runsSizeTotal(Iterable runs) { var bytes = 0; var unknown = 0; for (final run in runs) { final size = runSizeBytes(run); if (size == null) { unknown++; } else { bytes += size; } } return (bytes: bytes, unknown: unknown); } /// The selection's size for its summary, or null when no size is known. String? runsSizeLabel(Iterable runs) { final total = runsSizeTotal(runs); if (total.bytes == 0 && total.unknown > 0) return null; final size = formatByteSize(total.bytes); return total.unknown > 0 ? '$size + unknown' : size; } String _runs(int count) => count == 1 ? '1 run' : '$count runs'; String deleteRunsTitle(int count) => 'Delete ${_runs(count)}?'; /// The confirmation's body. The freed amount is omitted when no size is known. String deleteRunsMessage(int count, {String? size}) { final whose = count == 1 ? 'its' : 'their'; final frees = size == null ? '' : ' and frees about $size'; return 'This removes $whose artifacts, documents and history$frees. ' 'This can’t be undone.'; } /// The deleted run ids are drawn from selected runs that can be deleted, in /// list order. List deletableRunIds(Iterable runs) => [ for (final run in runs) if (runIsDeletable(run)) run['id'] as int, ]; /// One run the server kept, in its own words. typedef RunDeleteRefusal = ({int runId, String reason}); /// The server's `runs_deleted` reply. class RunsDeletion { const RunsDeletion({ required this.deleted, this.refused = const [], this.freedBytes, }); /// Parses the reply envelope, whose result is nested under `runs_deleted`, /// or returns null when it is not a deletion reply. static RunsDeletion? fromReply(JsonMap reply) { final body = reply['runs_deleted']; return body is Map ? fromBody(Map.from(body)) : null; } /// Parses the nested `{deleted, refused, freed_bytes}` result. static RunsDeletion? fromBody(JsonMap reply) { final deleted = reply['deleted']; if (deleted is! List) return null; final refused = reply['refused']; final freed = reply['freed_bytes']; return RunsDeletion( deleted: [for (final id in deleted) ?_intId(id)], refused: [ if (refused is List) for (final entry in refused.whereType()) if (_intId(entry['run_id']) case final id?) (runId: id, reason: '${entry['reason'] ?? ''}'.trim()), ], freedBytes: freed is num && freed >= 0 ? freed.round() : null, ); } final List deleted; final List refused; final int? freedBytes; /// Combines the replies of consecutive batches into one outcome. RunsDeletion merge(RunsDeletion other) => RunsDeletion( deleted: [...deleted, ...other.deleted], refused: [...refused, ...other.refused], freedBytes: freedBytes == null && other.freedBytes == null ? null : (freedBytes ?? 0) + (other.freedBytes ?? 0), ); /// `Deleted 3 runs, freed 1.2 GB.` and one line per refused run. String get report { final lines = []; if (deleted.isNotEmpty || refused.isEmpty) { final freed = freedBytes == null ? '' : ', freed ${formatByteSize(freedBytes!)}'; lines.add('Deleted ${_runs(deleted.length)}$freed.'); } if (refused.isNotEmpty) { lines.add( refused.length == 1 ? '1 run was not deleted:' : '${refused.length} runs were not deleted:', ); for (final refusal in refused) { final reason = refusal.reason.isEmpty ? 'refused by the server' : refusal.reason; lines.add('Run ${refusal.runId}: $reason'); } } return lines.join('\n'); } } /// The ids a `runs_removed` broadcast names. List removedRunIds(JsonMap frame) { final ids = frame['run_ids']; return ids is List ? [for (final id in ids) ?_intId(id)] : const []; } int? _intId(dynamic value) { if (value is int) return value; if (value is num && value == value.roundToDouble()) return value.toInt(); return null; }