#include #include #include #include #include #include #include namespace Void::Scheduler { namespace { // Howard Hinnant's exact civil-from-days / days-from-civil algorithms. [[nodiscard]] constexpr std::int64_t days_from_civil(std::int32_t y, std::uint32_t m, std::uint32_t d) noexcept { const std::int64_t y_adj = static_cast(y) - (m <= 2); const std::int64_t era = (y_adj >= 0 ? y_adj : y_adj - 399) / 400; const auto yoe = static_cast(y_adj - era * 400); // [0, 399] const std::uint64_t doy = (153U * (m + (m > 2 ? static_cast(-3) : 9U)) + 2U) / 5U + d - 1U; // [0, 365] const std::uint64_t doe = yoe * 365U + yoe / 4U - yoe / 100U + doy; // [0, 146096] return era * 146097 + static_cast(doe) - 719468; } [[nodiscard]] constexpr bool is_leap_year(std::int32_t y) noexcept { return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0); } [[nodiscard]] constexpr std::uint32_t days_in_month(std::int32_t y, std::uint32_t m) noexcept { switch (m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31U; case 4: case 6: case 9: case 11: return 30U; case 2: return is_leap_year(y) ? 29U : 28U; default: return 30U; } } [[nodiscard]] std::optional parse_fixed_offset_minutes(std::string_view tz) noexcept { if (tz == "UTC" || tz == "Z") { return 0; } if (tz.starts_with("UTC")) { tz.remove_prefix(3U); } if (tz.size() != 6U || (tz[0] != '+' && tz[0] != '-') || tz[3] != ':') { return std::nullopt; } const int sign = tz[0] == '-' ? -1 : 1; std::uint32_t hh = 0; std::uint32_t mm = 0; auto r1 = std::from_chars(tz.data() + 1, tz.data() + 3, hh); auto r2 = std::from_chars(tz.data() + 4, tz.data() + 6, mm); if (r1.ec != std::errc{} || r1.ptr != tz.data() + 3 || r2.ec != std::errc{} || r2.ptr != tz.data() + 6 || hh > 14U || mm > 59U || (hh == 14U && mm > 0U)) { return std::nullopt; } return sign * static_cast(hh * 60U + mm); } [[nodiscard]] Result parse_field(std::string_view field, std::uint32_t min_val, std::uint32_t max_val, bool map_7_to_0 = false) { if (field.empty()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar empty field")); } std::uint64_t mask = 0; std::size_t pos = 0; while (pos <= field.size()) { const std::size_t comma = field.find(',', pos); const std::string_view part = comma == std::string_view::npos ? field.substr(pos) : field.substr(pos, comma - pos); if (part.empty()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar empty list item")); } std::string_view range_part = part; std::uint32_t step = 1; if (const std::size_t slash = part.find('/'); slash != std::string_view::npos) { range_part = part.substr(0, slash); const std::string_view step_sv = part.substr(slash + 1); if (step_sv.empty() || step_sv.find('/') != std::string_view::npos) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar invalid step syntax")); } auto sr = std::from_chars( step_sv.data(), step_sv.data() + step_sv.size(), step); if (sr.ec != std::errc{} || sr.ptr != step_sv.data() + step_sv.size() || step == 0U) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar step must be positive")); } } std::uint32_t lo = min_val; std::uint32_t hi = max_val; const std::uint32_t parse_max = map_7_to_0 ? 7U : max_val; if (range_part == "*") { lo = min_val; hi = max_val; } else if (const std::size_t dash = range_part.find('-'); dash != std::string_view::npos) { const std::string_view a_sv = range_part.substr(0, dash); const std::string_view b_sv = range_part.substr(dash + 1); if (a_sv.empty() || b_sv.empty() || b_sv.find('-') != std::string_view::npos) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar invalid range syntax")); } auto r1 = std::from_chars( a_sv.data(), a_sv.data() + a_sv.size(), lo); auto r2 = std::from_chars( b_sv.data(), b_sv.data() + b_sv.size(), hi); if (r1.ec != std::errc{} || r1.ptr != a_sv.data() + a_sv.size() || r2.ec != std::errc{} || r2.ptr != b_sv.data() + b_sv.size() || lo < min_val || hi > parse_max || lo > hi) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar range bounds invalid")); } } else { std::uint32_t val = 0; auto rv = std::from_chars( range_part.data(), range_part.data() + range_part.size(), val); if (rv.ec != std::errc{} || rv.ptr != range_part.data() + range_part.size() || val < min_val || val > parse_max) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar field value out of range")); } lo = val; hi = (part.find('/') != std::string_view::npos) ? max_val : val; } for (std::uint32_t v = lo; v <= hi; v += step) { const std::uint32_t bit = (map_7_to_0 && v == 7U) ? 0U : v; mask |= (1ULL << bit); if (hi - v < step) { break; } } if (comma == std::string_view::npos) { break; } pos = comma + 1; } if (mask == 0ULL) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::Calendar field matched zero values")); } return mask; } } // namespace std::int64_t civil_to_epoch_minute(std::int32_t year, std::uint32_t month, std::uint32_t day, std::uint32_t hour, std::uint32_t minute) noexcept { const std::int64_t days = days_from_civil(year, month, day); return days * 1440LL + static_cast(hour) * 60LL + static_cast(minute); } CivilMinute epoch_minute_to_civil(std::int64_t epoch_minute) noexcept { std::int64_t days = epoch_minute / 1440LL; std::int64_t rem = epoch_minute % 1440LL; if (rem < 0) { rem += 1440LL; --days; } const auto hour = static_cast(rem / 60LL); const auto minute = static_cast(rem % 60LL); const std::int64_t z = days + 719468; const std::int64_t era = (z >= 0 ? z : z - 146096) / 146097; const auto doe = static_cast(z - era * 146097); // [0, 146096] const std::uint64_t yoe = (doe - doe / 1460U + doe / 36524U - doe / 146096U) / 365U; // [0, 399] const std::int64_t y = static_cast(yoe) + era * 400; const std::uint64_t doy = doe - (365U * yoe + yoe / 4U - yoe / 100U); // [0, 365] const std::uint64_t mp = (5U * doy + 2U) / 153U; // [0, 11] const auto d = static_cast( doy - (153U * mp + 2U) / 5U + 1U); // [1, 31] const auto m = static_cast(mp < 10U ? mp + 3U : mp - 9U); // [1, 12] const auto year = static_cast(y + (m <= 2U ? 1 : 0)); // 1970-01-01 was Thursday (4). std::int64_t wd = (days + 4LL) % 7LL; if (wd < 0) { wd += 7LL; } return CivilMinute{ .year = year, .month = m, .day = d, .hour = hour, .minute = minute, .weekday = static_cast(wd), }; } // ── TimezoneRegistry ────────────────────────────────────────────────────── void TimezoneRegistry::register_dst_zone(DstTransitionRule rule) { if (!rule.name.empty()) { m_dst_zones[rule.name] = std::move(rule); } } Result TimezoneRegistry::validate_timezone(std::string_view tz) const { if (parse_fixed_offset_minutes(tz).has_value() || m_dst_zones.contains(tz)) { return {}; } return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::UnsupportedTimezone, "Scheduler: unsupported or unknown timezone '" + std::string{tz} + "' (silent UTC fallback is forbidden)")); } Result> TimezoneRegistry::resolve_local_minute( std::string_view tz, std::int64_t local_epoch_minute, DstGapPolicy gap_policy, DstFoldPolicy fold_policy) const { if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) { const std::int64_t utc_min = local_epoch_minute - static_cast(*fixed); return std::vector{ ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}}; } auto it = m_dst_zones.find(tz); if (it == m_dst_zones.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::UnsupportedTimezone, "Scheduler: unsupported timezone '" + std::string{tz} + "'")); } const auto& rule = it->second; // Check spring-forward gap window. if (rule.gap_start_local_min.has_value() && rule.gap_end_local_min.has_value() && local_epoch_minute >= *rule.gap_start_local_min && local_epoch_minute < *rule.gap_end_local_min) { if (gap_policy == DstGapPolicy::Skip) { return std::vector{}; } const std::int64_t shifted_utc_min = *rule.gap_end_local_min - static_cast(rule.dst_offset_minutes); return std::vector{ResolvedSlot{ .utc_ms = shifted_utc_min * 60000LL, .fold_index = 0, }}; } // Check fall-back fold window. if (rule.fold_start_local_min.has_value() && rule.fold_end_local_min.has_value() && local_epoch_minute >= *rule.fold_start_local_min && local_epoch_minute < *rule.fold_end_local_min) { const std::int64_t first_utc_min = local_epoch_minute - static_cast(rule.dst_offset_minutes); const std::int64_t second_utc_min = local_epoch_minute - static_cast(rule.standard_offset_minutes); switch (fold_policy) { case DstFoldPolicy::First: return std::vector{ResolvedSlot{ .utc_ms = first_utc_min * 60000LL, .fold_index = 0}}; case DstFoldPolicy::Second: return std::vector{ResolvedSlot{ .utc_ms = second_utc_min * 60000LL, .fold_index = 1}}; case DstFoldPolicy::Twice: return std::vector{ ResolvedSlot{.utc_ms = first_utc_min * 60000LL, .fold_index = 0}, ResolvedSlot{.utc_ms = second_utc_min * 60000LL, .fold_index = 1}, }; } } // Outside gap/fold: determine whether DST or standard offset applies. bool in_dst = false; if (rule.gap_end_local_min.has_value() && rule.fold_start_local_min.has_value()) { in_dst = (local_epoch_minute >= *rule.gap_end_local_min && local_epoch_minute < *rule.fold_start_local_min); } else if (rule.gap_end_local_min.has_value()) { in_dst = (local_epoch_minute >= *rule.gap_end_local_min); } const std::int32_t off = in_dst ? rule.dst_offset_minutes : rule.standard_offset_minutes; const std::int64_t utc_min = local_epoch_minute - static_cast(off); return std::vector{ ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}}; } Result> TimezoneRegistry::local_minute_bounds(std::string_view tz, std::int64_t utc_min_lo, std::int64_t utc_min_hi) const { if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) { return std::pair{utc_min_lo + *fixed, utc_min_hi + *fixed}; } auto it = m_dst_zones.find(tz); if (it == m_dst_zones.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::UnsupportedTimezone, "Scheduler: unsupported timezone '" + std::string{tz} + "'")); } const std::int32_t min_off = std::min(it->second.standard_offset_minutes, it->second.dst_offset_minutes); const std::int32_t max_off = std::max(it->second.standard_offset_minutes, it->second.dst_offset_minutes); return std::pair{utc_min_lo + min_off - 120LL, utc_min_hi + max_off + 120LL}; } // ── CalendarExpression ──────────────────────────────────────────────────── Result CalendarExpression::parse(std::string_view expression) { std::vector tokens; std::size_t i = 0; while (i < expression.size()) { while (i < expression.size() && (expression[i] == ' ' || expression[i] == '\t')) { ++i; } if (i >= expression.size()) { break; } const std::size_t start = i; while (i < expression.size() && expression[i] != ' ' && expression[i] != '\t') { ++i; } tokens.push_back(expression.substr(start, i - start)); } if (tokens.size() != 5U) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler::CalendarExpression requires exactly 5 fields " "(minute hour day month weekday)")); } auto min_m = parse_field(tokens[0], 0, 59); if (!min_m.has_value()) return Void::Result::fail(min_m.error()); auto hr_m = parse_field(tokens[1], 0, 23); if (!hr_m.has_value()) return Void::Result::fail(hr_m.error()); auto day_m = parse_field(tokens[2], 1, 31); if (!day_m.has_value()) return Void::Result::fail(day_m.error()); auto mon_m = parse_field(tokens[3], 1, 12); if (!mon_m.has_value()) return Void::Result::fail(mon_m.error()); auto wd_m = parse_field(tokens[4], 0, 6, true); if (!wd_m.has_value()) return Void::Result::fail(wd_m.error()); CalendarExpression expr{}; expr.m_minutes = *min_m; expr.m_hours = static_cast(*hr_m); expr.m_days = static_cast(*day_m); expr.m_months = static_cast(*mon_m); expr.m_weekdays = static_cast(*wd_m); return expr; } bool CalendarExpression::matches(const CivilMinute& cm) const noexcept { return ((m_minutes & (1ULL << cm.minute)) != 0ULL) && ((m_hours & (1U << cm.hour)) != 0U) && ((m_days & (1U << cm.day)) != 0U) && ((m_months & (1U << cm.month)) != 0U) && ((m_weekdays & (1U << cm.weekday)) != 0U); } std::optional CalendarExpression::next_matching_minute( std::int64_t from_local_min, std::int64_t max_local_min) const noexcept { if (from_local_min > max_local_min) { return std::nullopt; } std::int64_t cur = from_local_min; // Guard iteration count against unsatisfiable combinations (e.g. Feb 31). for (int guard = 0; guard < 100000 && cur <= max_local_min; ++guard) { const CivilMinute cm = epoch_minute_to_civil(cur); if ((m_months & (1U << cm.month)) == 0U) { std::int32_t ny = cm.year; std::uint32_t nm = cm.month + 1U; if (nm > 12U) { nm = 1U; ++ny; } cur = civil_to_epoch_minute(ny, nm, 1U, 0U, 0U); continue; } if ((m_days & (1U << cm.day)) == 0U || (m_weekdays & (1U << cm.weekday)) == 0U) { // Jump to 00:00 of next day. const std::int64_t next_day_min = civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) + 1440LL; cur = next_day_min; continue; } if ((m_hours & (1U << cm.hour)) == 0U) { const std::int64_t next_hr_min = civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour, 0U) + 60LL; cur = next_hr_min; continue; } if ((m_minutes & (1ULL << cm.minute)) == 0U) { ++cur; continue; } return cur; } return std::nullopt; } std::optional CalendarExpression::prev_matching_minute( std::int64_t from_local_min, std::int64_t min_local_min) const noexcept { if (from_local_min < min_local_min) { return std::nullopt; } std::int64_t cur = from_local_min; for (int guard = 0; guard < 100000 && cur >= min_local_min; ++guard) { const CivilMinute cm = epoch_minute_to_civil(cur); if ((m_months & (1U << cm.month)) == 0U) { std::int32_t py = cm.year; std::uint32_t pm = cm.month - 1U; if (pm == 0U) { pm = 12U; --py; } cur = civil_to_epoch_minute(py, pm, days_in_month(py, pm), 23U, 59U); continue; } if ((m_days & (1U << cm.day)) == 0U || (m_weekdays & (1U << cm.weekday)) == 0U) { // Jump to 23:59 of previous day. cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) - 1LL; continue; } if ((m_hours & (1U << cm.hour)) == 0U) { cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour, 0U) - 1LL; continue; } if ((m_minutes & (1ULL << cm.minute)) == 0U) { --cur; continue; } return cur; } return std::nullopt; } Result CalendarExpression::materialize_range( const CalendarSpec& spec, const TimezoneRegistry& tz_registry, std::int64_t after_utc_ms, std::int64_t up_to_utc_ms, MisfirePolicy misfire, std::size_t max_catch_up) const { if (auto tz_ok = tz_registry.validate_timezone(spec.timezone); !tz_ok.has_value()) { return Void::Result::fail(tz_ok.error()); } MaterializedSlots out{}; out.next_cursor_utc_ms = after_utc_ms; if (up_to_utc_ms <= after_utc_ms) { return out; } const std::int64_t utc_min_lo = after_utc_ms / 60000LL - 1LL; const std::int64_t utc_min_hi = up_to_utc_ms / 60000LL + 1LL; auto bounds = tz_registry.local_minute_bounds(spec.timezone, utc_min_lo, utc_min_hi); if (!bounds.has_value()) { return Void::Result::fail(bounds.error()); } const auto [local_lo, local_hi] = *bounds; if (misfire == MisfirePolicy::Skip) { out.next_cursor_utc_ms = up_to_utc_ms; return out; } if (misfire == MisfirePolicy::CoalesceLatest) { // Scan backward from local_hi to coalesce arbitrarily many missed // slots (even millions) in bounded O(1) jumps! std::int64_t probe = local_hi; std::optional best{}; while (probe >= local_lo) { auto found = prev_matching_minute(probe, local_lo); if (!found.has_value()) { break; } auto resolved = tz_registry.resolve_local_minute( spec.timezone, *found, spec.gap_policy, spec.fold_policy); if (!resolved.has_value()) { return Void::Result::fail(resolved.error()); } for (const auto& slot : *resolved) { if (slot.utc_ms > after_utc_ms && slot.utc_ms <= up_to_utc_ms) { if (!best.has_value() || slot.utc_ms > best->utc_ms || (slot.utc_ms == best->utc_ms && slot.fold_index > best->fold_index)) { best = slot; } } } if (best.has_value()) { break; } probe = *found - 1LL; } if (best.has_value()) { out.slots.push_back(*best); } out.next_cursor_utc_ms = up_to_utc_ms; return out; } // CatchUpBounded: scan forward up to `max_catch_up` slots, preserving // remaining cursor state when more slots remain! const std::size_t cap = max_catch_up > 0U ? max_catch_up : 1U; std::int64_t probe = local_lo; while (probe <= local_hi) { auto found = next_matching_minute(probe, local_hi); if (!found.has_value()) { break; } auto resolved = tz_registry.resolve_local_minute( spec.timezone, *found, spec.gap_policy, spec.fold_policy); if (!resolved.has_value()) { return Void::Result::fail(resolved.error()); } for (const auto& slot : *resolved) { if (slot.utc_ms > after_utc_ms && slot.utc_ms <= up_to_utc_ms) { if (out.slots.size() < cap) { out.slots.push_back(slot); out.next_cursor_utc_ms = std::max(out.next_cursor_utc_ms, slot.utc_ms); } else { out.more_pending = true; return out; } } } probe = *found + 1LL; } out.next_cursor_utc_ms = up_to_utc_ms; return out; } } // namespace Void::Scheduler