Files
pipelines/app/lib/features/runs/domain/run_events.dart
T
alan 3b996bdbc7 Share one minute clock across time labels and narrow shell and runs rebuilds
Relative-time labels follow one wall-minute RelativeTimeClock instead of a
timer per row, skip ticks while their tab is offstage and rebuild only when
their text changes. The shell rebuilds its top bar only for the focused
destination's published bar and its tab bar only for badge changes. Run
events that repeat a row's state no longer notify, and the runs list filters
and sorts once per build. Adds a rebuild/timer benchmark.
2026-11-01 23:29:39 +00:00

243 lines
8.5 KiB
Dart

import '../../../core/api_gateway.dart';
import 'run_step_evidence.dart';
const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'};
bool isTerminalRunStatus(dynamic status) =>
terminalRunStatuses.contains(_word(status));
bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting';
int runLifecycleRank(dynamic status) => switch (_word(status)) {
'queued' => 0,
'running' || 'waiting' => 1,
'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2,
_ => -1,
};
int stepLifecycleRank(dynamic status) => switch (_word(status)) {
'running' || 'waiting' => 1,
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
_ => -1,
};
bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) {
if (_word(incoming).isEmpty) return false;
final oldRank = rank(current);
final newRank = rank(incoming);
return oldRank >= 0 &&
newRank >= 0 &&
(newRank < oldRank ||
(oldRank == 2 && newRank == 2 && incoming != current));
}
String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) {
if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}';
final oldRank = rank(current);
final newRank = rank(incoming);
if (oldRank < 0) return '$incoming';
if (newRank < 0 || (oldRank == 2 && newRank == 2) || newRank < oldRank) {
return '${current ?? ''}';
}
return '$incoming';
}
bool executingFor(dynamic status, bool current) => switch (_word(status)) {
'queued' || 'running' => true,
'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false,
_ => current,
};
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
JsonMap _scheduleOrigin(JsonMap current, JsonMap frame) {
final oldId = _positiveInt(current['schedule_id']);
final newId = _positiveInt(frame['schedule_id']);
final known =
current.containsKey('scheduled') ||
frame.containsKey('scheduled') ||
oldId > 0 ||
newId > 0;
if (!known) return {};
final id = oldId > 0 ? oldId : newId;
final nameConflict = oldId > 0 && newId > 0 && oldId != newId;
final name =
'${current['schedule_name'] ?? (nameConflict ? '' : frame['schedule_name'] ?? '')}';
return {
'scheduled':
current['scheduled'] == true || frame['scheduled'] == true || id > 0,
if (id > 0) 'schedule_id': id,
if (name.isNotEmpty) 'schedule_name': name,
};
}
int _positiveInt(dynamic value) =>
value is num && value > 0 ? value.toInt() : 0;
JsonMap _mergeRunFields(JsonMap current, JsonMap frame) {
if (_stale(current['status'], frame['status'], runLifecycleRank) &&
frame['resource_wait_set'] != true) {
return current;
}
final beforeStatus = '${current['status'] ?? ''}';
final status =
frame['resource_wait_set'] == true &&
frame['status'] == 'queued' &&
!isTerminalRunStatus(beforeStatus)
? 'queued'
: _advance(beforeStatus, frame['status'], runLifecycleRank);
final merged = <String, dynamic>{
...current,
..._scheduleOrigin(current, frame),
'status': status,
'executing': executingFor(status, current['executing'] == true),
'completed_steps': _maxInt(
current['completed_steps'],
frame['completed_steps'],
),
'resource_wait': isTerminalRunStatus(status)
? null
: frame['resource_wait_set'] == true
? frame['resource_wait']
: current['resource_wait'],
'notify_mode': _blank(frame['notify_mode'])
? current['notify_mode'] ?? 'auto'
: frame['notify_mode'],
'cancel_requested':
current['cancel_requested'] == true ||
frame['cancel_requested'] == true,
'cleanup_unconfirmed':
current['cleanup_unconfirmed'] == true ||
frame['cleanup_unconfirmed'] == true,
};
for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) {
if (!_blank(frame[key])) merged[key] = frame[key];
}
// Snapshot and terminal frames carry the measured size; others omit it.
if (frame['size_bytes'] is num) merged['size_bytes'] = frame['size_bytes'];
final oldExport = _positiveInt(current['export_pending_sequence']);
if (oldExport > 0 || frame.containsKey('export_pending_sequence')) {
merged['export_pending_sequence'] = _blank(frame['status'])
? oldExport
: status == 'waiting'
? _positiveInt(frame['export_pending_sequence'])
: 0;
}
if (current['steps'] is! List) {
final evidence = mergeGraphEvidence(
current['graph_evidence'] as JsonMap?,
frame,
);
if (evidence != null) merged['graph_evidence'] = evidence;
}
return merged;
}
int _maxInt(dynamic a, dynamic b) =>
(a is num ? a.toInt() : 0).clamp(b is num ? b.toInt() : 0, 0x7fffffff);
/// A summary row can be built from a sufficiently identified push; otherwise
/// the caller must resync from the server's authoritative list.
JsonMap? newRunSummaryFromFrame(JsonMap frame) {
final id = frame['run_id'];
final pipelineId = frame['pipeline_id'];
if (id is! num ||
id <= 0 ||
pipelineId is! num ||
pipelineId <= 0 ||
_blank(frame['name'])) {
return null;
}
final row = <String, dynamic>{
'id': id,
'pipeline_id': pipelineId,
'name': frame['name'],
'title': _blank(frame['title']) ? null : frame['title'],
'version': frame['version'] ?? 0,
'notify_mode': frame['notify_mode'] ?? 'auto',
'status': frame['status'] ?? '',
'executing': executingFor(frame['status'], true),
'completed_steps': _maxInt(0, frame['completed_steps']),
'created_at': frame['created_at'] ?? '',
'finished_at': frame['finished_at'] ?? '',
'outcome': frame['outcome'] ?? '',
'current_stage': frame['current_stage'] ?? '',
'resource_wait': frame['resource_wait'],
'cancel_requested': frame['cancel_requested'] == true,
'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true,
};
row.addAll(_scheduleOrigin({}, frame));
final sequence = _positiveInt(frame['export_pending_sequence']);
if (sequence > 0) row['export_pending_sequence'] = sequence;
final evidence = mergeGraphEvidence(null, frame);
if (evidence != null) row['graph_evidence'] = evidence;
return row;
}
({List<JsonMap> runs, bool needsResync}) foldRunEvent(
List<JsonMap> runs,
JsonMap frame,
) {
final id = frame['run_id'];
if (id is! num || id <= 0) return (runs: runs, needsResync: false);
final index = runs.indexWhere((run) => run['id'] == id);
if (index < 0) {
final row = newRunSummaryFromFrame(frame);
return row == null
? (runs: runs, needsResync: true)
: (runs: [row, ...runs], needsResync: false);
}
final updated = _mergeRunFields(runs[index], frame);
// A frame that repeats the row's state (a busy run's progress stream)
// keeps the same list, so its holders can skip a rebuild.
if (identical(updated, runs[index]) || _sameFields(updated, runs[index])) {
return (runs: runs, needsResync: false);
}
final next = [...runs];
next[index] = updated;
return (runs: next, needsResync: false);
}
/// Shallow equality: nested values compare by identity, so a rebuilt nested
/// map counts as a change.
bool _sameFields(JsonMap a, JsonMap b) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
if (!b.containsKey(entry.key) || b[entry.key] != entry.value) return false;
}
return true;
}
JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) {
if (detail == null || detail['id'] != frame['run_id']) return detail;
if (_stale(detail['status'], frame['status'], runLifecycleRank) &&
frame['resource_wait_set'] != true) {
return detail;
}
final merged = _mergeRunFields(detail, frame);
final steps = frame['step'] is Map
? upsertRunStep(
detail['steps'] is List
? (detail['steps'] as List)
.whereType<Map>()
.map((s) => Map<String, dynamic>.from(s))
.toList()
: [],
Map<String, dynamic>.from(frame['step'] as Map),
)
: detail['steps'] ?? [];
return {...merged, 'steps': steps};
}
bool runDetailNeedsFullSync(JsonMap frame) {
final step = frame['step'];
final stepStatus = step is Map ? step['status'] : null;
return isTerminalRunStatus(frame['status']) ||
isWaitingRunStatus(frame['status']) ||
frame['cancel_requested'] == true ||
frame['cleanup_unconfirmed'] == true ||
isWaitingRunStatus(stepStatus) ||
stepLifecycleRank(stepStatus) == 2;
}
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();