Files
pipelines/app/lib/features/runs/domain/run_deletion.dart
T
alan 266916f92a Runs: multi-select delete, run sizes and Largest-first sort
- Select mode (bar Select or long-press): per-row checkboxes, per-day
  Select all/Deselect all over finished runs only, "N selected" with the
  selection size, Delete and Done. Active runs get a disabled checkbox
  whose semantics give the reason.
- Native destructive confirmation, then delete_runs {run_ids} (batched by
  1000); the nested runs_deleted reply removes deleted rows and reports
  "Deleted N runs, freed X" plus refusals verbatim. runs_removed pushes
  remove rows and close an open detail; a deleted open run closes too.
  Delete run in the row and detail menus.
- size_bytes shown compactly in rows (0/absent = unknown, nothing shown),
  updated from run_event frames that carry it; Largest first sort (flat,
  unknowns last); the sort choice persists.
- Shared AppListRow gains selectionControl and onLongPress.
- Browser probe tool/runs_delete_probe.mjs; fixture server implements
  delete_runs/runs_removed.
2026-10-31 22:19:36 +00:00

181 lines
6.0 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<JsonMap> 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<JsonMap> 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<int> deletableRunIds(Iterable<JsonMap> 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<String, dynamic>.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<Map>())
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<int> deleted;
final List<RunDeleteRefusal> 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 = <String>[];
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<int> 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;
}