Files
meshcore-bot/modules/scheduled_message_admin.py
T
agessaman 7af1f46fdd fix(scheduler): close the gaps the second review round found
- An end date closes at the last second before the next local day begins, worked out in UTC. "23:59:59" did not exist on a day whose DST change skips the last hour (America/Nuuk, 2027-03-27), and APScheduler moved it past midnight, letting the schedule fire on the following date.
- APScheduler reads "last" and the ordinals as prefixes, so "last--fri", "lastfri" or "last-" quietly meant the last day of the month. Anything starting with an ordinal must now be "last" or a full positional day. A positional day combined with a day-of-week ("1st-tue * mon") never matches and is rejected.
- A schedule with no future run is invalid in the editor and skipped with a reason at startup, not only when it has date bounds.
- An option with nothing after it ("start=2027-01-01") gets its own error, and a channel that would read as week= is refused like start= and end=.
- The editor resets every builder control on each open, so a new entry no longer inherits the last edited entry's days or monthly choice, and it recognizes the several-times-a-day and every-N modes when reopening an entry. The preview runs the save-time entry checks once channel and message are filled in. With one day a month, a note explains that Weeks skips most months.
- The every-other-week docs example no longer repeats an INI key, a weather-service link follows the moved section, and the changelog says plainly that a key written as last-fri changes meaning: it used to run on the month's last day.
2026-11-04 19:41:50 -08:00

316 lines
12 KiB
Python

#!/usr/bin/env python3
"""Read/validate/compose ``[Scheduled_Messages]`` entries for the web viewer.
The bot's schedules live in ``config.ini`` and are applied by
:meth:`modules.scheduler.MessageScheduler.setup_scheduled_messages`, which
``reload_config()`` re-runs — so edits take effect without a restart and there is
no second store to keep in sync.
Everything here validates through the same parsers the scheduler uses
(:mod:`modules.scheduled_message_cron`), so the UI can never accept a schedule the
bot would then reject at startup.
"""
from __future__ import annotations
import configparser
import datetime
from typing import Any
from .scheduled_message_cron import (
bounds_error,
parse_schedule_key,
parse_scheduled_message_value,
split_schedule_options,
week_error,
)
SECTION = "Scheduled_Messages"
# Mirrors MessageScheduler.MIN_COMMAND_PLACEHOLDER_INTERVAL_SECONDS. Imported lazily
# in _min_interval_floor() to avoid importing the scheduler (and APScheduler's
# background machinery) into the web viewer process just for a constant.
_COMMAND_PLACEHOLDER = "{cmd:"
def _min_interval_floor() -> int:
from .scheduler import MessageScheduler
return int(MessageScheduler.MIN_COMMAND_PLACEHOLDER_INTERVAL_SECONDS)
def _min_fire_interval_seconds(trigger: Any, tz: Any, samples: int = 12) -> float | None:
"""Smallest gap between consecutive firings, measured the way the scheduler does."""
from .scheduler import MessageScheduler
return MessageScheduler._min_fire_interval_seconds(trigger, tz, samples)
def next_run_times(trigger: Any, tz: Any, count: int = 5) -> list[str]:
"""Next *count* firing times as ISO strings, for previewing a schedule."""
if trigger is None:
return []
out: list[str] = []
previous = trigger.get_next_fire_time(None, datetime.datetime.now(tz))
while previous is not None and len(out) < count:
out.append(previous.isoformat())
previous = trigger.get_next_fire_time(
previous, previous + datetime.timedelta(microseconds=1)
)
return out
def describe_schedule(
schedule: str,
tz: Any,
message: str = "",
count: int = 5,
start: str | None = None,
end: str | None = None,
week: str | None = None,
) -> dict[str, Any]:
"""Validate a schedule key and describe when it would fire.
Args:
schedule: The raw key an operator typed, e.g. ``0 6,12,18 * * *`` or ``@daily``.
tz: Timezone the bot schedules in.
message: Message body, only needed to apply the ``{cmd:...}`` airtime floor.
count: How many upcoming runs to return.
start: Optional ISO date the schedule starts on (from the entry's value).
end: Optional ISO date it runs through, inclusive.
week: Optional ISO week-number expression (``*/2`` for every other week).
Returns:
``valid``, a human ``label``, ``next_runs``, ``interval_seconds`` (tightest gap),
``deprecated`` for the legacy HHMM form, and ``error`` when unusable.
"""
raw = (schedule or "").strip()
if not raw:
return {"valid": False, "error": "Schedule is required", "next_runs": []}
# Same check the save path runs, so the preview never calls a window valid that
# saving would refuse.
window_error = bounds_error(start, end) or week_error(week)
if window_error:
return {"valid": False, "error": window_error, "next_runs": []}
try:
parsed = parse_schedule_key(raw, tz, start, end, week)
except Exception as exc: # noqa: BLE001 - any parser error is just an invalid schedule
return {"valid": False, "error": f"Could not parse schedule: {exc}", "next_runs": []}
if parsed.trigger is None:
reason = f" ({parsed.error})" if parsed.error else ""
return {
"valid": False,
"error": (
"Not a valid schedule. Use 5-field cron (minute hour day-of-month "
"month day-of-week), a positional day-of-month such as last-fri or "
f"4th-tue, or a preset like @daily or @hourly.{reason}"
),
"next_runs": [],
}
interval = _min_fire_interval_seconds(parsed.trigger, tz)
result: dict[str, Any] = {
"valid": True,
"label": parsed.display_label,
"next_runs": next_run_times(parsed.trigger, tz, count),
"interval_seconds": interval,
"deprecated": bool(parsed.is_deprecated_hhmm),
"error": None,
}
warnings: list[str] = []
if parsed.is_deprecated_hhmm:
warnings.append(
f"{raw} is the deprecated HHMM form and will stop working in a future "
"release. Use 5-field cron instead."
)
if not result["next_runs"]:
if start or end:
# Well-formed, just outside its window -- distinct from a malformed schedule.
result["finished"] = True
warnings.append(
f"This schedule has no runs left: it is bounded to "
f"{start or 'any date'} .. {end or 'any date'}."
)
else:
# e.g. "0 0 30 feb *": parses, but no date ever matches.
return {
"valid": False,
"error": "This schedule never fires: no date matches every field.",
"next_runs": [],
}
if warnings:
result["warning"] = " ".join(warnings)
# Same floor the scheduler enforces at startup, applied here so the UI refuses it
# up front rather than letting it be saved and silently dropped on reload.
if _COMMAND_PLACEHOLDER in (message or ""):
floor = _min_interval_floor()
if interval is not None and interval < floor:
result["valid"] = False
result["error"] = (
f"A message using {{cmd:...}} may not run more often than every "
f"{floor // 60} minutes; this fires every "
f"{_humanize_seconds(interval)}. Each run costs airtime."
)
return result
def _humanize_seconds(seconds: float) -> str:
seconds = int(seconds)
if seconds % 86400 == 0:
days = seconds // 86400
return f"{days} day{'s' if days != 1 else ''}"
if seconds % 3600 == 0:
hours = seconds // 3600
return f"{hours} hour{'s' if hours != 1 else ''}"
if seconds % 60 == 0:
minutes = seconds // 60
return f"{minutes} minute{'s' if minutes != 1 else ''}"
return f"{seconds} seconds"
def compose_value(
channel: str,
message: str,
scope: str | None = None,
start: str | None = None,
end: str | None = None,
week: str | None = None,
) -> str:
"""Build the config value for an entry, matching parse_scheduled_message_value.
Date bounds and the week filter lead, so they cannot be confused with a message
body, and are read back off by
:func:`~modules.scheduled_message_cron.split_schedule_options`.
"""
channel = (channel or "").strip()
message = (message or "").strip()
scope = (scope or "").strip()
starts_on = (start or "").strip()
ends_on = (end or "").strip()
weeks = (week or "").strip()
prefix = ""
if starts_on:
prefix += f"start={starts_on} "
if ends_on:
prefix += f"end={ends_on} "
if weeks:
prefix += f"week={weeks} "
if scope:
if not scope.startswith("#"):
scope = f"#{scope}"
return f"{prefix}{channel}:{scope}:{message}"
return f"{prefix}{channel}:{message}"
def validate_entry(
channel: str,
message: str,
scope: str | None,
start: str | None = None,
end: str | None = None,
week: str | None = None,
) -> str | None:
"""Return an error string for an unusable entry, or None when it is fine."""
starts_on = (start or "").strip()
ends_on = (end or "").strip()
weeks = (week or "").strip()
window_error = bounds_error(starts_on or None, ends_on or None) or week_error(weeks or None)
if window_error:
return window_error
if not (channel or "").strip():
return "Channel is required"
if not (message or "").strip():
return "Message is required"
if ":" in (channel or ""):
return "Channel cannot contain ':'"
if scope and ":" in scope:
return "Scope cannot contain ':'"
# The INI writer rejects these outright; catching them here gives a better message.
for field, value in (("channel", channel), ("message", message), ("scope", scope or "")):
if "\n" in value or "\r" in value:
return f"The {field} cannot contain line breaks (use \\n for a mesh line break)"
# What is written has to read back as what was submitted. A channel that looks like
# a date bound, or a message that looks like a scope ("#net: tonight" with no
# scope), would otherwise save and then run as something else.
try:
read_start, read_end, read_week, rest = split_schedule_options(
compose_value(channel, message, scope, starts_on, ends_on, weeks)
)
read_back = (read_start, read_end, *parse_scheduled_message_value(rest))
if read_week != (weeks or None):
return "The channel name cannot start with start=, end= or week="
except ValueError as exc:
return f"This entry would not read back as written: {exc}"
expected_scope = None
if (scope or "").strip():
expected_scope = (scope or "").strip()
if not expected_scope.startswith("#"):
expected_scope = f"#{expected_scope}"
expected = (starts_on or None, ends_on or None, channel.strip(), message.strip(), expected_scope)
if read_back != expected:
if read_back[2] != expected[2] or read_back[:2] != expected[:2]:
return "The channel name cannot start with start=, end= or week="
return (
"With no scope set, the message cannot start with #name: "
"(it would be read as a scope). Set the scope, or reword the start."
)
return None
def read_entries(config_path: str, tz: Any) -> list[dict[str, Any]]:
"""Read every ``[Scheduled_Messages]`` entry from disk, described for the UI.
Reads the file rather than a cached ConfigParser so the list reflects what was
just written. Malformed rows are returned with an ``error`` instead of being
hidden, since a row the bot is skipping is exactly what an operator needs to see.
"""
# Default optionxform (lower-casing) on purpose: the bot reads this section with a
# plain ConfigParser, so the UI must show the same keys the scheduler registers.
# ini_writer matches keys case-insensitively, so edits and deletes still line up.
parser = configparser.ConfigParser(interpolation=None)
try:
parser.read(config_path, encoding="utf-8")
except (OSError, configparser.Error):
return []
if not parser.has_section(SECTION):
return []
entries: list[dict[str, Any]] = []
for schedule, raw_value in parser.items(SECTION):
entry: dict[str, Any] = {
"schedule": schedule,
"raw_value": raw_value,
"channel": "",
"scope": None,
"message": "",
"start": None,
"end": None,
"week": None,
}
try:
start, end, week, rest = split_schedule_options(raw_value)
channel, message, scope = parse_scheduled_message_value(rest)
entry.update(
channel=channel, message=message, scope=scope, start=start, end=end,
week=week,
)
except ValueError as exc:
# Keep the same shape as a described entry so callers never have to
# special-case a malformed row to find out it is not running.
entry["valid"] = False
entry["error"] = f"Malformed value: {exc}"
entry["next_runs"] = []
entries.append(entry)
continue
entry.update(
describe_schedule(
schedule, tz, message=message, start=start, end=end, week=week
)
)
entries.append(entry)
return entries