224 lines
7.9 KiB
Dart
224 lines
7.9 KiB
Dart
import '../../../../core/api_gateway.dart';
|
|
import '../saved_schedule.dart';
|
|
import '../schedule_rule.dart';
|
|
|
|
/// Which half of the timer rule the editor is writing.
|
|
enum ScheduleTimerMode { interval, clock }
|
|
|
|
/// Either a ready-to-send `save_schedule` record or field errors keyed by the
|
|
/// draft field the control binds to. [record] is null when any field fails, so
|
|
/// an invalid draft can never be mistaken for a save payload.
|
|
class ScheduleSaveResult {
|
|
ScheduleSaveResult(this.record, this.errors);
|
|
|
|
final JsonMap? record;
|
|
final Map<String, String> errors;
|
|
|
|
bool get isValid => record != null;
|
|
}
|
|
|
|
/// Core editor state for one saved schedule, mirroring the web editor draft.
|
|
///
|
|
/// Pure draft only: no network, timer calculation or timezone conversion.
|
|
/// [build] mirrors `serializeSchedule` in `web/src/schedules.js` for name,
|
|
/// prompt, pinned version, server workspace, timer rule, weekdays and
|
|
/// timezone. It starts from a deep copy of the server record, so unknown
|
|
/// record/input/rule/run-option fields and the exact revision survive an edit.
|
|
class ScheduleDraft {
|
|
ScheduleDraft._(this.source, this.pipelineId);
|
|
|
|
/// The record this draft edits; null for a create.
|
|
final SavedSchedule? source;
|
|
final int? pipelineId;
|
|
|
|
String name = '';
|
|
String prompt = '';
|
|
String version = '';
|
|
String workspace = '';
|
|
bool enabled = true;
|
|
ScheduleTimerMode mode = ScheduleTimerMode.interval;
|
|
String every = '24h';
|
|
String times = '';
|
|
List<String> days = [];
|
|
String timezone = '';
|
|
String notifyMode = 'auto';
|
|
|
|
/// New schedule: the server's create sentinel is `id: 0` with no revision.
|
|
factory ScheduleDraft.create({
|
|
required int pipelineId,
|
|
String version = '',
|
|
String workspace = '',
|
|
String timezone = '',
|
|
}) => ScheduleDraft._(null, pipelineId)
|
|
..version = version
|
|
..workspace = workspace
|
|
..timezone = timezone;
|
|
|
|
/// Existing record: every field starts from the server value, never from a
|
|
/// default that could overwrite it.
|
|
factory ScheduleDraft.fromSchedule(SavedSchedule s, {int? pipelineId}) {
|
|
final rule = s.rule;
|
|
return ScheduleDraft._(s, s.pipelineId ?? pipelineId)
|
|
..name = s.name
|
|
..prompt = s.prompt
|
|
..version = s.version?.toString() ?? ''
|
|
..workspace = s.workspace
|
|
..enabled = s.raw['enabled'] is bool ? s.enabled : true
|
|
..mode = rule.isClock
|
|
? ScheduleTimerMode.clock
|
|
: ScheduleTimerMode.interval
|
|
..every = rule.raw['every'] is String ? rule.every : '24h'
|
|
..times = rule.times.join(', ')
|
|
..days = [...rule.days]
|
|
..timezone = rule.timezone
|
|
..notifyMode = s.raw['notify_mode'] is String ? s.notifyMode : 'auto';
|
|
}
|
|
|
|
/// Validates every field and assembles the exact `save_schedule` record.
|
|
/// The draft and the source snapshot are never mutated.
|
|
ScheduleSaveResult build() {
|
|
final errors = <String, String>{};
|
|
void fail(String field, String message) =>
|
|
errors.putIfAbsent(field, () => message);
|
|
|
|
final selectedPipeline = source?.pipelineId ?? pipelineId;
|
|
if (!_validIdentity(selectedPipeline)) {
|
|
fail('pipelineId', 'Choose a valid pipeline.');
|
|
}
|
|
if (source != null &&
|
|
(!_validIdentity(source!.id) || !_validIdentity(source!.revision))) {
|
|
fail(
|
|
'record',
|
|
'Schedule identity or revision is missing. Refresh before editing.',
|
|
);
|
|
}
|
|
|
|
if (name.trim().isEmpty) fail('name', 'Enter a schedule name.');
|
|
if (prompt.trim().isEmpty) fail('prompt', 'Enter a prompt.');
|
|
final pinned = int.tryParse(version);
|
|
if (!_digits.hasMatch(version) ||
|
|
pinned == null ||
|
|
pinned < 1 ||
|
|
pinned > _maxSafeInteger) {
|
|
fail('version', 'Choose a positive pinned version, not latest (0).');
|
|
}
|
|
if (!workspace.startsWith('/') || _workspaceBreaks.hasMatch(workspace)) {
|
|
fail('workspace', 'Enter an absolute workspace path on the server.');
|
|
}
|
|
if (!const {'auto', 'on', 'off'}.contains(notifyMode)) {
|
|
fail('notifyMode', 'Choose a notification mode.');
|
|
}
|
|
if (days.any((day) => !scheduleDays.contains(day)) ||
|
|
days.toSet().length != days.length) {
|
|
fail('days', 'Choose valid, distinct weekdays.');
|
|
}
|
|
List<String>? clock;
|
|
if (mode == ScheduleTimerMode.interval) {
|
|
if (!_validDuration(every)) {
|
|
fail(
|
|
'every',
|
|
'Interval must be at least 1m (for example 24h or 1h30m).',
|
|
);
|
|
}
|
|
} else {
|
|
clock = [for (final time in times.split(',')) time.trim()];
|
|
if (clock.any((time) => !_timeOfDay.hasMatch(time)) ||
|
|
clock.toSet().length != clock.length) {
|
|
fail('times', 'Enter distinct 24-hour times, such as 09:00, 17:30.');
|
|
}
|
|
}
|
|
if (!_validTimezone(timezone.trim())) {
|
|
fail('timezone', 'Enter a valid IANA timezone.');
|
|
}
|
|
if (errors.isNotEmpty) return ScheduleSaveResult(null, errors);
|
|
|
|
final record = source?.toJson() ?? <String, dynamic>{};
|
|
if (source == null) record['id'] = 0;
|
|
record['name'] = name.trim();
|
|
record['pipeline_id'] = selectedPipeline;
|
|
record['version'] = pinned;
|
|
record['enabled'] = enabled;
|
|
record['input'] = (source?.input ?? <String, dynamic>{})
|
|
..['prompt'] = prompt;
|
|
// Untrimmed like `workspace: draft.workspace`; validation also runs on the
|
|
// untrimmed value, so a valid workspace is sent exactly as the operator
|
|
// entered it.
|
|
record['workspace'] = workspace;
|
|
|
|
final rule = source?.rule.toJson() ?? <String, dynamic>{};
|
|
for (final key in const ['every', 'times', 'days', 'timezone']) {
|
|
rule.remove(key);
|
|
}
|
|
if (mode == ScheduleTimerMode.interval) {
|
|
rule['every'] = every.trim();
|
|
} else {
|
|
rule['times'] = clock;
|
|
}
|
|
if (days.isNotEmpty) {
|
|
final prior = source?.rule.days ?? const <String>[];
|
|
final unchanged =
|
|
prior.length == days.length && prior.every(days.contains);
|
|
rule['days'] = unchanged ? [...prior] : [...days];
|
|
}
|
|
if (timezone.trim().isNotEmpty) rule['timezone'] = timezone.trim();
|
|
record['rule'] = rule;
|
|
record['notify_mode'] = notifyMode;
|
|
return ScheduleSaveResult(record, const {});
|
|
}
|
|
}
|
|
|
|
const _maxSafeInteger = 9007199254740991;
|
|
bool _validIdentity(int? value) =>
|
|
value != null && value > 0 && value <= _maxSafeInteger;
|
|
final _digits = RegExp(r'^\d+$');
|
|
final _timeOfDay = RegExp(r'^([01]\d|2[0-3]):[0-5]\d$');
|
|
final _workspaceBreaks = RegExp(r'[\x00\r\n]');
|
|
final _zonePart = RegExp(r'^[A-Za-z0-9_+\-]+$');
|
|
const _durationPart = r'((?:\d+(?:\.\d*)?|\.\d+))(ms|us|µs|ns|h|m|s)';
|
|
final _areas =
|
|
'Africa America Antarctica Arctic Asia Atlantic Australia '
|
|
'Brazil Canada Chile Etc Europe Indian Mexico Pacific US'
|
|
.split(' ');
|
|
final _singleZones =
|
|
'UTC GMT UCT Zulu Universal Greenwich CET EET EST HST '
|
|
'MST WET GB NZ PRC ROC ROK W-SU Egypt Eire Iceland Iran Israel Jamaica '
|
|
'Japan Kwajalein Libya Navajo Poland Portugal Singapore Turkey Cuba '
|
|
'Hongkong'
|
|
.split(' ');
|
|
|
|
double? _unit(String unit) => switch (unit) {
|
|
'h' => 3600000,
|
|
'm' => 60000,
|
|
's' => 1000,
|
|
'ms' => 1,
|
|
'us' || 'µs' => .001,
|
|
'ns' => .000001,
|
|
_ => null,
|
|
};
|
|
|
|
/// Go-style compound duration, at least one minute, as the web client accepts.
|
|
bool _validDuration(String text) {
|
|
final every = text.trim();
|
|
final parts = RegExp(_durationPart).allMatches(every).toList();
|
|
final duration = parts.fold<double>(
|
|
0,
|
|
(sum, part) => sum + double.parse(part[1]!) * _unit(part[2]!)!,
|
|
);
|
|
return parts.map((part) => part[0]!).join() == every &&
|
|
duration.isFinite &&
|
|
duration >= 60000;
|
|
}
|
|
|
|
/// Structural IANA check. Dart carries no timezone database, so a known area
|
|
/// plus a well-formed location is the strongest pure check; the server stays
|
|
/// the final validator.
|
|
bool _validTimezone(String value) {
|
|
if (value.isEmpty || value == 'Local' || _singleZones.contains(value)) {
|
|
return true;
|
|
}
|
|
final parts = value.split('/');
|
|
return parts.length > 1 &&
|
|
_areas.contains(parts.first) &&
|
|
parts.every(_zonePart.hasMatch);
|
|
}
|